簡體   English   中英

列表未寫入文本文件

[英]List not being written to a text file

我有一個程序應該詢問要計算多少個素數,然后將它們全部寫入文本文件。 但是,它將創建文件,然后將無法運行。

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

是沒用的。

  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(primes)始終為1。

這是一個解決方案。 對不起,C語言,但是您可以輕松地對其進行python化。

#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");
}

您的問題是代碼:

 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算法篩網

您可以使用Eratosthenes的Sieve算法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM