dimanche 23 octobre 2016

Check a random number if is in a list

I have a list that is generated by selecting 10 random number in the range of 0-100, and now I need to let the program to generate random number to hit if it is in the list, if it is, count 1, if it is not, keep checking until hits the target. I need to use the binary serch method

Here is what I have:

import random

rawlist = [0 for n in range(10)]
for n in range(len(rawlist)):
     rawlist[n] = random.randint(0,100)

print "original list-->> ", rawlist

rawlist = [int(x) for x in rawlist]

def sortem(rawlist):
    for x in range(len(rawlist)):
        for y in range(len(rawlist)-1):
            if rawlist[y] > rawlist[y+1]:
                rawlist[y], rawlist[y+1] = rawlist[y+1], rawlist[y]
    return rawlist

print "sorted list-->> ", sortem(rawlist)
count = 0
target = random.randint(0, 100)
if target != int(len(rawlist)):
    count = count+1
print target
print count

but my program stops after generating one random number, how could I get it keep going?




Aucun commentaire:

Enregistrer un commentaire