Home > Backend Development > Python Tutorial > python 生成不重复的随机数的代码

python 生成不重复的随机数的代码

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-16 08:47:09
Original
2233 people have browsed it
复制代码 代码如下:

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')

这是用算法生成的 其实python有方法的
random.sample(list, n)即是从list中随机选取n个不同的元素
复制代码 代码如下:

import random
for i in range(4):
print random.sample(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], 7)
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template