列表未写入文本文件

时间:2014-12-15 17:58:07

标签: python

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

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

2 个答案:

答案 0 :(得分:1)

您的代码什么都不做。

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

没用。

  while not(k==j) and not(j%k==0):
        k = k + 1

无用,因为j总是2。

  if k == j:
        primes.append(j)
        f.write(str(j)+"\n")
  else:
        notprimes.append(j)

在这里,您将2追加到素数一次。

  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

所以len(素数)总是1.

这是一个解决方案。对不起C语言,但你可以很容易地pythonize它。

#include <stdio.h>
typedef unsigned long long ull;

int main(){
ull numb=10000,stop=20000;
ull i,c;
int cnt;
printf("Here are the primes between %lld and %lld :\n\n",numb,stop);
while(numb<=stop){
for(i=1;i<=numb;++i){
if(!(numb%i)) ++cnt;
}
if ((cnt==2) || (i==1)) printf("%lld; ",numb);
cnt=0;
++numb;
}
printf("\n\nThat's all\n");
}

答案 1 :(得分:1)

您的问题是代码:

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