Home > database >  Append to an empty list using while loop
Append to an empty list using while loop

Time:10-04

I've tried running this python script but it returns an empty list, I don't see what I'm missing but it seems I'm failing to append anything to the list. (The goal is to return a list of n numbers of prime numbers starting from 2, there are restrictions such as using only the while loop.) Appreciate any insights!!

def primes_list(n):
    primes = []
    count = 0
    while count < n:
        num = 1
        divisor = 2
        while num % divisor != 0 and num > divisor:
            divisor  = 1
        if divisor == num:
            primes.append(num)
        count  = 1
    return primes

CodePudding user response:

def primes_list(n):
    num = 1
    while num <= n:
        div = 2
        while num % div and num > div: div  = 1
        if div == num: yield num
        num  = 1

print(list(primes_list(100)))

This will simplify the code and alternative using yield generator.

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

CodePudding user response:

count is not used in the algorithm. Do you mean to use count everywhere num currently appears? Since you reset num to 1 on every iteration, every time around, the two boolean conditions are both false and the outer while effectively just counts up to n.

CodePudding user response:

You don't need count as a counter. You just need to move num outside the while loop and increase num till n.

def primes_list(n):
    primes = []
    num = 1
    while num < n:
        divisor = 2
        while num % divisor != 0 and num > divisor:
            divisor  = 1
        if divisor == num:
            primes.append(num)
        num  = 1
    return primes
  • Related