Python Forum

Full Version: Beginner at Python. Trying to count certain integer from random string of code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I hope my title wasn't too long. I have code to make a random string of numbers; 0 or 1. I want it to count and print how many times 1 appears in the string of numbers. This is what i have so far:
import random
def Rand(Start, end, num):
    res = [ ]

    for j in range (num):
        res.append(random.randint(start, end))

    return res
num = 1000
start = 0
end = 1
pie = (Rand(start, end, num))

def count(lst): 
      
    return sum(lst)

lst = pie
print(count(lst))
I feel that i have no idea if its actually counting whether its 1 or not. I'm kind of figuring there's a better way to do what I'm trying to accomplish. Thanks for helping!
Python strings have method .count() for counting purpose:

>>> s = '1100101'
>>> s.count('1')
4
(Oct-14-2019, 05:38 AM)perfringo Wrote: [ -> ]Python strings have method .count() for counting purpose:

>>> s = '1100101'
>>> s.count('1')
4

It is working for list as well

>>> s=['1','0','1','0','1','1','0']
>>> s.count('1')
4
For counting hashable items there is collections.Counter().

>>> from collections import Counter
>>> s = '1100101'                                                                         
>>> Counter(s)                                                                            
Counter({'1': 4, '0': 3})
>>> Counter(s)['1']
4
Writing your own counter for specific needs is pretty simple. Following is counting even numerics in a string (it will raise ValueError if character is not numeric):

>>> numeric = '23542'
>>> sum(1 for char in numeric if int(char) % 2 == 0)
3