python is skipping over my if statement - python

N1 = int(input("What interger do you wish to turn to binary (from 0 - 7 only!)"))
while (N1 > 7) or (N1 <0) :
N1 = int(input("You input must be from 0 - 7 only!"))
while True:
if N1 == 0:
print ("0 0 0")
break
else:
a = (N1 - 4)
if a < 0:
a = 0
else:
a = 1
N1 = a
b = (N1 - 2)
if b < 0:
b = 0
else:
b = 1
N1 = b
c = (N1 - 1)
if c < 0:
c = 0
else:
c = 1
print(a,b,c)
break
this program turns int to binary but it's skipping line 8-13 why?

In this bit:
a = (N1 - 4)
if a < 0:
a = 0
else:
a = 1
N1 = a
After the else, you first set the value of a to 1, and then copy that value to N1. So, your program forgot what N1 was, and the outcome for b and c will always be the same. (The same problem happens again for b and c.)
By the way, there are more efficient ways to figure out the binary representation of a number. Hint: use the & operator to find out whether the last bit of a number is 1, and use the >> operator to shift all bits of the number to the right.

The naive way to fix it is to remove N1 at each case and subtract different values when running if statements since N1 doesn't update while executing the second while loop. You should always avoid this happening in your codes:
N1 = int(input("What interger do you wish to turn to binary (from 0 - 7 only!)"))
while (N1 > 7) or (N1 <0) :
N1 = int(input("You input must be from 0 - 7 only!"))
while True:
if N1 == 0:
print ("0 0 0")
break
else:
a = (N1 - 4)
if a < 0:
a = 0
else:
a = 1
b = (N1 - 6)
if b < 0:
b = 0
else:
b = 1
c = (N1 - 7)
if c < 0:
c = 0
else:
c = 1
print(a,b,c)
break
But you can do it in an iterative style:
N1 = int(input("What interger do you wish to turn to binary (from 0 - 7 only!)"))
if (N1 > 7) or (N1 <0) :
N1 = int(input("You input must be from 0 - 7 only!"))
else:
binary = []
if N1 == 0:
print ("0 0 0")
for i in range (0,3):
if (N1 - pow(2,(2 - i))) >= 0:
binary.append(1)
N1 = N1 - pow(2,(2 - i))
else:
binary.append(0)
print binary

... I've test it and it works! ( it works only when a < 0 so only with N1 < 4 because a = N1-4, 4 - 4 = 0, 0 = 0, so 0 not < 0, and the if statement doesn't work with 4, and naturally doesn't work with 5, 6, 7... too )

Related

How do I print 4 numbers in each row in python?

How do I print 4 numbers in a row? I am a complete beginner. This is Python code I did for Fibonacci sequence.
For example, if I put 6 as an input, I get
0 1 1 2 3 5
However, I want to get it like
0 1 1 2
3 5
Code:
i = 1
n1 = 0
n2 = 1
seq = n1 + n2
num = int(input("Enter a positive number: "))
while i <= num:
print(n1, end = " ")
n1 = n2
n2 = seq
seq = n1 + n2
i += 1
print()
print(n1, end = " " if i % 4 else "\n")

A test interview question I could not figure out

