Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Summing the 1s from a list in python

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)

        
    

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading