[英]Intended to be a limited loop, but seems to be infinite
I wanted to do the following task:我想做以下任务:
Given a number N, let's say it's 5. I want to generate a list with all numbers in the range from 1 to N (5) with no duplicates in a random order.
给定一个数字 N,假设它是 5。我想生成一个列表,其中包含 1 到 N (5) 范围内的所有数字,并且没有随机顺序的重复项。
So I wrote this code.所以我写了这段代码。 Using these debug outputs I realized that the loop is pretty much infinite, even though it wasn't supposed to be.
使用这些调试输出我意识到循环几乎是无限的,即使它不应该是。
import random
def generate(n):
amount = n
print('Line 1 success') #TODO:DEBUG
randnum = 0
print('Line 2 success') #TODO:DEBUG
finished = False
print('Line 3 success') #TODO:DEBUG
nums = []
print('Line 4 success') #TODO:DEBUG
while amount != 0:
while finished != True:
print('Line 5 success', amount) #TODO:DEBUG
randnum = random.randint(1,n)
print('Line 6 success') #TODO:DEBUG
if not randnum in nums:
finished = True
nums.append(randnum)
print('Generation', amount, 'success') #TODO:DEBUG
print(nums, ' ; ', randnum) #TODO:DEBUG
print('Line 7 success') #TODO:DEBUG
amount = amount - 1
print('Line 8 success') #TODO:DEBUG
finished = False
print('Line 9 success') #TODO:DEBUG
print(nums)
generate(5)
It gives me an infinite loop and I have no idea why and how to fix it.它给了我一个无限循环,我不知道为什么以及如何修复它。
Why is it an infinite loop?为什么是无限循环?
What about this?那这个呢?
import random
def generate(n):
l = []
for i in range(0,n,1):
l.append(i)
random.shuffle(l)
According to your comment, this should work:根据您的评论,这应该有效:
import random
def generate(n):
l = []
z = 0
while z < n:
x = random.randint(0,n)
if x not in l:
z +=1
l.append(x)
return l
You need to do a minor change @ amount = amount -1
你需要做一个小改动 @
amount = amount -1
This way your list gets appended every time a unique randnum is generated.这样,每次生成唯一的randnum时,您的列表都会被附加。
Also I have updated the loop break condition to reduce the time complexity.我还更新了循环中断条件以降低时间复杂度。
import random
def generate(n):
amount = n
randnum = 0
finished = False
nums = []
while amount > 0 and finished != True:
randnum = random.randint(1,n)
if not randnum in nums:
finished = True
nums.append(randnum)
amount = amount - 1
finished = False
print(nums)
generate(5)
OUTPUT : [4, 1, 3, 5, 2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.