Python code to extend a list of prime numbers - python

I want to write code that extends a list of prime numbers using Python, but something does not work:
list = [2,3,5,7]
for num in range(15,30):
for i in range(0,len(list)-1):
if num%list[i] != 0:
if i + 1 == len(list):
list.append(num)
else:
continue
else:
break
print(list)
The incorrect output is: [2, 3, 5, 7]

Your issue is that
for i in range(0,len(list)-1):
should be
for i in range(0,len(list)):
The range function in python will stop on the number before the number you specify in the stop argument, so you don't need to minus 1 yourself. From the documentation:
For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

Because your code doesn´t work.
If you run your code, you will see that the program jumps in the else part of your first if condition and there you will break the for loop. So your program does nothing other than deklaring a list and print that list, because the true part of the if condition isn´t processed.

Another way to fix the issue #RobStreeting pointed out (+1) is to get rid of the range(len()) idiom and use enumerate(). We can fix the missing 11 & 13 that #ThierryLathuille points out by starting our loop just afer the last collected prime. Finally, you shouldn't have a variable named list as that's a reserved Python keyword. Putting this all together, your code looks something like:
primes = [2, 3, 5, 7]
for number in range(primes[-1] + 1, 50):
for i, prime in enumerate(primes, start=1):
if number % prime:
if i == len(primes):
primes.append(number)
else:
continue
else:
break
print(*primes, sep=", ")

Related

While loop keeps going back to end condition

I'm just going over some python basics, and wrote some code that I thought would print every even element inside of a list:
def print_evens(numbers):
"""Prints all even numbers in the list
"""
length = len(numbers)
i = 0
while i < length:
if numbers[i] % 2 == 0:
print (numbers[i])
i += 1
print_evens([1, 2, 3, 4, 5, 6])
I'm not sure why but the loop doesn't go past the end condition and just keeps cycling back and forth. I feel I'm missing something very simple.
If I had to guess where the problem lies, I'd say it's with the if statement, though I'm not sure what would be wrong about it.
The problem is that when you start with 1 the variable i never get updated, because it's not even. So the solution is to increment the i every time without a condition:
while i < length:
if numbers[i] % 2 == 0:
print (numbers[i])
i += 1
If you don't want to bother with indexes you can loop directly on the list items.
def print_evens(numbers):
"""Prints all even numbers in the list
"""
for n in numbers:
if n % 2 == 0:
print(n)

Removing data structure

The goal here is to take an amount of int values indicated by the first int and create a list, in order of even numbers to odd numbers (value order of the numbers doesn't matter).
My code so far deals with most of the problem. However, how would I go about ignoring the first int value?
Example input:
example=[7,1, 0, 1, 0, 0, 1, 1]
example=[3,3, 3, 2]
example=[3,2, 2, 2]
My code:
even=[]
odd=[]
while True:
try:
n = int(input())
except:
break
if n % 2 ==0:
even.append(n)
else:
odd.append(n)
print(even+odd)
Before going in while loop, pop out first value. You can also save this as the total numbers.
Also, there is an error in your code. If try fails in while loop, for the first time loop running there will be an exception. And next on previous value will be used, so a single value will be repeated. I corrected it by adding n=0.
even=[]
odd=[]
n=0
NumCount= int(input())
while True:
try:
n = int(input())
except:
break
if n % 2 ==0:
even.append(n)
else:
odd.append(n)
print ("Total numbers (even+odd)", NumCount)
print(even+odd)

Code is in Infinite Loop and I don't know Why

My code is stuck in an infinite loop on the following lines:
while i <= len(mylist):
if mylist[i][j] == number:
I've stepped through the code but still do not know how to fix it. The problem I'm trying to solve is as follows:
Define a procedure, check_sudoku,
that takes as input a square list
of lists representing an n x n
sudoku puzzle solution and returns the boolean
True if the input is a valid
sudoku square and returns the boolean False
otherwise.
A valid sudoku square satisfies these
two properties:
Each column of the square contains
each of the whole numbers from 1 to n exactly once.
Each row of the square contains each
of the whole numbers from 1 to n exactly once.
You may assume that the input is square and contains at
least one row and column.
The below code I've written should check for just the row, not the column. Any advice on how to fix it and what I've done wrong would be greatly appreciate, so I'll understand and not make the mistake again.
def check_sudoku(mylist):
i = 0
j = 0
number = len(mylist)
while i <= len(mylist):
if mylist[i][j] == number:
number = number - 1
j = 0
if number == 0:
i = i + 1
number = len(mylist)
else:
j = j + 1
if number not in list:
break
return False
return True
check_sudoku([[1, 2, 3, 4],
[1, 3, 1, 4],
[3, 1, 2, 3],
[4, 4, 4, 4]])
I'm going to explain the function with the list you supplied as an example.
What's happening is:
number = len(mylist)
number = 4
while 0 <= 4
if 1 == 4: // This condition will never be true and therefore doesn't run the code below it
The while will run again and the same will happen.
If you put this line
print("i: " + str(i) + " j: " + str(j))
Just under where the While Loop starts, you realise that i and j never increment and it stays on the first spot.
You have to increment i and j after your bigger if statement

Finding all numbers that evenly divide a number

So I'm trying to make a program that when I input a number it will give me all the factors(12->1,2,3,4,6,12). I only started programming very recently so there may be some very obvious things. But here's my code
numbers = [1]
newnum = 1
chosen = int(input("Enter what you want the factors of: "))
def factors(numbers,newnum,chosen):
lastnum = numbers[-1]
if (chosen == lastnum):
for number in numbers:
if (number % 1 != 0):
numbers.remove(number)
print (numbers)
else:
factors(numbers,newnum,chosen)
else:
newnum = numbers[-1] + 1
numbers.append(newnum)
print (numbers)
factors(numbers,newnum,chosen)
factors(numbers,newnum,chosen)
Ok, so I don't really need the redundancies addressed but if you see something that would completely stop the program from working please point it out. Sorry I bothered you all with this but I don't know what else to do.
There are lots of problems:
Every integer number modulo 1 is zero because each integer is divisible by one without remainder.
You remove items from the list you're iterating over, that will definetly give wrong results if you don't do it carefully!
You try to do recursion but you don't return the result of the recursive call. That's possible because you operate on a mutable list but it's generally not really good style
You don't have any inline comments explaining what that line is supposed to do, so it's hard to give any reasonable guidance on how to improve the code.
If you want a code that finds all factors, consider something like this:
chosen = int(input("Enter what you want the factors of: "))
def factors(chosen, currentnum=None, numbers=None):
# Recursion start, always append 1 and start with 2
if numbers is None:
numbers = [1]
currentnum = 2
# We're at the last value, it's always divisible by itself so
# append it and return
if currentnum == chosen:
numbers.append(currentnum)
return numbers
else:
# Check if the chosen item is divisible by the current number
if chosen % currentnum == 0:
numbers.append(currentnum)
# Always continue with the next number:
currentnum += 1
return factors(chosen, currentnum, numbers)
>>> factors(chosen)
Enter what you want the factors of: 12
[1, 2, 3, 4, 6, 12]
That's not the optimal solution but it uses recursion and gives a proper result. Just don't enter negative values or catch that case in the function at the beginning!
# Two Pointer Approach
ans = []
def divisor(val):
result = []
for i in range(1, val + 1):
ans.append(i)
i = 0
j = len(ans) - 1
while i < j:
if ans[i] * ans[j] == ans[-1]:
result.append(ans[i])
result.append(ans[j])
i += 1
else:
j -= 1
return sorted(result)
print(divisor(12))
# Output
>>> [1, 2, 3, 4, 6, 12]

How can I continue the for loop of the outer side?

def countPrimes(self, n):
if n <= 1:
return 0
if n == 2:
return 1
count = 0
counted = [2, ]
for num in xrange(3, n+1, 2):
for c in counted:
if num % c == 0:
continue
count += 1
counted.append(num)
return count
I am writing a code for the solution of primes counting problems. I used counted as an array storing for primes that have been examined and use them for the examination for the next prime. I tried using continue to drop out the inner for loop then count += 1 and counted.append(num) would not be executed once the num is found not a valid prime. However, I met implementing problem here, as the continue statement would take me to another c instead of another num.
If I understand your question correctly, you want to know how to break the inner c loop, avoid the other code, and continue with another num. Like the other answers, you want to make use of break with some smart booleans. Here's what the loop might look like:
for num in xrange(3, n+1, 2):
next_num = False
for c in counted:
if num % c == 0:
next_num = True
break
if next_num:
continue
count += 1
counted.append(num)
This way, if you encounter a num that is divisible by c, you break out of the inner c loop, avoid adding num to the counted list.
It doesn't make a ton of sense to accumulate a count and a list of primes as you go. Introduces the chance for a mismatch somewhere. I've massaged the code a bit, with some more descriptive variable names. It's amazing how clear names can really make the algorithm make more sense. (At least for me it does)
def primesUpTo(n):
primes = []
if n > 1:
primes.append(2)
for candidate in xrange(3, n+1, 2):
for prime in primes:
candidate_is_prime = candidate % prime
if not candidate_is_prime: # We're done with this inner loop
break
if candidate_is_prime:
primes.append(candidate)
return primes
print len(primesUpTo(100))
Try using break instead of continue. See the documentation here. Basically break takes you out of the smallest enclosing loop, spitting you back into your higher-level loop for its next iteration. On the other hand, continue just jumps you on to the next iteration of the smallest closing loop, so you wouldn't go out to the higher-level loop first.

Categories