I am testing a simple linear diophantine equations code. Here is the code:
a = 3
b = 4
n = 67
i = 0
while True:
if i * a <= n:
if (n - (i * a)) % b == 0:
yy = int((n - (i * a)) / b)
print("{0} x {1} + {2} x {3} = {4}".format(a, i, b, yy, n))
i = i + 1
else:
print("No possible solution!")
break
When the code is run, it is able to find the possible x and y in this equation (which is fine). But, what I can't figure out is why is the print "No Possible solution!" is getting printed together with the answer. The else block is suppose to appear only if a solution is not possible e.g a = 3, b = 4 and n = 2.
Any advice will be appreciated.
print("No possible solution!") is inside the else case so it will execute regardless of whether any solutions were found or not.
Here is one way to fix it where a boolean variable keeps track of whether a solution was found or not and prints the message based on the state of that variable:
a = 3
b = 4
n = 2
i = 0
solution_found = False
while True:
if i * a <= n:
if (n - (i * a)) % b == 0:
yy = int((n - (i * a)) / b)
print("{0} x {1} + {2} x {3} = {4}".format(a, i, b, yy, n))
solution_found = True
i = i + 1
else:
break
if not solution_found:
print("No possible solution!")
Use flag to identify solution is available or not.
a = 3
b = 4
n = 67
i = 0
isSolutionAvailable=False
while True:
if i * a <= n:
if (n - (i * a)) % b == 0:
yy = int((n - (i * a)) / b)
print("{0} x {1} + {2} x {3} = {4}".format(a, i, b, yy, n))
isSolutionAvailable=True
i = i + 1
else:
break
if(not(isSolutionAvailable)):
print("No possible solution!")
Related
I am trying to solve quadratic equations using Python, my program finds solutions but first one is being calculated wrong, I checked the code several times and can't find what am I doing wrong
a = 2 # random.randint(1, 10)
b = 9 # random.randint(-110, 10000)
c = 4 # random.randint(-10000, 10000000)
d = (b ** 2) + (- 4 * a * c)
print(d)
if d < 0:
print('x does not exist')
elif d == 0:
print((-1 * b) / 2 * a)
else:
print('x exists')
def sqrt(n):
if n < 0:
return
else:
return n ** 0.5
x_1 = (-1 * b - sqrt(b)) / 4
x_2 = (-1 * b + sqrt(b)) / 4
print(f'solution 1 is: {round(x_1)}, solution 2 is: {round(x_2)}')
In the formula:
x_1 = (-1 * b - sqrt(b)) / 4
sqrt(b) should be sqrt(d).
Also in the print statement:
print(f'solution 1 is: {round(x_1)}, solution 2 is: {round(x_2)}')
The round function is confusing.
You could change it to:
print(f'solution 1 is: {(x_1)}, solution 2 is: {(x_2)}')
Your x1 and x2 expressions are not correct. It should be:
x_1=(-1*b+sqrt(d))/(2*a)
x_2=(-1*b-sqrt(d))/(2*a)
Given an arbitrary range of 1 to F and a starting point S with an ending point G such that the only directions we could go is L Left steps and R Right Steps (also arbitrary), create a general solution that will return the number of steps it would take to go from S to R if it is possible otherwise return not possible.
You are bound to the range [1, F] which means that you cannot move L or R steps if the next move will be more than F or less than 1
Example:
F = 100
S = 2
G = 1
L = 0
R = 1
Output: not possible
F = 10
S = 1
G = 10
L = 1
R = 2
Output: 6
Explanation: [1 -> 3(R) -> 5(R) -> 7(R) -> 9(R) -> 8(L) -> 10(R)]
I've been given this problem in our class and our current topic is binary search and divide and conquer. Here's my approach but this does not solve one hidden case.
F = int(input())
S = int(input())
G = int(input())
L = int(input())
R = int(input())
count = 0
while S != G:
dist = abs(S - G) # Takes the current distance from S to G
if S > G:
if S-L > 0:
S -= L
count += 1
else:
S += R
count += 1
else:
if S+R <= F:
S += R
count += 1
else:
S -= L
count += 1
if dist == abs(S - G): # If distance doesn't change after trying
print("not possible") # a move, conclude that it is not possible.
break
if S == G: print(count)
Mathematically this problem means that we are looking for
integer solutions (for x and y) of the following equation:
x * R - y * L = G - S
we can start by creating a function to check if there is a solution quickly:
def path(S, G, F, L, R):
x=0
while True:
y = (x * R - G + S) / L
if y>=0 and int(y)==y:
return(x,y)
else:
x+=1
This will work if there are solutions, but not if they are not.
It can be proved mathematically that there is no solution when L devides R but not G-S. Here is the proof:
If
R mod L =0 (L devides R)
(G - S)/L != 0 (L doesn't devide G-S)
then by deviding the whole equation (x * R - y * L = G - S) by L we take:
x * R/L - y = (G - S)/L <=>
y= (x * R/L) - (G - S)/L
Now, we want y mod 1 = 0 (means that y is integer) for x mod 1 =0 (x integers). Using common modulo operations we take:
y mod 1 = [(x * R/L) - (G - S)/L] mod 1 =
[(x * R/L) mod 1 - ((G - S)/L) mod 1] mod 1 =
[(x mod 1 * (R/L) mod 1) mod 1 - ((G - S)/L) mod 1] mod 1 =
[(x mod 1 * 0) mod 1 - ((G - S)/L) mod 1] mod 1 =
[((G - S)/L) mod 1] mod 1
This cannot be 0 if L doesn't devide G-S which eventally means that there are no pair of integers x,y that can satisfy the original condition.
Programatically this means for our code, the following additions:
def path(S, G, F, L, R):
if R%L==0 and (G-S)%L != 0 :
return 'No solutions'
x=0
while True:
y = (x * R - G + S) / L
if y>=0 and int(y)==y:
return(x,y)
else:
x+=1
I don;t know if mathematically we can prove that the above if is the only exception, it can probably be proved with some more modulo operations. Programatically we can add some clock in our code so that if there are no solutions, which means that it will go to infitive loop, we can return False after some time. Here is how we can do this:
How would I stop a while loop after n amount of time?
If the distance didn't change that doesn't mean it's impossible, you could have just jumped over the point and made it to the other side with the same distance, imagine L=2, R=1, S=3, G=2, you start distance 1 from goal, jump left (still distance 1) then jump right and win. What you need to check is whether you have gone in a loop and ended up at a location you have already tried before. You can either keep track of these locations (say in a set) or do some math ahead of time and figure out how many Ls and Rs it takes before you have definitely looped (probably not intended to figure this out).
F=int(input())
S=int(input())
G=int(input())
L=int(input())
R=int(input())
L*=-1
Fl=1-L
Fr=F-R
h0=set()
n=0
while True:
if S<G:
S+= R if S<=Fr else L
elif G<S:
S+= L if Fl<=S else R
else:
print(n)
break
if S in h0:
print('not possible')
break
h0.add(S)
n+=1
I am attempting to create a program to solve a specific system of equations using brute force with python. I solved for one equation and substituted it into the second equation. Variables a through f are given by user input, and I am trying to output values for x and y within a range of -10 to 10 if they exist. Any help is greatly appreciated, Thank You!
My problem is that for each check within the range the output is no solution, whereas I would like it to output no solution only if none of the numbers within the range satisfy the equation. Updated the code to fix the int object not callable error.
To be clear, the code is mostly working and gives the correct answer, but the answer is nested in roughly 100 'no solution' statements
''' Read in first equation, ax + by = c '''
a = int(input())
b = int(input())
c = int(input())
''' Read in second equation, dx + ey = f '''
d = int(input())
e = int(input())
f = int(input())
for x in range(-10, 10, 1):
for y in range(-10, 10, 1):
if a * x + b * y == c and d * x + e * y == f:
print(x, y)
else:
print('No solution')
# a * x + b * y = c
# d * x + e * y = f
To fix the issue of the else statement printing for each iteration of the if statement I created a check and set it to false. I set a condition that set the variable to true if any of the numbers within the range satisfied the condition. Then set an if statement to print 'No solution' if the variable was still false. Thanks to everyone for the help with syntax, but I'm glad I had the opportunity to figure this out on my own.
Here's the updated working code:
''' Read in first equation, ax + by = c '''
a = int(input())
b = int(input())
c = int(input())
''' Read in second equation, dx + ey = f '''
d = int(input())
e = int(input())
f = int(input())
check = False
for x in range(-10, 10, 1):
for y in range(-10, 10, 1):
if a * x + b * y == c and d * x + e * y == f:
check = True
print(x,y)
if check == False:
print('No solution')
# a * x + b * y = c
# d * x + e * y = f
if d * x + b((c - a * x)/b) == f:
Parentheses after a variable is an operator that tries to call the variable as a function. So this line above is trying to call b() as a function. You need to explicitly add the multiply operator instead:
if d * x + b*((c - a * x)/b) == f:
So, there is a lot going on here that can be improved upon.
But with some basic assumptions on best practices I've re-written your code so that it is easy for anyone to understand.
The main things I'd recommend getting use to:
Setting up a "main" in your python code
building functions instead of relying on a procedural design
commenting the goal of your functions, along with something about the input and output
There are plenty of discussion online as to why, but to sum them up it makes it A) more clear what your intentions are and B) provides an easier baseline for troubleshooting your code.
There are still more things that could be discussed about improving the clarity of intention and design but I'll cut myself short at fear of rambling on.
def brute_force_two_equations(first_values, second_values,
max_range=10, min_range=-10):
'''
Brute force way of finding solution in
system of equations
Params:
first_values: a list of three values [a const, a const, and the result]
second_values: a list of three values [a const, a const, and the result]
max_range: the maximum range to test with, default 10
min_range: the minimum range to test with, default -10
'''
for x in range(min_range, max_range + 1):
for y in range(min_range, max_range + 1):
first_result = equation(first_values[0], first_values[1], x, y)
second_result = equation(second_values[0], second_values[1], x, y)
if first_result == first_values[2] and second_result == second_values[2]:
return (x, y)
def equation(const1, const2, x, y):
'''
A simple equation: a * x + b * y = c
Params:
const1: the first constant value, `a` in the above example
const2: the second constant value, `b` in the above example
x: the first variable value
y: the second variable value
'''
return const1 * x + const2 * y
def get_three_integers():
'''
Requests and provides three integers from the user
'''
inputs = []
for i in range(0, 3):
inputs.append(int(input("Please enter a value: ")))
return inputs
if __name__ == "__main__":
print("== First Equation ==")
first_equation_values = get_three_integers()
print("== Second Equation ==")
second_equation_values = get_three_integers()
solution = brute_force_two_equations(first_equation_values,
second_equation_values)
if solution:
print(f"(x, y) {solution}")
else:
print("No Solution found")
You're saying "No solution" without complely looping through all the choices.
Code should be
for x in range(-10, 10, 1):
for y in range(-10, 10, 1):
if a * x + b * y == c and d * x + e * y == f:
print(x, y)
else:
print('No solution')
This is the way I did it and it works:
(I borrowed the check = False idea)
''' Read in first equation, ax + by = c '''
a = int(input())
b = int(input())
c = int(input())
''' Read in second equation, dx + ey = f '''
d = int(input())
e = int(input())
f = int(input())
check = False
for x in range(-10, 11):
for y in range(-10, 11):
if (a * x) + (b * y) != c:
y += 1
continue
if (a * x) + (b * y) == c and (d * x) + (e * y) != f:
y += 1
continue
if (a * x) + (b * y) == c and (d * x) + (e * y) == f:
check = True
print("x = {} , y = {}".format(x,y))
else:
x += 1
continue
if check == False:
print("There is no solution")
I have written a code to find Pythagorean triplets but it is not optimized
it took 5-6 minutes for the algorithm to find answer for big numbers...
my teacher said it should take less than 3 secs...
num = int(input())
def main(n):
for x in range(1, n):
for y in range(1, x):
for z in range(1, y):
if x + y + z == n:
if x * x == y * y + z * z or y * y == x * x + z * z or z * z == x * x + y * y:
a = f'{z} {y} {x}'
print(a)
return
else:
print('Impossible')
for example if you enter 12, you'll get 3,4,5
if you enter 30 , the answer will be 5,12,13
The sum of these three numbers must be equal to the number you entered.
can anyone please help me ?
Note the proof for the parametric representation of primitive pythagorean triples. In the proof, the author states:
We can use this proof to write an optimized algorithm:
def p(num):
a, b, c = 1, 1, 0
n = 0
while c < num:
for m in range(1, n):
a = 2 * m * n
b = n ** 2 - m ** 2
c = n ** 2 + m ** 2
if c >= num:
return "Impossible!"
elif a + b + c == num:
return b, a, c
n = n + 1
print(p(12)) # >>> (3, 4, 5)
print(p(30)) # >>> (5, 12, 13)
print(p(31)) # >>> Impossible!
You're doing a lot of repeated and unnecessary work. You know that A^2 + B^2 = C^2 and you know that C > B > A. It doesn't matter if you want to say C > A > B because any solution you find with that would be satisfied with C > B > A. For instance take 12 and solution 3, 4, 5. It doesn't actually matter if you say that A=3 and B=4 or A=4 and B=3. Knowing this we can adjust the loops of each for loop.
A can go from 1 to num, that's fine. Technically it can go to a bit less since you are adding another value to it that has to be at least 1 as well.
B then can go from A+1 to num since it needs to be greater than it.
So what about C? Well it doesnt' need to go from 1 since that's not possible. In fact we only care about A + B + C = num, so solve for C and you get C = num - A - B. That means you don't need to use a loop to find C since you can just solve for it. Knowing this you can do something like so:
In [142]: def find_triplet(num):
...: for a in range(1, num-1):
...: for b in range(a+1, num):
...: # A^2 + B^2 = C^2
...: # And A+B+C = N
...: c = num - a - b
...: if c > 0:
...: if a*a + b*b == c*c:
...: print(f'{a} {b} {c}')
...: else:
...: break
...:
In [143]: find_triplet(30)
5 12 13
So why check to see if C > 0 and break otherwise? Well, if you know C = num - A - B and you are incrementing B, then once B becomes too large, C is going to continue to get more and more negative. Because of that you can check if C > 0 and if it's not, break out of that inner loop to have A increment and B reset.
The approach you discussed takes O(n^3) complexity.
An efficient solution is to run two loops, where first loop runs from x = 1 to n/3, second loop runs from y = x+1 to n/2. In second loop, we check if (n – x – y) is equal to (x * x + y * y):
def pythagoreanTriplet(n):
# Considering triplets in
# sorted order. The value
# of first element in sorted
# triplet can be at-most n/3.
for x in range(1, int(n / 3) + 1):
# The value of second element
# must be less than equal to n/2
for y in range(x + 1,
int(n / 2) + 1):
z = n - x - y
if (x * x + y * y == z * z):
print(x, " ", y, " ", z)
return
print("Impossible")
# Driver Code
n = int(input())
pythagoreanTriplet(n)
PS: Time complexity = O(n^2)
I am trying to write a function to determine if a number is prime. I have come up with
the following solution, however inelegant, but cannot figure out how to write it.
I want to do the following: take the number x and divide it by every number that is less than itself. If any solution equals zero, print 'Not prime.' If no solution equals zero, print 'Prime.'
In other words, I want the function to do the following:
x % (x - 1) =
x % (x - 2) =
x % (x - 3) =
x % (x - 4) =
etc...
Here is as far as I have been able to get:
def prime_num(x):
p = x - 1
p = p - 1
L = (x % (p))
while p > 0:
return L
Wikipedia provides one possible primality check in Python
def is_prime(n):
if n <= 3:
return n >= 2
if n % 2 == 0 or n % 3 == 0:
return False
for i in range(5, int(n ** 0.5) + 1, 6):
if n % i == 0 or n % (i + 2) == 0:
return False
return True