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

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


使用Eratosthenes算法筛网

您可以使用算法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/

10-11 22:30
查看更多