gpt4 book ai didi

python - 列表未写入文本文件

转载 作者:行者123 更新时间:2023-12-01 04:55:32 25 4
gpt4 key购买 nike

我有一个程序,应该询问要计算多少个素数,然后将它们全部写入文本文件。但是,它创建了文件然后不运行。

def constantcall():
j = 2
chk = 1
f = open("primes.txt", "w")
primes = []
notprimes = []
ask = input("how many primes? ")
while len(primes) < int(ask):
k = 2
while not(k==j) and not(j%k==0):
k = k + 1
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close
return(" ")

if __name__ == '__main__':
while(True):
constantcall()

最佳答案

你的问题是代码:

 while len(primes) < int(ask):
k = 2

此时len(primes)小于int(ask),并且没有任何东西向素数添加项,因此无限循环。

您的代码必须是(为了避免无限循环):

def constantcall():
j = 2
chk = 1
f = open("primes.txt", "w")
primes = []
notprimes = []
ask = input("how many primes? ")
while len(primes) < int(ask):
k = 2
while not(k==j) and not(j%k==0):
k = k + 1
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close
return(" ")

if __name__ == '__main__':
constantcall()

使用埃拉托色尼筛法算法

您可以使用算法 Sieve of Eratosthenes :

def primes(count):
"""
Returns a list with the first `count` prime numbers.

An advice: If you will be using this functiona a lot it's better
for performance if you precalculate cribe.
"""

# Calculate primes up to 50, you can change this to your preference.
MAX = 50

sieve = [1] * MAX
for i in range(2, int(MAX ** 0.5) + 2 ):
for j in range(i + i, MAX, i):
sieve[j] = 0

# Finally primes are indexes in the list that still has 0.
result = []
for index, elem in enumerate(sieve):
if elem == 1: result.append(index)

return result[1:count + 1]

您的代码可以重写为:

def constantcall():
f = open("primes.txt", "w")
ask = int(input("how many primes? "))
prime_numbers = primes(ask)
f.writelines(map(lambda x: "{0}\n".format(x), prime_numbers))


if __name__ == '__main__':
constantcall()

关于python - 列表未写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27490159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com