0

I have written a code that randomly generated 100 numbers and puts in all in an array. I want to know of a command, or code, that would tell me how many 5's (or any number for that matter) are in the array after it is generated.
This is my code so far>>

import random
x = 1
def rand():
    return random.randrange(0,10,1) #a random number between 0 and 9
myList = []
while (x != 100):
    x=x+1
    y = rand()
    myList.append(y)

and at the end I want a command to give me the number of 5's. Something like>>

getNumber.of(5) from myList

I also want an output that shows location also. Something like>>

7 (5's) at: myList[12], myList[20], myList[27], myList[33], myList[59], myList[74], myList[90]
Carton32
  • 84
  • 5

3 Answers3

0

You can solve this problem with a generator and the builtin sum:

def getNumberOf(candidate, mylist):
    """ Returns the number of appearances of candidate in mylist """
    return sum(1 for number in mylist if number==candidate)

def getPositionOf(candidate, mylist):
    """ Returns a list of indexes where the candidate appears in mylist"""
    return [index for index, value in enumerate(mylist) if value==candidate]
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
0

Given a list of numbers mylist, you can get the positions of the occurrences of 5 with this:

[a for (a,b) in enumerate(mylist) if b == 5]
Zev Chonoles
  • 1,063
  • 9
  • 13
0

Python lists have a count method:

>>> myList = [1,2,3,4,5,5,4,5,6,5]
>>> myList.count(5)
4

This will get you started on the indexes:

>>> start = 0
>>> indexes = []
>>> for _ in xrange(myList.count(5)):
...     i = myList.index(5, start)
...     indexes.append(i)
...     start = i + 1
... 
>>> indexes
[4, 5, 7, 9]
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331