Python begginer - Can someone tell me why this loop don't finish? - python

def is_power_of_two(n):
# Check if the number can be divided by two without a remainder
while n % 2 == 0:
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
if n != 0:
return False
print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False
This is a excercice from Coursera's Python course. I don't know why it don't finish when n=0.

while n % 2 == 0: will turns out to be a infinate loop.
This happening because
First number input is 0
while n % 2 == 0: ---> 0 ==0 --> True
While True:
#This is infinate loop.
Code correction
To avoid this check if n is zero or not before while.
def is_power_of_two(n):
if n ==0:
return False
# Check if the number can be divided by two without a remainder
while n % 2 == 0:
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
if n != 0:
return False
print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False
Gives #
False
True
True
False

Related

How to properly check if a number is a prime number

Hey so i have this function to check if a number is a prime number
def is_prime(n):
flag = True
for i in range(2, n ):
if (n % i) == 0:
flag = False
return flag
print(is_prime(1))
However when i test the number 1, it skips the for loop and returns True which isn't correct because 1 is not a prime number.
How could i fix this?
You can first start by checking if n is greater than 1 the code should proceed, else it should return False. If n passes the first condition, only then the code can proceed to verify if n is indeed prime or not.
def is_prime(n):
flag = True
if n > 1:
for i in range(2, n ):
if (n % i) == 0:
flag = False
return flag # Returns this flag after check whether n is prime or not
# Returns False if n <= 1
return False
print(is_prime(1))
output:
False
2 is also skipped by the loop, but the function returns true thanks to the flag, and we know that's right.
Also you can exit early the loop if the condition is met:
def is_prime(n: int) -> bool:
if n > 1:
for i in range(2, n): # if n == 2, there is no loop, is never checked
if (n % i) == 0:
return False # can return early once we meet the condition, don't need to finish the loop
return True
print(is_prime(7534322224))
print(is_prime(5))
An alternative approach (though much slower on bigger numbers):
def is_prime(n: int) -> bool:
if n < 2: return False
return n == 2 or True not in [True for i in range(2, n) if (n % i) == 0]
print(is_prime(75343224))
print(is_prime(5))

I'm trying to print the integers from 0 to 100 and identify the prime numbers

I've worked a lot on this but I can't figure out the problem. Can you help me?
The code should print numbers from 0 to 100 and print next to the prime numbers "Prime". The first function works but if I try to print the numbers all togheter the "prime" tag gets misplaced.
def testPrime(numTest):
if numTest <= 1:
return False
if numTest == 2:
return True
for i in range(2, numTest):
if (numTest % i) == 0:
return False
else:
return True
def printPrimes (lenght):
i = 0
while i <= lenght:
if testPrime(i):
print(str(i) + "Prime")
else:
print(str(i))
i += 1
printPrimes(100)
The logic in testPrime() is flawed. There are faster techniques but here's a trivial approach that may help:
def testPrime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
Since a prime number is defined a number a natural number greater than 1 that is not a product of two smaller natural numbers
I think this is the only lines you need.
def testPrime(n):
for i in range(2,n):
if n%i == 0:
return False
return True

How do I break an infinite Python loop?

I'm looking to fix the following code, so that it can finish successfully for all numbers listed. How can I break the infinite loop that's present?
Furthermore, how can I return print(is_power_of_two(8)) as True?
# Check if the number can be divided by two without a remainder
while n % 2 == 0:
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
return False
print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False
your while condition should be :
# Check if the number can be divided by two without a remainder
while n % 2 == 0 and n >1:
n = n / 2
cause for the moment your code infinitely loops when n=1 cause 1%2 = 1
Add and n != 0 to the while condition, so the loop will halt when n is zero.
def is_power_of_two(n):
# Check if the number can be divided by two without a remainder
while n!=0 and (n % 2 == 0 or 2%n==0):
n = n / 2
return True
return False
import math
math.log2(number).is_integer()
Use this. From Check if a given number is power of two in Python
def is_power_of_two(n):
#Check Number for Zero
if n==0:
return False
else:
# Check if the number can be divided by two without a remainder
while n % 2 == 0:
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
return False
def is_power_of_two(n):
# Check if the number can be divided by two without a remainder
while n % 2 == 0 and n!=0:
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
return False
print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False

