I started learning python yesterday , and I realized I can make a perfect square checker using functions and the isinstance function. However , my code says 144 is not a perfect square. What am I doing wrong?
My Code :
def sqrt():
x = int(input("Enter a number:"))
a = x ** 0.5
return a
b = sqrt()
if isinstance ( b , int) == True:
print("It is a perfect square")
if isinstance( b , int) == False:
print("It is not a perfect square")
Keep in mind that number ** 0.5 will always result to a floating value. Example: 144 ** 0.5 == 12.0. Because of this, isinstance(b , int) will always be False.
This is an alternative solution among many other possible solutions:
def is_perfect_square(number):
root = int(number ** 0.5)
return root ** 2 == number
print(is_perfect_square(144))
The type of b in the original code is a float.
you can see this by adding type(b) to the end of the code which would return <class 'float'>.
so you could change the code to this:
def sqrt():
x = int(input("Enter a number:"))
a = x ** 0.5
return a
b = sqrt()
if b - int(b) == 0:
print("It is a perfect square")
else:
print("It is not a perfect square")
This method avoids checking for type, but instead checks if the decimal part == 0 which is sufficient for a square.
Note: there are other methods.
Related
I was exercising to improve my coding but when I try to use this code and run, terminal just freezes and not giving any error at all, I cant do anything either until I press ctrl+c. Cause of its not giving error I don't know what did I wrong.
# 31. Write a Python program to compute the greatest common divisor (GCD) of two positive integers.
def findGCD(num,num1):
numDivided = 0
num1Divided = 0
while True:
num/2
numDivided+=1
num1/2
num1Divided+=1
if num and num1 == 1 or 0:
break
gcd = numDivided*num1Divided
print(gcd)
findGCD(101,102)
There are numerous mistakes including the incorrect if statement referred to above. num/2 will calculate something but this will be a float value if num is odd; then you do nothing with the result; same for num1/2. To find GCD you have to use integer arithmetic. Incidently 101 and 102 have only the GCD of 1 so maybe not the best example. The code below works. I suggest you paint it into https://pythontutor.com/visualize.html#mode=edit to step through the code and see how it works.
def findGCD(num, num1):
if num > num1:
hold = num1
else:
hold = num
for i in range(1, hold + 1):
if ((num % i == 0) and (num1 % i ==0)):
gcd = i
return gcd
I need to write a function that takes 2 parameters base and number.
The function returns True if there is an exponent that gives me the number base ** exp == number or False otherwise.
Examples:
check_is_power(2, 16) -> True # because you have a valid exp here (4)
check_is_power(3, 17) -> False # because there is not a whole positive number as an exp
important:
I can use only these functions to solve this:
def add(x: float, y: float) -> float:
return x + y
def subtract_1(x: int) -> int:
return x - 1
def is_odd(n: int) -> bool:
return n % 2 == 1
def divide_by_2(n: int) -> int:
return n // 2
This is what I tried:
def check_is_power(base: int, number: int) -> bool:
if number == base:
return True
return check_is_power(base, divide_by_2(number))
Now, I know I have problems with this code but That's my start position and I would like help to finish this. Thanks!
Something like this?
Work only with integers and positives number
def add(a, b) :
return a + b
def subtract_1(x):
return x - 1
def mul(a, b) :
if b == 1:
return a
if(b == 0):
return 0
return add(mul(a, subtract_1(b)), a)
def exp(a, b) :
if a == 0 and b == 0:
return -1 #should be NaN
if b == 1:
return a
if(b == 0):
return 1
return mul(exp(a, subtract_1(b)), a)
def check_is_power(base, number):
e = 0
if base == 0 and number == 0:
return True
if base <= 0 or number <= 0:
return False
while True:
r = exp(base, e)
if r == number:
return True
if r > number:
break
e = add(e, 1)
return False
print(check_is_power(15, 170859375))
Since I did not see a restriction on allowing one to change the sign of a value from positive to negative, following is a very simple block of code that appears to provide the necessary results.
def add(x: float, y: float) -> float:
return x + y
def is_exponent(x,y):
a = 0
b = y
c = -x # No mention of not allowing changing the sign of the base to effectively allow subtraction
while b > 0:
b = add(b,c)
a = a + 1
if b < 0:
return False
elif b == 0 and a == x:
return True
elif b == 0 and a < x:
return False
else:
return is_exponent(x,a)
while True:
base = int(input("Enter base "))
value = int(input("Enter value to check "))
if (is_exponent(base, value)):
print(value, "is an exponent of", base)
else:
print(value, "is not an exponent of", base)
choice = input("Do you want to check another pair (y/n)? ")
if choice != 'y':
break
All that is needed is the addition function along with recursively calling the "is_exponent" function.
Testing this out with a few different base numbers seemed to hold together.
#Una:~/Python_Programs/Exponent$ python3 Exponent.py
Enter base 6
Enter value to check 36
36 is an exponent of 6
Do you want to check another pair (y/n)? y
Enter base 25
Enter value to check 625
625 is an exponent of 25
Do you want to check another pair (y/n)? y
Enter base 25
Enter value to check 125
125 is not an exponent of 25
Do you want to check another pair (y/n)? y
Enter base 17
Enter value to check 4913
4913 is an exponent of 17
Do you want to check another pair (y/n)?
Give that a try and see if it meets the spirit of the exercise.
I am trying to create a function that will test whether a number is a prime number and then return True or False. I am an extreme beginner at Python, so please make your code as simple as possible. Here's what I tried so far (only returns True):
def isPrime(x):
x = int(x)
for i in range(2, x):
if(x % i == 0):
x == False
else:
x == True
return x
print(isPrime(input("Enter a prime number.")))
You almost made it, just need to change it like this:
def isPrime(x):
x = int(x)
for i in range(2, x):
if x % i == 0:
return False
return x >= 2
print(isPrime(input("Enter a prime number.")))
EDIT: As pointed by #MarkRansom, when the i variable reaches the square root of x, it is safe to assume that there are no more possible divisors for it:
from math import sqrt
def isPrime(x):
x = int(x)
for i in range(2, int(sqrt(x)) + 1):
...
I believe the simplest form of your program would be along the lines:
def isPrime(x):
if x > 1:
for i in range(2, x):
if x % i == 0:
return False
return True
return False
print(isPrime(int(input("Enter a number: "))))
But this is not as efficient as it could be. To do better, we would treat 2 (and all even numbers) as a special case and only allow the divisor to cover the odd numbers from 3 to the square root of the number we're testing. The more divisions we can avoid, the faster it goes.
Ultimately using a Sieve of Eratosthenes will beat this approach, even with optimizations.
When you typed this, I believe you meant as follows below:
def isPrime(x):
x = int(x)
for i in range(2, x):
if (x % i) == 0:
x = False
else:
x = True
return x
print(isPrime(input("Enter a prime number.")))
## Which runs as follows in python IDLE:
>>> def isPrime(x):
x = int(x)
for i in range(2, x):
if (x % i) == 0:
x = False
else:
x = True
return x
>>> print(isPrime(input("Enter a prime number.")))
Enter a prime number.11
True
>>> print(isPrime(input("Enter a prime number.")))
Enter a prime number.100
False
I know when I started out, I made many typing errors.
By rereading my code and lots of practice, I slowly got better.
Here's a how I would write out your task.
def isPrime(h):
h = int(h)
test = None
for x in range(2, h):
if (h%x) == 0:
test = False
print(f"{test}, the number {h} is not a prime!")
break
else:
test = True
print(f"{test}ly, the number {h} is a prime!")
## Then I'll run the call to the function in python IDLE as:
>>>
>>> isPrime(input("Enter a number.\n"))
Enter a number.
11
Truely, the number 11 is a prime!
>>>
>>> isPrime(input("Enter a number.\n"))
Enter a number.
110
False, the number 110 is not a prime!
>>>
One of most important things, that really helped me was:
reading others code (and the docs!!)
then play with their code in IDLE
repeat the above <--------(I still do this all the time!!)
How would I make my code round any value that has a decimal point of x.999999999?
The code so far I have is:
y = int(input("Enter a cube number "))
cuberoot = y**(1/3)
if cuberoot.is_integer():
print("integer")
else:
if cuberoot == HERE.9999999:
print("Integer")
else:
print("not integer")
help
(where it says "HERE" is what do i put there)
Use modulo operator.
y = int(input("Enter a cube number "))
cuberoot = y ** (1/3)
fraction = cuberoot % 1
if fraction == 0 or fraction > 0.999999:
print("integer")
else:
print("not integer")
Using an error-tolerance will give you incorrect results for large numbers. For example, 1012 - 1 is not a cube, but (10**12 - 1) ** (1/3) is 9999.999999996662 which would pass your test.
A safer way to do this would be to round it to an integer, then check whether it has the right cube:
def is_cube(x):
y = x ** (1/3)
y = int(round(y))
if y ** 3 == x:
print('Integer')
else:
print('Not integer')
Examples:
>>> is_cube(27)
Integer
>>> is_cube(28)
Not integer
>>> is_cube(10**12)
Integer
>>> is_cube(10**12 - 1)
Not integer
However, note that this won't work for very large numbers, since x ** (1/3) is done using floating-point numbers, so the error might be greater than 0.5, in which case the rounding will give the wrong result. For example, the above code fails for the input 10 ** 45.
I've made a program which takes number of test cases as input and for each test case, it needs a number as input. Finally it checks whether the numbers you have entered are fibonacci numbers or not and prints accordingly. I've had no problems running it on my PC.But when i upload it to CodeChef.com(where i saw this quesion), it shows runtime error.
Any help is appreciated and as i'm a noob my code might look lengthy ., any modifications are welcome.Thanks!
Here's my code:
def isperfect(n):
import math
if n < 0:
print("No Solution")
return False
else:
test = int(math.sqrt(n))
return test*test == n
test_cases = int(input())
count = 0
store = []
while count < test_cases:
x = int(input())
store.append(x)
count += 1
for each_item in store:
assert isinstance(each_item, int)
s1 = 5*each_item*each_item-4
s2 = 5*each_item*each_item+4
if(isperfect(s1) == True or isperfect(s2) == True):
print("YES")
else:
print("NO")
This is the most elegant solution i've encountered:
def is_fibonacci(n):
phi = 0.5 + 0.5 * math.sqrt(5.0)
a = phi * n
return n == 0 or abs(round(a) - a) < 1.0 / n
The code is not mine, was posted by #sven-marnach.
The original post:
check-input-that-belong-to-fibonacci-numbers-in-python
The runtime error is apparently due to an exception, but Codechef does not provide any more information. It could be various things including divide by zero, memory exhaustion, assertion failure, ...
Although your program works for many common numbers, it doesn't handle all the inputs that the Codechef constraints allow. In particular, the number to be tested can have up to 1000 digits in it. If you try a large input like a 1000-digit number, you'll find it fails. First it fails because of your assert isinstance(each_item, int); a number of 12 digits or more is not of type int. You can just remove the assertion. The next failure occurs because you are using the floating point sqrt routine, and that requires the integer to be converted into floating point. Python can handle very long integers, but the floating point representation is more limited in its precision, and cannot handle 1000 digit integer conversions. That's harder to fix, but can be done. See this ActiveState recipe for an all-integer solution for square root.
I've figured that this can be done by using Newton- Raphson method, i have replaced the code in the function isperfect() with Newton-Raphson formula code, removed assertion and it worked. Thanks for all your help.
Here's the final code:
def isperfect(n):
x = n
y = (x + n // x) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x*x == n
test_cases = int(input())
count = 0
store = []
while count < test_cases:
x = int(input())
store.append(x)
count += 1
for each_item in store:
s1 = 5*each_item*each_item-4
s2 = 5*each_item*each_item+4
if(isperfect(s1) == True or isperfect(s2) == True):
print("YES")
else:
print("NO")
This is going to be a very efficient way of doing it.
In [65]:
import scipy.optimize as so
from numpy import *
In [66]:
def fib(n):
s5=sqrt(5.)
return sqrt(0.2)*(((1+s5)/2.)**n-((1-s5)/2.)**n)
def apx_fib(n):
s5=sqrt(5.)
return sqrt(0.2)*(0.5*(1+s5))**n
def solve_fib(f):
_f=lambda x, y: (apx_fib(x)-y)**2
return so.fmin_slsqp(_f,0., args=(f,),iprint=0)
def test_fib(fibn):
if fibn<1:
print 'No, it is not'
else:
n=int(round(solve_fib(fibn)))
if int(round(fib(n)))==int(fibn):
print 'Yes, it is. (%d)'%n
else:
print 'No, it is not'
In [67]:
asarray(fib(arange(1,20)), dtype='int64')
Out[67]:
array([ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, 233, 377, 610, 987, 1597, 2584, 4181])
In [68]:
test_fib(34)
Yes, it is. (9)
In [69]:
test_fib(4181)
Yes, it is. (19)
In [70]:
test_fib(4444)
No, it is not
Fairly simple and efficient way of doing it
def isInFib(n):
if n == 0: return False
elif n == 1: return True
else:
A = 1
B = 1
FLIP = True
while(True):
new = A + B
if new > n: return False
elif new == n: return True
else:
if(FLIP):
A = new
FLIP = not FLIP
else:
B = new
FLIP = not FLIP
Explanation of Algorithm
I first check if my input is equal to 0 or 1, and return appropriate.
If my input is greater than 1, we go into the else, infinite loop.
A and B represent the last two previous numbers in the sequence. We add A and B to get new, the current Fibonacci number.
We check if new is equal to our input number, if that's true we return true, we are done and complete the function.
If it's greater, that means our number is not in the Fibonacci sequence, since we have surpassed it.
if it's less, we need to keep going! and this is where I think it get's confusing to explain. I want to set up A or B as my current fibonacci sequence number (new), but I have make sure that I keep switching between them, since I don't want one to get left behind. Fibonacci sequence takes the previous 2 numbers and adds them together. I want A and B to be my last two previous sums.
I'll use an example
1,1,2,3,5,8,13
A and B are initially 1. So new is equal to 2 first. I then check if I'm over my input number or equal to it. But if my input number is less. I want to keep going.
I want A to equal new (value = 2) then, before we get to our next iteration of the while loop. So that new will equal 2 + 1 as A + B on the next iteration.
But, then THE next iteration of the loop, I want to set B as 3, and I want to leave A being equal to 2. So I have to keep switching between putting the current fibonacci number I'm at, in A or B. And that's why I have the flip logic! It just keeps switching between True and False.
Try this function:
def isfib(number):
num1 = 1
num2 = 1
while True:
if num2 <= number:
if num2 == number:
return True
else:
tempnum = num2
num2 += num1
num1 = tempnum
else:
return False
Here's how it works:
Set num1 and num2 to 0.
If num2 isn't less than or equal to the number return False.
If num2 is equal to the number return True.
Set add num1 to num2, set num1 to num2's original value and go back to step 2.
num=int(input("Enter a number : "))
n1=0
n2=1
i=1
lst=[]
lst.append(n1)
lst.append(n2)
while i<num-1:
n3=n1+n2
n1=n2
n2=n3
lst.append(n3)
i=i+1
for i in lst:
if (num == i):
print("Fibonacci number")
break
else:
print("Not fibonacci")
def isfib(number):
num1 = 0
num2 = 1
while True:
if num2 <= number:
if num2 == number:
return True
else:
tempnum = num2
num2 += num1
num1 = tempnum
else:
return False
n=int(input())
number=n
fibonacci=isfib(number)
if (fibonacci):
print("true")
elif n==0:
print("true")
else:
print("false")