我已将其设置为用户输入最大输入,然后程序确定哪些数字为素数,然后将其全部打印到文件中。但目前它只将最接近的素数打印到上输入。我需要它打印20个随机数并将它们放在一个文件上。同样print (num)
20次,它可以打印20个不同的输出,但是如果我添加print (num)
20次,则打印相同的数字20次
import random
#Always start at 2
lower = 2
#Take input from the user
upper = int(input("Enter maximum size for prime number to be: "))
for num in range(lower,upper + 1):
if num > 1:
#Prime numbers are greater than 1
for i in range(2,num):
if (num % i) == 0:
break
#End program if number is 0
#Print results
else:
randomprimes =(num)
primes =(random.choice(randomprimes))
import sys
former, sys.stdout = sys.stdout, open('Prime Number Generator Output.txt', 'w')
print (primes)
results, sys.stdout = sys.stdout, former
results.close()
答案 0 :(得分:2)
random.choice
返回给定iterable中的随机项。
如果您想要给定列表中的20个随机项而不重复,请使用random.sample
。 (谢谢,休·博思韦尔)
编辑:通常不会这样做,但这是一个解决方案:
import random, math
upper = int(input("Enter maximum size for prime number to be: "))
primes = [x for x in range(2, upper) if x not in [j for i in range(2, math.ceil(math.sqrt(upper))) for j in range(i*2, upper, i)]]
with open("Prime Number Generator Output.txt", "w") as f:
for prime in random.sample(primes, min(len(primes),20)):
f.write(str(prime) + "\n")