首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不重复的Python-randint函数

不重复的Python-randint函数
EN

Stack Overflow用户
提问于 2017-01-31 13:13:53
回答 4查看 236关注 0票数 1

我只是python.And的初学者,我在这里只是写了一个简单的程序来自我评估,并尝试回答随机order.But中提出的问题,这里的错误是,randint函数有时会获得相同的数字,我会重复得到相同的问题。我尽了最大的努力来解决它,但我做不到。希望我能在这里得到一些帮助。`导入随机

代码语言:javascript
复制
global some
global i
i=0

some=[]
names=['electric charge','permitivity of the medium','permitiovity of free space','relative permitivity of the medium','intensity  of the electric field','electric potential at a point','electric potential energy','dipole moment','torque acting on the dipole','electric flux','linear charge density of the conductor','surface charge density of the conductor','capacitance of a parallel plate capacitor','practical unit of capacitance']
answer=['C','C2N-1m-2','C2N-1m-2','no unit','NC-1 or Vm-1','V','J','Cm','Nm','Nm2C-1','Cm-1','Cm-2','F','uF or pF']
def loop(i):
    for i in range(i,len(names)):
        global qno
        qno=random.randint(0,len(names))
        if i>0:
            for k in range(0,len(some)):
                if str(qno)==some[len(some)-1]:
                    loop(i-1)
        print(names[qno])
        print('Type your answer')
        tell=input()
        if tell==answer[qno]:
            print('Right answer.Move on')
        else:
            print('Wrong answer,.The answer is '+answer[qno])
        for j in range(i+1):
            some.append(str(qno))
i=i+1

loop(i)
`
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-01-31 13:18:00

在您的函数之前,添加一个布尔值数组,用于描述已经回答了哪些问题:

代码语言:javascript
复制
already_asked = [False] * len(names)

然后,将qno赋给一个值,继续生成随机数,直到命中一个您以前没有问过的数,并将新提出的问题标记为已问:

代码语言:javascript
复制
qno = random.randint(0, len(names))
while already_asked[qno]:
    qno = random.randint(0, len(names))
already_asked[qno] = True
票数 2
EN

Stack Overflow用户

发布于 2017-01-31 13:26:09

random.shuffle函数执行的正是您想要的操作。

票数 1
EN

Stack Overflow用户

发布于 2017-01-31 13:46:06

如果你使用随机型If (0,14),你一定会得到很多重复的结果!例如:

代码语言:javascript
复制
import random

names=['electric charge','permitivity of the medium','permitiovity of free space','relative permitivity of the medium','intensity  of the electric field','electric potential at a point','electric potential energy','dipole moment','torque acting on the dipole','electric flux','linear charge density of the conductor','surface charge density of the conductor','capacitance of a parallel plate capacitor','practical unit of capacitance']


for i in range(10):
...     print( random.randint(0,len(names)))

以下是我第一次运行时的输出:

代码语言:javascript
复制
12
6
6
6
7
14
7
11
4
10

注意我是如何三次获得数字6的!显然,随着范围的增加,重复发生的次数会减少,但你总是有机会重复数字,特别是因为这只是一个伪随机生成的数字。

也许你正在寻找像shuffle这样的东西?例如:

代码语言:javascript
复制
>>> new_order = ([ i for i in range(len(names)) ])
>>> random.shuffle(new_order)
>>> print(new_order)
[9, 10, 7, 8, 4, 13, 0, 2, 3, 6, 12, 5, 1, 11]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41950104

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档