سؤال

I have to random choose names from a list in python using random.randint.

I have done it so far. but i am unable to figure out how to print them without repetition. some of the name repeat them after 10 to 15 names.

please help me out. I am not allowed to use any high functions. I should do it with simple functions. here is my program.

import random
names = [about 150 names]
print([names[random.randint(0, len(names)-1)] for i in range(user_input)])
هل كانت مفيدة؟

المحلول

If you can destructively modify names, just pop the values instead of copying them. Then they're not there anymore, so you won't be able to repeat.

If you can't destructively modify names, just do the same to a copy:

tmp = names[:]
result = [tmp.pop(random.randrange(len(tmp))) for _ in range(user_input)]

This does have quadratic performance, since each pop from the middle of the list has to shift half the list up one notch. But for 150 names, this is unlikely to be a problem. For example, on my laptop, picking 100 values out of 150 names takes 83 microseconds.

If you really aren't allowed to use even randrange, you can write it yourself:

def randrange(x): return randint(0, x-1)

نصائح أخرى

These restrictions are pretty silly. I'm not sure what "high functions" are, but you still need help after I provided the function in your last question, so perhaps function declarations aren't allowed?

Still, you can do the same thing without a function. You just need to keep track of indices you've already used. Here's another go:

indices = []
for x in range(5):
    index = random.randint(0, len(population)-1)
    while index in indices:
        index = random.randint(0, len(population)-1)
    indices.append(index)
names = [population[i] for i in indices]

Assuming, that you can only use randint and basic operations (loops, assignments and sublistings) - you can do the "in place shuffling trick" (modern version of Fisher Yates) to achieve such a result

copy = names[:]    
for i in xrange( user_input-1, 1, -1 ):
  swap = random.randint(0, i) 
  copy[i],copy[swap] = copy[swap],copy[i]

print copy[ :user_input ]

Generate an array of random numbers of the same length as names

sortarr = [random.randint(0, 10*len(names)) for i in range(len(names))] 

and sort your names array based on this new array

names = [name for sa, name in sorted(zip(sortarr, names))]

What it does is assigns some random numbers to the names. They can be repeating, but it will not make repeating names because if two numbers are the same, they will be assigned to some arbitrary names.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top