I am making some code that allows me to choose the closest number from a list, I have managed to do that. However when the closest number is found and its over 'myNumber' I want python to print out the number in the list before it.
For example;
if i were to have a list;
TwoN = [1,2,4,8,16,32,64,128,256,512, 1024, 2048, 4096, 8192]
and
myNumber = 30
I want python to print 16 not 32
This is the code i've done so far...
TwoN = []
for i in range(12):
TwoN.append(2**i)
print(TwoN)
myNumber = 30
closest = TwoN[0]
for i in range(1, len(TwoN)):
if abs(TwoN[i] - myNumber) < abs(closest - myNumber):
closest = TwoN[i];
Sum = myNumber - closest
if Sum < 0:
closest = TwoN[(i-1)]
print(closest)
else:
print(closest)
When myNumber = 30 , the program will output 1024 when i want it to output 16..
any help is appreciated thanks