For this problem I’m supposed to generate a user input list with random integers between 1 and 10. Im then supposed to count the occurrences of each integer from 0-10 and print them.
I’m a beginner in code so I’ve been having trouble trying to do the occurrences part and have them print out like this for example
for user_input = 4 if the generated list is [3,5,7,8]
* Output:
0: 0
1: 0
2: 0
3: 1
4: 0
5: 1
6: 0
7: 1
8: 1
9: 0
10: 0
so far this is what I have written any help, references, or examples would help immensely!
import random
def main():
random_list = []
n = int(input('Enter list length: '))
for count in range(n):
number = random.randint(1, 10)
print(number)
main()
the list has to be user generated, for example if they type in 4 for n, a random list of 4 numbers from 0-10 will be shown and my code has to count how many times those 4 random numbers show up from 0-10! also please let me know if I read that second question wrong.
also is the def count part right? or is that what should be replaced with a for loop?
You already wrote a for-loop in your code, but here is an example
for number in range(5):
print(number)
outputs:
0
1
2
3
4
Notice how it is 5 numbers BUT from 0 to 4.
Now you got the numbers from 0 to 10.
As mentioned you are not using the lst so it won’t work.
Apart from that, why bother with it only to return a method-call? Just call the .count() method on the spot.
import random
random_list = []
n = int(input('Enter list length: '))
for count in range(n):
list = random.randint(10)
print(number)
list = []
count = list.count('0',1','2','3','4','5','6','7','8','9')
print(count)
like this? sorry I don’t know much about counts either all of my homework problems have not been based off the content we learn or in the textbook I always have to look up what everything means
Well it’s still quite messy - with declaring random_list but never using it and such.
Do you have an IDE to write and test your code? Then you should be able to see if what you write works or doesn’t and try to go from there.
The idea is that you adress the entries of a list with it’s index, starting at 0.
So lis=[1,2,3] has lis[1]->2 because the 1-index is the second in the list.
If you just want to count random numbers, you can go:
counts = [0]*11
for _ in range(n):
num= random.randint(10)
counts[num] += 1