So I wrote a piece of code in pycharm
to solve this problem:
pick any 5 positive integers that add up to 100
and by addition,subtraction or just using one of the five values
you should be able to make every number up to 100
for example
1,22,2,3,4
for 1 I could give in 1
for 2 i could give in 2
so on
for 21 I could give 22 - 1
for 25 I could give (22 + 2) - 1
li = [1, 1, 1, 1, 1]
lists_of_li_that_pass_T1 = []
while True:
if sum(li) == 100:
list_of_li_that_pass_T1.append(li)
if li[-1] != 100:
li[-1] += 1
else:
li[-1] = 1
if li[-2] != 100:
li[-2] += 1
else:
li[-2] = 1
if li[-3] != 100:
li[-3] += 1
else:
li[-3] = 1
if li[-4] != 100:
li[-4] += 1
else:
li[-4] = 1
if li[-5] != 100:
li[-5] += 1
else:
break
else:
if li[-1] != 100:
li[-1] += 1
else:
li[-1] = 1
if li[-2] != 100:
li[-2] += 1
else:
li[-2] = 1
if li[-3] != 100:
li[-3] += 1
else:
li[-3] = 1
if li[-4] != 100:
li[-4] += 1
else:
li[-4] = 1
if li[-5] != 100:
li[-5] += 1
else:
break
this should give me all the number combinations that add up to 100 out of the total 1*10 ** 10
but its not working please help me fix it so it prints all of the sets of integers
I also can't think of what I would do next to get the perfect sets that solve the problem
After #JohnY comments, I assume that the question is:
Find a set of 5 integers meeting the following requirements:
their sum is 100
any number in the [1, 100] range can be constructed using at most once the elements of the set and only additions and substractions
A brute force way is certainly possible, but proving that any number can be constructed that way would be tedious. But a divide and conquer strategy is possible: to construct all numbers up to n with a set of m numbers u0..., um-1, it is enough to build all numbers up to (n+2)/3 with u0..., um-2 and use um-1 = 2*n/3. Any number in the ((n+2)/3, um-1) range can be written as um-1-x with x in the [1, (n+2)/3] range, and any number in the (um-1, n] range as um-1+y with y in the same low range.
So we can use here u4 = 66 and find a way to build numbers up to 34 with 4 numbers.
Let us iterate: u3 = 24 and build numbers up to 12 with 3 numbers.
One more step u2 = 8 and build numbers up to 4 with 2 numbers.
Ok: u0 = 1 and u1 = 3 give immediately:
1 = u0
2 = 3 - 1 = u1 - u0
3 = u1
4 = 3 + 1 = u1 + u0
Done.
Mathematical disgression:
In fact u0 = 1 and u1 = 3 can build all numbers up to 4, so we can use u2 = 9 to build all numbers up to 9+4 = 13. We can prove easily that the sequence ui = 3i verifies sum(ui for i in [0, m-1]) = 1 + 3 + ... + 3m-1 = (3m - 1)/(3 - 1) = (um - 1) / 2.
So we could use u0=1, u1=3, u2=9, u3=27 to build all numbers up to 40, and finally set u4 = 60.
In fact, u0 and u1 can only be 1 and 3 and u2 can be 8 or 9. Then if u2 == 8, u3 can be in the [22, 25] range, and if u2 == 9, u3 can be in the [21, 27] range. The high limit is given by the 3i sequence, and the low limit is given by the requirement to build numbers up to 12 with 3 numbers, and up to 34 with 4 ones.
No code was used, but I think that way much quicker and less error prone. It is now possible to use Python to show that all numbers up to 100 can be constructed from one of those sets using the divide and conquer strategy.

Variable takes negative value while it is restricted to be nonnegative

