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.
Related
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.
I encountered an issue with my Python script that converts binary to decimals. The caveat with this script is that I can only use basic computational functions (+, -, *, /, **, %, //), if/else, and for/while loops.
Shown below is my script:
x = int(input("Enter your binary input: "))
z=0
while x != 0:
for y in range (0,20):
if (x % 2 == 0):
z += 0*2**y
x = int(x/10)
elif (x % 2 != 0):
z += 1*2**y
x = int(x/10)
print(z)
While my script works for binaries with short length (e.g., 1101 = 13), it does not work for long binaries (especially those that have a length of 20). For example, inputting a binary of 11111010010011000111, my script returns an output of 1025217 instead of 1025223.
Can anyone point me to my mistake?
Thank you in advance!
Floating arithmetic isn't perfect and has a precision limit.
11111010010011000111 / 10 gives 1.1111010010011e+18, which when converted to an integer will give you a wrong result and it snowballs from there.
>>> int(11111010010011000111 / 10)
1111101001001100032
The more binary digits you have, the more "off" your calcuations will be.
In order to avoid the problem you encountered, use floor division, ie, x // 10.
Or you can skip turning x into a number and do the necessary power calculations based off each binary digit and its position.
x = input("Enter your binary input: ")[::-1]
n = 0
# this would be more elegant with `enumerate()`, but I assume you can't use it
# same for `sum()` and a comprehension list
for i in range(len(x)):
n += int(x[i])*2**i
print(n)
You can use the following method
to multiple each of the binary digits with its corresponding value of 2 raised to the power to its index (position from right – 1) and sum them up.
binary = input('Binary number: ')
decimal = 0
binary_len = len(binary)
for x in binary:
binary_len = binary_len - 1
decimal += pow(2,binary_len) * int(x)
print(decimal)
input : 11111010010011000111
output : 1025223
More examples
You should not use int to convert any number if you have to write a number converter.
Just use string operations:
digits = input("Enter your binary input: ")
number = 0
for digit in digits:
number = number * 2 + (digit == "1")
print(number)
output
Enter your binary input: 11111010010011000111
1025223
I am trying to define a function to convert a binary number to a decimal number and check if it is an absolute square or not. I am passing a list of binary numbers as the argument and the function is supposed to print "True" or "False" as the output in the same order as that of the list elements; depicting whether or not they are absolute squares.
While trying so I am getting a syntax error in the ninth line where I am trying to calculate the decimal equivalent of the binary digits by adding the individual values arising out of each binary digit owing to it's position.
Logic of Execution: 1001 in Binary means [pow(2,3)*1 + pow(2,2)*0 + pow(2,1)*0 + pow(2,0)*1] in Decimal. It's equal to 9 which is an absolute square of 3. So the output should be "True"
import math
n = int(input("Enter the total no of elements to check: "))
num_list = []
for k in range (n):
print("Enter the number at position "+str(k)+" : ")
num = int(input())
num_list.append(num)
#print(num_list) for debugging purpose
def Binary_SquareRoot_Checker(input_list):
for i in input_list:
q = str(i)
no_of_digit = len(q)
#For each element of the list, we need to count the no of digits present
addition_num = 0
for p in range (no_of_digit):
r = q[p]
value = (2**(no_of_digit - (p+1)) * int(r)
addition_num = addition_num + value
#print(addition_num) just to see the decimal number
root = math.sqrt(sum_num)
if int(root + 0.5) ** 2 == sum_num:
#Checking for absolute square property
print("True")
else:
print("False")
Binary_SquareRoot_Checker(num_list)
I am getting Syntax Error at addition_num = addition_num + value
Please tell me why this error is being reported?
In the 20th line, change:
value = (2**(no_of_digit - (p+1)) * int(r)
To:
value = (2**(no_of_digit - (p+1)) * int(r) )
I want floating numbers be limited for example to 8. When I run the below code it gives me 16 floating numbers. For example, x=4 and y=3, it gives 1.3333333333333333. How can I reduce the number of "3"s. NOTE: I DON'T WANT TO ROUND, JUST LIMIT "3"s.
x=int(input())
y=int(input())
print(x/y)
You can easily do that if you
multiply the number by a power of 10
convert the number to int and
at last divide the number by the power of 10
So the code:
def limit_num(num, limit):
num = num * 10**limit
num = int(num)
num /= 10**limit
return num
number = 4/3 # 1.3333333333333333
number = limit_num(number, 5)
print(number) # 1.33333
Or in one line:
def limit_num(num, limit):
return (int(num * 10**limit) / 10**limit)
round will not give you correct result if decimal digits are 999 types.
You should convert float to string and try
def truncate_float_decimal(float_num, truncate_to_digits):
base_length = len(float_num.split('.')[0])+1
base_length += truncate_to_digits
return float((float_num[:base_length]))
truncated_float = truncate_float_decimal("14.999992223",7)
print (truncated_float)
I need to create a program that adds together all the intergers in a number together. For enstance if i input 5, the program will look at it as if it were 1+2+3+4+5 and output 15. I need to do this for any number about 0. I also have to complete this using loops with python. Here is what i have so far.
print("This program calculates the sum of all integers from 1 to the input value.")
t=0
x=int(input("Please enter an integer: "))
while x>0:
print(t)
x=int(input("Please enter an integer: "))
The range function in python, when passed a single integer, returns a list of numbers leading up to it, from zero. sum returns the sum of all numbers in a list.
So, to print the sum of all numbers from zero to x, you would do this:
print(sum(range(x+1)))
To find the sum from 1 to n including, you could use n * (n + 1) // 2 formula e.g.,
n=5: 5 * (5 + 1) // 2 = 15:
print("This program calculates the sum of all integers "
"from 1 to the input value.")
while True:
x = int(input("Please enter an integer: "))
if x <= 0:
break
print(x * (x + 1) // 2) # print sum