Amateur python user here;
I am creating a program that takes 500 randomized numbers, and counts how many there are of each number ranging from 0-9, then prints a chart that shows how many times each number occurred. I initially created a working program that accomplished this, however the criteria for this program is that I have to use a fruitful function to get a randomized number and return it, which I am having trouble doing. This is the main code I am having trouble with:
symbol = 0
while timesRun != 500:
timesRun = 1
genRandom(symbol)
if symbol == 0:
zero = 1
elif symbol == 1:
one = 1
elif symbol == 2:
two = 1
elif symbol == 3:
three = 1
elif symbol == 4:
four = 1
elif symbol == 5:
five = 1
elif symbol == 6:
six = 1
elif symbol == 7:
seven = 1
elif symbol == 8:
eight = 1
elif symbol == 9:
nine = 1
And this is the function for the while loop, minus the entirety of the other elif statements and else statement, just to save your reading time:
def genRandom(letter):
ranNum = randint(0,9)
allNumbers.append(ranNum)
if ranNum == 0:
letter = 0
return letter
When I print genRandom(symbol), it does return a 500 random numbers line by line, however when I check the if statements (if symbol ==1:, etc...), it only uses the global symbol and not the argument I sent. When I print my chart, the output looks like this:
Number | Occurrences
-------------------------------
0 | 0
1 | 0
2 | 0
3 | 0
4 | 0
5 | 0
6 | 0
7 | 0
8 | 0
9 | 0
What is the best fix for this?
Thanks in advance
CodePudding user response:
When you call genRandom(symbol)
, you are assuming that symbol
will be modified with the new value. Python doesn't work that way. The only thing you get back from a function is what it returns: symbol = genRandom()
.
However, there's a better way to do what you are doing:
counts = [0]*10
for _ in range(500):
num = randint(0,9)
counts[num] = 1
print(counts)
CodePudding user response:
Here's your obligatory one-liner:
import collections
import random
print( collections.Counter(random.randint(0,9) for _ in range(500)) )
I am obviously being smug, but here's a walk-though:
collections.Counter does exactly the thing you're trying to do. It takes an iterable and counts how many times that "thing" occurs.
random.randint is another "batteries included" function that'll give you some random numbers... Don't use it for cryptography.
The other magic in there is that argument I've passed to the Counter's constructor. The (f() for _ in range(N))
is called a List Comprehension ("https://www.geeksforgeeks.org/python-list-comprehension/") and is a one-line for-loop. It means do f()
for every _
(pythonic way to say "I'm not going to use this value") in the range
of [0..N), and return them as an iterable.