I am programming a vehicle routing problem in Python with PuLP. I got all my code in it, but for some reason I get a negative value for one of my decision variables, even though I restricted all of them to be nonnegative.
My code is as follows (Traveltimes is a two dimensional np array, with travel times between each pair of customers (i,j), where c(i,j) = c(j,i) and c(i,i) = 0.):
My code:
numVehicles = 2
numCustomers = 2
prob = LpProblem("DSP", LpMinimize)
var = [[[0 for k in range(numVehicles)] for j in range(numCustomers+1)] for i in range(numCustomers+1)]
for i in range(numCustomers+1):
for j in range(numCustomers+1):
for k in range(numVehicles):
var[i][j][k] = LpVariable("x"+str(i)+","+str(j)+","+str(k), 0,1, cat='Binary')
# ADD OBJECTIVE
obj = ""
for i in range(numCustomers+1):
for j in range(numCustomers+1):
for k in range(numVehicles):
obj += traveltimes[i][j]*var[i][j][k]
prob += obj
# ADD CONSTRAINTS
# All customers visited
for j in range(numCustomers+1):
for k in range(numVehicles):
nr = ""
for i in range(numCustomers+1):
nr += var[i][j][k]
prob += nr == 1
# Enter each customer exactly once
for i in range(numCustomers+1):
nr = ""
for k in range(numVehicles):
for j in range(1, numCustomers+1):
nr += var[i][j][k]
prob += nr == 1
# Leave each customer exactly once
for j in range(numCustomers+1):
nr = ""
for k in range(numVehicles):
for i in range(1, numCustomers+1):
nr += var[i][j][k]
prob += nr == 1
# Per vehicle only one customer can be visited as first
nrFirst = ""
for k in range(numVehicles):
for j in range(numCustomers+1):
nrFirst += var[0][j][k]
prob += nrFirst <= 1
# Max num vehicles
nrOut = ""
for k in range(numVehicles):
for j in range(numCustomers+1):
nrOut += var[0][j][k]
prob += nrOut <= numVehicles
# Restrict x(0,j,k) to be nonpositive
for j in range(numCustomers+1):
for k in range(numVehicles):
prob += var[0][j][k] >= 0
print(prob)
# Solve LP
prob.solve()
for v in prob.variables():
print(v.name, "=", v.varValue)
print("objective=", value(prob.objective))
The first output is the formulation printed
MINIMIZE
1.731*x0,1,0 + 1.731*x0,1,1 + 2.983*x0,2,0 + 2.983*x0,2,1 + 1.731*x1,0,0 + 1.731*x1,0,1 + 9.375*x1,2,0 + 9.375*x1,2,1 + 2.983*x2,0,0 + 2.983*x2,0,1 + 9.375*x2,1,0 + 9.375*x2,1,1 + 0.0
SUBJECT TO
_C1: x0,0,0 + x1,0,0 + x2,0,0 = 1
_C2: x0,0,1 + x1,0,1 + x2,0,1 = 1
_C3: x0,1,0 + x1,1,0 + x2,1,0 = 1
_C4: x0,1,1 + x1,1,1 + x2,1,1 = 1
_C5: x0,2,0 + x1,2,0 + x2,2,0 = 1
_C6: x0,2,1 + x1,2,1 + x2,2,1 = 1
_C7: x0,1,0 + x0,1,1 + x0,2,0 + x0,2,1 <= 1
_C8: x1,1,0 + x1,1,1 + x1,2,0 + x1,2,1 <= 1
_C9: x2,1,0 + x2,1,1 + x2,2,0 + x2,2,1 <= 1
_C10: x0,0,0 + x0,1,0 + x0,2,0 <= 1
_C11: x0,0,0 + x0,0,1 + x0,1,0 + x0,1,1 + x0,2,0 + x0,2,1 <= 1
VARIABLES
0 <= x0,0,0 <= 1 Integer
0 <= x0,0,1 <= 1 Integer
0 <= x0,1,0 <= 1 Integer
0 <= x0,1,1 <= 1 Integer
0 <= x0,2,0 <= 1 Integer
0 <= x0,2,1 <= 1 Integer
0 <= x1,0,0 <= 1 Integer
0 <= x1,0,1 <= 1 Integer
0 <= x1,1,0 <= 1 Integer
0 <= x1,1,1 <= 1 Integer
0 <= x1,2,0 <= 1 Integer
0 <= x1,2,1 <= 1 Integer
0 <= x2,0,0 <= 1 Integer
0 <= x2,0,1 <= 1 Integer
0 <= x2,1,0 <= 1 Integer
0 <= x2,1,1 <= 1 Integer
0 <= x2,2,0 <= 1 Integer
0 <= x2,2,1 <= 1 Integer
It can clearly be observed that all variables are restricted to be an integer between 0 and 1 (thus binary). However, for some reason, I do get negative values for some variable(s), as can be seen below
x0,0,0 = 0.0
x0,0,1 = -1.0
x0,1,0 = 0.0
x0,1,1 = 1.0
x0,2,0 = 0.0
x0,2,1 = 1.0
x1,0,0 = 1.0
x1,0,1 = 1.0
x1,1,0 = 1.0
x1,1,1 = 0.0
x1,2,0 = 0.0
x1,2,1 = 0.0
x2,0,0 = 0.0
x2,0,1 = 1.0
x2,1,0 = 0.0
x2,1,1 = 0.0
x2,2,0 = 1.0
x2,2,1 = 0.0
objective= 11.159
Really looking forward to any suggestions on how to solve this problem, since I clearly do not want negative values!
As a few others have suggested you should write a Minimum Complete and Verifiable Example.
That said, if you are getting constraints violated, and you are sure you've implemented them correctly, I reckon you have an infeasible problem (i.e. if you looked at your constraints carefully you would find there is a combination which makes solving impossible).
To check this add:
print (("Status:"), LpStatus[prob.status])
Just after you do prob.solve(). I reckon you'll find it's infeasible.
prob += nr == 1
"+=" is for assignment
"==" is checking for equivalence, and belongs in an "if" statement or a "while".
For instance:
if prob + nr == 1: #execute what follows if prob + nr is equal to 1

