Home > Software engineering >  Summing the 1s from a list in python
Summing the 1s from a list in python

Time:10-12

Given I have the task that I have to count the number of 1s entailed in a list. Upon assessing the prior my code is giving the message "NONE."

What am I doing wrong ?

#alternative: 
result=[]

def count(x):
    for i in enumerate(x):
        if i==1:
            sum(i)
            append.result(i)
            return result 

c = count([1, 4, 5, 1, 3])
print(c)

        
    

CodePudding user response:

l = [1, 4, 5, 1, 3]
l.count(1)

Will output 2.

CodePudding user response:

As Mark mentioned, using enumerate here isn't very helpful, as it creates an index and a value, when in this case, you only care about the value. Since x is already a list, you don't need to use enumerate.

Be careful to wait until after your loop is done to use return in this case, as you're exiting the loop when the first 1 is encountered.

Additionally, be sure that you're actually assigning the value to something, rather than just outputting it. Doing sum(i) doesn't really do anything in this case, especially because you already checked that i==1!

Also, the syntax for adding to a list is x.append(value) where x is the list. There are easier ways to do this, such as with a list comprehension:

def count(x):
    return len([value for value in x if value==1])

Or expanded out:

def count(x):
    result = []
    for value in x:
        if value == 1:
            result.append(value)
    return len(result)

Or generalized for any number n:

def count(x, n):
    result = []
    for value in x:
        if value == n:
            result.append(value)
    return len(result)

And the generalized form as a list comprehension:

def count(x, n):
    return len([value for value in x if value==n])

Additionally, you could use python's built in count function, but I suspect that if this is an assignment of some sort, that may be disallowed, but that can be used like so:

x = [1, 2, 1, 1, 3, 5]
num_1s = x.count(1)
print(str(num_1s))

Which outputs 3

CodePudding user response:

You probably want it like this:

result=[]

def count(x):
    for i in x:
        if i==1:
            result.append(i)
    return len(result) 

c = count([1, 4, 5, 1, 3])
print(c)

Output

2'

Or you could simplify it further by:

def count(x):
    result = 0
    for j, i in enumerate(x):
        if i==1:
            result  =1
    return result

Or, if you want to use pandas, you can write it even more simple:

import pandas as pd

def count(x):
    x = pd.Series(x)
    return x.value_counts().loc[1]

CodePudding user response:

def count(x):
    result = []
    for i,num in enumerate([1,2,3]):
            if num==1:
                #sum(i)
                result.append(num)
            return result
c = count([1, 4, 5, 1, 3])
print(c)

I don't think you are using enumerate properly, also sum(i) is not being stored in memory so it does not do anything. Finally, make sure you append onto your list correctly.

This is my first post so if anything is unclear let me know.

CodePudding user response:

I see 3 three main issues here.

Firstly, the enumerate function allows you to iterate with both the index of the item in the list along with the item itself. For example,

my_list = ["a", "b", "c"]
for index, item in enumerate(my_list):
    print(index, item)

will output

0 a
1 b
2 c

compared to

my_list = ["a", "b", "c"]
for item in my_list:
    print(item)

which will output

a
b
c

If we do

for i in enumerate(my_list):
    print(i)

We get

(0, 'a')
(1, 'b')
(2, 'c')

Meaning you're assigning a bundle (a "tuple") of two values (both the index and the item) to i. So that if check of yours will never be true as you are trying to check whether a bundle of values equals a single value (which it never will). This is why your function is returning None, it never actually gets past the if and as such, never returns anything. This is issue #1, you should just be using

for i in x:
    if i == 1:
        ...

so you can if check only the item.

Now if that if check does succeed and Python moved on to the next line, Python would throw an error as the sum method requires a list of values to be passed to it rather than a single value (the item). This is issue #2, the summing should wait until you have a full list of values.

Now the final issue - the return keyword returns a value from the function and exits it immediately, so if the sum error was avoided, you would still be leaving the function before you finished iterating the list. This is issue #3. You should rather just append to the list and return the sum of it after the iteration is complete.

I think this is more what you were going for:

result=[]

def count(x):
    ones = 0
    for i in x:
        if i == 1:
            result.append(i)
    return sum(result)

Or perhaps without the list:

def count(x):
    ones = 0
    for i in x:
        if i == 1:
            ones = ones   1
    return ones

And for fun a recursive solution:

def count(x):
    if len(x) == 0:
        return 0
    i = x.pop()
    if i == 1:
        return 1   count(x)
    return count(x)
  • Related