Can't define 2 as prime number or not

I'm trying to define prime numbers, but my algorithm doesn't recognize 2 as a prime number. Instead return None. I try it in Google Colab, Jupiter Notebook and PyCharm with same result.
My code:
# V1) Test all divisors from 2 through n-1. (skip 1 and n)
def is_prime_v1(n):
""" Return 'True' if 'n' is a prime number. False otherwise. """
if n == 1:
return False # 1 is not prime
for d in range(2, n):
if n % d == 0:
return False # Is not prime
return True
# ===== Test Function =====
for n in range(1, 21):
print(n, is_prime_v1(n))
My output:
1 False
2 None
3 True
4 False
5 True
6 False
7 True
8 False
9 True
10 False
11 True
12 False
13 True
14 False
15 True
16 False
17 True
18 False
19 True
20 False
Additionally, the return has some erros, like 9 is not a prime number.
This code is from, starting in 0:46: Python and Prime Numbers || Python Tutorial || Learn Python Programming
Because Your program never enters the loop.
for d in range(2, n):
if n % d == 0:
return False # Is not prime
return True
starts from 2, up until n-1.
Also, you should indent it differently. Only after your program exited the loop should you return True:
for d in range(2, n):
if n % d == 0:
return False # Is not prime
return True
But if you want to optimize your function, it should be like this:
def is_prime_v1(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for d in range(3, round(n**0.5) + 1, 2):
if n % d == 0:
return False
return True
Since you dont need to check up to the number itself, only it's square root.
Also, no number that is even can ever be prime (except 2), since it would be divisible by two.
EDIT:
I'm happy my answer helped :)
You can explicitly define 2 as prime.
The return True is inside your for loop and so is returning true after just 1 iteration (which is why you have errors).
For primes, it suffices to check only up to the square root of the number you are testing, this should speed things up considerably for large n.
Try this
def is_prime_v1(n):
""" Return 'True' if 'n' is a prime number. False otherwise. """
if n == 1:
return False # 1 is not prime
elif n == 2:
return True
for d in range(2, int(n**0.5) + 1):
if n % d == 0:
return False # Is not prime
return True
for d in range(2, n):
if n % d == 0:
return False # Is not prime
return True
Create a separate if for it like you did for 1.
if n == 2:
return True #2 is prime

Incorrect boolean checking for Prime

Why does the following code return True when it should return False. Trying to test if number is prime.
The intent of the code is to loop the this range(2,n) and if any number i divides n (remainder is 0) return False. The code returns True (incorrect) for 25 but False (correct) for 20. When the loop reaches 5 then 25%5 is 0 so it should return False. Where did I go wrong. There are other ways to check if number is prime but I want to know why this way does not work for 25 but does for 20.
def isPrime(n):
"""
"""
for i in range(2,n):
if n%i == 0:
return False
else:
return True
def main():
print isPrime(25) #Should return False
if __name__ == '__main__':
main()
Here is another implementation without the return statements that get so the area of the code that I would like to better understand.
for i in range(2,n+1):
if n%i == 0:
print 'for i =',i,'n%i =',n%i,'Therefore',n,'is not a prime'
print 'Should break out of loop here and return False'
else:
print 'for i =',i,'n%i =',n%i
Here is sample output.
for i = 2 n%i = 0 Therefore 10 is not a prime
Should break out of loop here and return False
for i = 3 n%i = 1
for i = 4 n%i = 2
for i = 5 n%i = 0 Therefore 10 is not a prime
Should break out of loop here and return False
for i = 6 n%i = 4
for i = 7 n%i = 3
for i = 8 n%i = 2
for i = 9 n%i = 1
So, shouldn't have broken out where i is 2 or when i is 5 when n is 10? Why doesn't it?
In your code you are checking with each number in that range and at the same time you are returning true or false, that's a bad idea. you have to return false if all the numbers in that range not matching with your condition. Instead of that in your coding you are checking for each element.
def isPrime(n):
"""
"""
for i in range(2, n):
if n % i == 0:
return False
else:
return True
print isPrime(25)
So if you write the else with for loop it will first execute for all the elements in range if nothing is matching it will it will go to the else part rather than checking if:..Else:.. for each element in that range.

Categories