Make a random number more probable in python

I'm using numpy.random.rand(1) to generate a number between 0-1 and the values of a and b change depending on what the number is. How can I make the probability of x > .5 and x < .5 be proportional to a and b? So if a is 75 and b is 15 then the probability of x > .5 is 5 times more probable than x < .5. I'm unsure as to what codes to use to assign probabilities. This is what I have:
a = 100
b = 100
while True:
x = numpy.random.rand(1)
print x
if x < .5:
a = a + 10
b = b - 10
print a
print b
if x > .5:
b = b + 10
a = a - 10
print a
print b
if b1 == 0:
print a
break
if b2 == 0:
print b
break
I'd make two calls to random: One to calculate a random number between 0 and 0.5 and a second to determine if the number should be above 0.5.
For example;
a = 100
b = 100
x = numpy.random.rand(1)/2.0
proportion = a/(1.0*b+a)
if numpy.random.rand(1) > proportion:
x += 0.5
what a fitting name.
ratio = a/b
x = numpy.random.uniform(0.5 + ratio*0.5)
now you have a numbers distributed between 0 and the ratio multiplied by 0.5. With uniform distribution, the ratio between the population of numbers greater than 0.5 and the population lower than 0.5 is the desired ratio.
now we just need to broadcast those ranges to be between 0.5 and 1.0.
if x >= 0.5:
x = x - math.trunc(x)
if int(str(number-int(x))[1:]) < 5:
x += 0.5
In this case I would have numpy generate a number between 1 and 100 then assign based on that. I.e. (pusdocode)
if rand(100) => 50: a=0
else: a=1
then all you have to do is changed the 50 to whatever the % you want. I can elaborate further if that is confusing.
def get_rand_value(a, b):
if rand(100) => a:
return True
else:
return 1
a = 100
b = 100
while True:
x = get_rand_value(a, b)
print x
if x < .5:
a = a + 10
b = b - 10
print a
print b
if x > .5:
b = b + 10
a = a - 10
print a
print b
if b1 == 0:
print a
break
if b2 == 0:
print b
break

Is this working properly - Sum of Fibonacci in Python 3

I have a task to make a program that will sum the first 100 Fibonacci numbers. I checked my output in Python, and my output in QBasic 64 and they aren't same. I checked with different inputs also.
Input: 10
Output: 89
-----------
Input: 100
Output: 573147844013817084101
Is it correct ?
Here is my code:
n = int(input())
print()
p = 0
d = 1
z = p + d
print(str(p) + ' + ' + str(d) + ' = ' + str(z))
for i in range(n - 2):
p = d
d = z
z = p + d
print(str(p) + ' + ' + str(d) + ' = ' + str(z))
print('Sum:', z)
EDIT: Code edited again, check it now. I just found on Wikipedia.. It depends from what number you start the loop. So if I use (0, 1, 1, 2, 3, 5, 8, 13, 21, and 34) as first 10 Fibonacci numbers, the sum is going to be 88, not 89.
The sums of the first ten and 100 fibonacchi number would be 88 and 573147844013817084100, respectively:
>>> cache = {}
>>> def fib(n):
if n == 0: return 0
if n == 1: return 1
if not n in cache:
cache[n] = fib(n - 1) + fib(n - 2)
return cache[n]
>>> sum([fib(i) for i in range(10)])
88
>>> sum([fib(i) for i in range(100)])
573147844013817084100
In your loop you are already starting the iteration at the 3rd position, since you set. So set your range to (n -2).
0: 1
1 : 1
2 : 1
3 : 2
4 : 3
5 : 5
To get the sum of the Fibonacci numbers, using zero as the first in the series, you need to do this:
def run_it(n):
N2 = 0
N1 = 0
N = 0
z = N
for i in range(n):
print(N,z)
N2 = N1
N1 = N
if N is 0: N = 1
else: N = N1 + N2
z = z + N
run_it(int(input('Number: ')))
To calculate the sum using one as the start of the series, change the initial value of N from zero to one.

Categories