Python generates code that does not repeat random Numbers

  • 2020-04-02 09:26:05
  • OfStack

 
import random 
print 'N must >K else error' 
n=int(raw_input("n=")) 
k=int(raw_input("k=")) 
result=[] 
x=range(n) 
for i in range(k): 
t=random.randint(i,n-1) 
temp=x[i] 
x[i]=x[t] 
x[t]=temp 
result.append(x[i]) 
print result 
raw_input('Inpuy AnyKey to exit') 

This is generated by an algorithm and python has a way of doing it
Random. Sample (list, n) means that n different elements are randomly selected from the list
 
import random 
for i in range(4): 
print random.sample(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], 7) 

Related articles: