So I supposed to verify if the input number is a UPC number or not. I have to allowed leading zeros and accounted it in the calculation.
Here is my current code, it works for all number except number has leading zeros:
Condition for UPC code valid:
Calculate the sum of multiplying odd digit index by 3 and even digit index by 1 of the input number.
Calculate the sum we just did modulo 10, get result digit.
If the resulting digit is between 1 and 9 then subtract result digit from 10. If the result digit is 0, add 0 to the to the base number to get the completed number.
def UPC_code(num):
sum_digit = 0
index = 0
num_temp = str(num)[:-1]
len_nt = len(num_temp)
for digit in num_temp:
if (index + 1) % 2 != 0: # If number position is odd
sum_digit += int(digit) * 3 # Sum = digit * 3
if index < len_nt: # Increase index till end
index += 1
elif (index + 1) % 2 == 0: # If number position is even
sum_digit += int(digit) * 1 # Sum = digit * 1
if index < len_nt:
index += 1
# print(sum_digit)
res_digit = sum_digit % 10
if 1 <= res_digit <= 9:
res_digit = 10 - res_digit # Res digit meet condition = 10 - res digit
if res_digit == num % 10:
return True
elif res_digit != num % 10:
return False
else:
print("Something went wrong")
# End UPC_code()
Call UPC_code()
import code_check.py as cc
num = str(input())
num_int = int(num)
if cc.UPC_code(num_int) is True and num_int != 0:
print(num, "valid UPC code.")
else:
print("Not valid")
Expected input:
042100005264
Expected output:
042100005264 valid UPC code
Actual output:
Not valid
it works for all number except number has leading zeros
As you have doubtless discovered, python does not allow you to write 0700. Historically that would have meant 0o700, or 448, which is likely not what you want anyhow...
In this case the solution is simple. If you need to handle numbers like 00007878979345, handle strings.
Thus refactor your code to take a string. As a bonus, int("000008") is 8, so when you need the number as a number you don't even have to do anything.
We have a program that changes decimals to binary.
And the goal is to run the program, input a value, and outputs the value in binary.
The problem with my code is that it has trailing zeros when outputting the binary.
I need to achieve this without using external libraries like "math", so please stick to the built-in functions.
Current output:
Insert a value:
5
The number fits in 1 byte and is in binary:
00000101
Insert a value:
100
The number fits in 1 byte and is in binary:
01100100
Insert a value:
280
The number fits in 16 bits and is in binary:
0000000100011000
Expected output:
Insert a value:
5
The number fits in 1 byte and is in binary:
101
Insert a value:
100
The number fits in 1 byte and is in binary:
1100100
Insert a value:
280
The number fits in 16 bits and is in binary:
100011000
Current code:
def dec2bin(value, number_bits):
result = ''
while number_bits > 0:
bit_value = 2 ** (number_bits - 1)
if value >= bit_value:
result = result + '1'
value = value - bit_value
else:
result = result + '0'
number_bits = number_bits - 1
print(result)
input_ok = False
userinput = 0
while not input_ok:
print('Insert a value:')
userinput = int(input())
if userinput > 65535:
print('invalid, cant handle that big numbers, try again')
else:
input_ok = True
if userinput < 256:
print('The number fits in 1 byte and is in binary:')
dec2bin(userinput, 8)
else:
print('The number fits in 16 bits and is in binary:')
dec2bin(userinput, 16)
It easy with string formatting functions (see Pranav's comment). But perhaps in this case you want the algorithm to take care of it, and see treating it as a string is cheating.
def dec2bin(value, number_bits):
result = ''
starting = True
while number_bits > 0:
bit_value = 2 ** (number_bits - 1)
if value >= bit_value:
result = result + '1'
value = value - bit_value
starting = False
elif not starting:
result = result + '0'
number_bits = number_bits - 1
print(result)
Since you are storing the value as a string you can use
result.lstrip('0')
to remove the leading zeros from your answer.
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.
decimal = input("Please insert a number: ")
if decimal > 256:
print "Value too big!"
elif decimal < 1:
print "Value too small!"
else:
decimal % 2
binary1 = []
binary0 = []
if decimal % 2 == 0:
binary1.append[decimal]
else:
binary0.append[decimal]
print binary1
print binary0
So Far, I want to test this code, it says on line 13:
TypeError: builtin_function_or_method' object has no attribute
__getitem__.
I don't understand why it is wrong.
I would like to convert the decimal number into binary. I only wanted to try and get the first value of the input then store it in a list to use then add it to another list as either a 0, or a 1. And if the input doesn't divide by 2 equally, add a zero. How would I do this?
binary1.append[decimal]
You tried to get an element from the append method, hence triggering the error. Since it's a function or method, you need to use the appropriate syntax to invoke it.
binary1.append(decimal)
Ditto for the other append call.
In response to your binary question. It is possible to brute-force your way to a solution quite easily. The thinking behind this is we will take any number N and then subtract N by 2 to the biggest power that will be less than N. For instance.
N = 80
2^6 = 64
In binary this is represented as 1000000.
Now take N - 2^6 to get 16.
Find the biggest power 2 can be applied to while being less than or equal to N.
2^4 = 16
In binary this now represented as 1010000.
For the actual code.
bList = []
n = int(raw_input("Enter a number"))
for i in range(n, 0, -1): # we will start at the number, could be better but I am lazy, obviously 2^n will be greater than N
if 2**i <= n: # we see if 2^i will be less than or equal to N
bList.append(int( "1" + "0" * i) ) # this transfers the number into decimal
n -= 2**i # subtract the input from what we got to find the next binary number
print 2**i
print sum(bList) # sum the binary together to get final binary answer
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")