Python: Why donnot I get a result in the terminal - python

Python: Why don't I get a result in the terminal
def is_even(number):
if number % 2 == 0:
return True
return False
is_even(10)

You need to print the output of the function. You also need to create the function.
def is_even(num):
if num % 2 == 0:
return True
else:
return False
print(is_even(10)) #True
print(is_even(7)) #False

Related

***Time limit exceeded*** error on python program

when i try to print this line:
print(perfect_square(0))
i should get True but instead i get a time limit exceeded error and i dont know how to fix it.
i tried chaging it to an elif statment instead of 2 separate if statements but i still get that error
This is my current code:
def perfect_square(n):
s = 1
while s != n:
if s*s == n:
return True
elif s == 0:
return True
else:
s +=1
return False
def perfect_cube(n):
s = 1
while s != n:
if s*s * s == n:
return True
elif s == 0:
return True
else:
s +=1
return False
Seems quite clear to me why the perfect_square(0) and perfect_cube(0) cases cause an infinite loop. You start s=1 and always increment it s+=1. It will never be equal to n=0 so you get an infinitely running program. Maybe try making checks for invalid values of n?
def perfect_cube(n):
if n < 1: return False
# ...

Finding Cyclops Numbers in Python

I am working on a problem in which I need to return True or False after checking to see whether a number is a cyclops number or not. A cyclops number is made up of odd number of digits, consists of only one zero and that zero is located in the middle. Here's what I have so far:
def is_cyclops(n):
strNum = str(n)
for i, el in enumerate(strNum):
if(len(strNum) % 2 == 0):
return False
else:
# find middle number is zero
# no other zeros exist
# return True
is_cyclops(0) # True
is_cyclops(101) # True
is_cyclops(1056) # False
is_cyclops(675409820) # False
How can I find the median number (without using numpy) & ensure it is a zero, and it is the only zero that exists in that number?
This worked for me:
def is_cyclops(num: int) -> bool:
str_ = str(num)
if not len(str_) % 2:
return False
if not str_.count('0') == 1:
return False
mid_index = len(str_) // 2
if str_[mid_index] == '0':
return True
return False
print(
is_cyclops(0),
is_cyclops(101),
is_cyclops(1056),
is_cyclops(675409820)
)
Output:
True True False False
As it looks like you've had a good attempt here, I'll help out.
def is_cyclops(n):
strNum = str(n)
if(len(strNum) % 2 == 0):
return False
else:
middle_index = len(strNum)//2
if strNum[middle_index] != "0": return False # find middle number is zero
if strNum.count("0") > 1: return False # no other zeros exist
return True
is_cyclops(0) # True
is_cyclops(101) # True
is_cyclops(1056) # False
is_cyclops(675409820) # False

Python - function returns true when a given number is a prime number or else false

Hi I'm a beginner and I'm stuck on this question that wants me to use only while loop to solve. The question wants me to write a function that returns True when the given number is a prime number and it returns False if the given number is not a prime number.
My code so far:
def is_prime(n):
i = 2
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
The problem I have is I think my code displays the correct output for numbers 4 and above and it returns 'None' for 1, 2, and 3. I've debugged it and I think the problem is the while loop condition. But I don't know how to fix it. I would appreciate it if any of you pros can help me out!
edit:
I changed the while condition but 1 still returns None.. and 2 returns False when it's supposed to return True
def is_prime(n):
i = 2
while i <= n:
if n%i != 0:
return True
else:
return False
i+=1
import math;
def is_prime(n):
i = 2
while i < max(math.sqrt(n),2):
if n%i != 0:
return True
else:
return False
if i == 2:
i+=1
else
i+=2
You could hard-code these 3 cases, in case you dont want to use sqrt:
def is_prime(n):
i = 2
if n in (1,3):
return True
elif n == 2:
return False
while i <= n//2:
if n%i != 0:
return True
else:
return False
i+=1
for x in range(1, 5):
print(x, '=', is_prime(x))
Output:
(1, '=', True)
(2, '=', False)
(3, '=', True)
(4, '=', False)
Want to get really fancy? Make a Sieve of Eratosthenes:
def is_prime(n):
a = list()
# Assume all are prime
a[0:n+1] = (n+1)*[1]
# Start with removing even numbers
i = 2
while i*i <= n:
print ("I: ", i)
# Set all divisible by i to 0
a[0:n+1:i] = len(a[0:n+1:i])*[0]
# If a[n] is zero, return False
if a[n] == 0:
return False
# Increment i until we have a prime number
while a[i] == 0:
i+=1
if a[n] == 0:
return False
else:
return True
If you want to impress your lesson teacher you can show him a fast probabilistic prime number isprime for numbers larger than 2**50. I haven't found any errors in it after weeks of cpu time stress testing it on a 6 core AMD:
import random
import math
def lars_last_modulus_powers_of_two(hm):
return math.gcd(hm, 1<<hm.bit_length())
def fast_probabilistic_isprime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if lars_last_modulus_powers_of_two(hm+hm) != 2:
return False
if pow(2, hm-1, hm) == 1:
return True
else:
return False
def fast_probabilistic_next_prime(hm):
if hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
if hm % 2 == 0:
hm = hm + 1
hm += 2
while fast_probabilistic_isprime(hm) == False:
hm += 2
return hm
""" hm here is bitlength, which must be larger than 50.
usage is create_probabilistic_prime(1000)
"""
def create_probabilistic_prime(hm):
if 2**hm < 2**50:
return "This is to only be used on numbers greater than 2**50"
num = random.randint(2**hm,2**(hm+1))
return fast_probabilistic_next_prime(num)

Codecademy Python “is_prime” exercise in “Practice Makes Perfect”-Is it really iterating?

This function is supposed to return True if a number is prime and False if it's not. The problem is that is_prime(9) returns True.
def is_prime(x):
if x<2:
return False
elif x==2:
return True
elif x==3:
return True
else:
for i in range(2,x):
if x%i==0:
return False
break
else:
return True
Because if you write
for i in range(2,x):
if x%i==0:
return False
break
else:
return True
if x is 9 then 9%2 != 0, so it takes else path and returns True
odd_number % 2 is always = 1
You have to remove the last line and replace it with return True after the for has finished:
def is_prime(x):
if x<2:
return False
elif x==2:
return True
elif x==3: #<-- This one is useless, it will be already checked within the for
return True
else:
for i in range(2,x):
if x%i==0:
return False
break
return True
print is_prime(9)
print is_prime(11)
Your code is improperly indented. The else:return True line should be indented one level less, so that it runs after the for loop terminates. The current code returns True whenver any divisibilty test fails, not when all of the divisibility tests fail.
The function is buggy. The else: inside the loop is returning True the first time it encounters a number that isn't a divisor. That needs to be deleted, and the return True needs to be placed after the loop (outside of it).
Check indentation. The if and else in the for loop.
Understand the meaning of return, the function literally exits when you return.
Corrected code:
def is_prime(x):
if x<2:
return False
elif x==2:
return True
elif x==3:
return True
else:
for i in range(2,x):
if x%i==0:
print "Hello"
return False
break
else:
return True
print is_prime(9)

Python issues with return statement

Hello I'm very new to python and was wondering if you could help me with something.
I've been playing around with this code and can't seem to get it to work.
import math
def main():
if isPrime(2,7):
print("Yes")
else:
print("No")
def isPrime(i,n):
if ((n % i == 0) and (i <= math.sqrt(n))):
return False
if (i >= math.sqrt(n)):
print ("is Prime: ",n)
return True
else:
isPrime(i+1,n)
main()
Now the output for the isPrime method is as follows:
is Prime: 7
No
I'm sure the function should return true then it should print "Yes".
Am I missing something?
You are discarding the return value for the recursive call:
def isPrime(i,n):
if ((n % i == 0) and (i <= math.sqrt(n))):
return False
if (i >= math.sqrt(n)):
print ("is Prime: ",n)
return True
else:
# No return here
isPrime(i+1,n)
You want to propagate the value of the recursive call too, include a return statement:
else:
return isPrime(i+1,n)
Now your code prints:
>>> isPrime(2,7)
is Prime: 7
True

Categories

Resources