![]() |
| Beginner at Python. Trying to count certain integer from random string of code - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Beginner at Python. Trying to count certain integer from random string of code (/thread-21777.html) |
Beginner at Python. Trying to count certain integer from random string of code - kiaspelleditwrong - Oct-14-2019 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! RE: Beginner at Python. Trying to count certain integer from random string of code - perfringo - Oct-14-2019 Python strings have method .count() for counting purpose: >>> s = '1100101' >>> s.count('1') 4 RE: Beginner at Python. Trying to count certain integer from random string of code - Malt - Oct-14-2019 (Oct-14-2019, 05:38 AM)perfringo Wrote: Python strings have method .count() for counting purpose: It is working for list as well >>> s=['1','0','1','0','1','1','0'] >>> s.count('1') 4 RE: Beginner at Python. Trying to count certain integer from random string of code - perfringo - Oct-14-2019 For counting hashable items there is collections.Counter(). >>> from collections import Counter >>> s = '1100101' >>> Counter(s) Counter({'1': 4, '0': 3}) >>> Counter(s)['1'] 4Writing 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 |