Python Print statements don't work - python

a = input('enter a ')
b = input('enter b ')
c = input('enter c ')
def is_right_angled(a, b, c):
a, b, c = sorted([a, b, c]) #sort inputs smallest to largest
pathag=(a * a + b * b - c * c) #< 0.1 #a ^2 + b ^2 - c ^2 should = 0 approx
if pathag<0.1: # test "pathag" to to see if close
print ("This is a right triangle")
else: # if "pathag" not close, not "right"
print ("This is NOT a right triangle")
return abs(a * a + b * b - c * c) < 0.1

There could be a couple issues specific to the print function not working (I think you might also want to revisit some of the logical assumptions driving your is_right_angled function.)
1) An input function creates a string variable. You will need to explicitly convert this to an int or float variable in order for your function to correctly work with these variables.
a = float(input('enter a '))
2) You are not actually calling the function in the above code. Be sure to call it or the code won't run. Add this to the end of your script:
is_right_angled(a, b, c)

Related

How to get variable values from a txt file with a specified format?

I am writing a program that solves quadratic equations, with the variables assigned from a .txt file, with this specific format:
The text file will contain lines of comma separated text – each line contains three floating point numbers. The first number is the value for A, the second number is the value for B, and the third number is the value for C.
Now I have my code mostly written out I am just unsure how I would assign these variables from a .txt file. Here is my current code:
print("\nWelcome to the Blockhouse Bay College Quadratic Equation Program")
file = input("\nPlease input text file name: ")
file = file + ".txt"
text_file = open(file, "r")
import math
# function for finding roots
def equationroots( a, b, c):
# calculating discriminant using formula
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
# checking condition for discriminant
if dis > 0:
print("There are two distinct roots ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print("There is one real root")
print(-b / (2 * a))
# when discriminant is less than 0
else:
print("Complex Roots")
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
# Driver Program
#<---------------Need these variables assigned to lines from .txt file
a = 1
b = 10
c = -24
# If a is 0, then incorrect equation
if a == 0:
print("Cannot be a quadratic equation if a is zero")
else:
equationroots(a, b, c)
Note: Please note at the start of my code I have asked the user to input the file name, I still need to work on this as I need to create an error message for when the file does not exist. Just ignore this as I can fix that later.
with open('file.txt') as f:
content = f.read()
for line in content.splitlines():
a, b, c = map(float, content.split(','))
Complete program:
print("\nWelcome to the Blockhouse Bay College Quadratic Equation Program")
import math
# function for finding roots
def equationroots( a, b, c):
# calculating discriminant using formula
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
# checking condition for discriminant
if dis > 0:
print("There are two distinct roots ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print("There is one real root")
print(-b / (2 * a))
# when discriminant is less than 0
else:
print("Complex Roots")
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
filename = input("\nPlease input text file name: ")
with open(filename + '.txt') as f:
content = f.read()
for line in content.splitlines():
a, b, c = map(float, content.split(','))
# If a is 0, then incorrect equation
if a == 0:
print("Cannot be a quadratic equation if a is zero")
else:
equationroots(a, b, c)
Try this:
I had to move some of your code around, but I left inline comments to explain what I changed. I also included a check to make sure the path exists.
import math # Python convention is to put imports at the top
import os
print("\nWelcome to the Blockhouse Bay College Quadratic Equation Program")
# function for finding roots
def equationroots( a, b, c):
# calculating discriminant using formula
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
# checking condition for discriminant
if dis > 0:
print("There are two distinct roots ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print("There is one real root")
print(-b / (2 * a))
# when discriminant is less than 0
else:
print("Complex Roots")
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
file = input("\nPlease input text file name: ")
file = file + ".txt"
if os.path.exists(file): # check if file exists
with open(file, "rt") as text_file: # using a with statement is
# preferred over directly
# opening the file
for line in text_file: # iterate through lines of file
# the next line splits the `line` by "," commas,
# removes whitespace and casts each item to float
a,b,c = [float(i.strip()) for i in line.split(',')]
if a == 0:
print("Cannot be a quadratic equation if a is zero")
else:
equationroots(a, b, c)
else:
# print some message
you could read the file like this:
f = open(file_name,"r")
for line in f.readlines():
a,b,c = map(float,line.split(","))
# now call your function
if a == 0:
print("Cannot be a quadratic equation if a is zero")
else:
equationroots(a, b, c)
we started by opening the file then we iterate over the lines using file.readlines() then for every line we splitted the values and converted all of them to a float using map()

Codility NailingPlanks - Using Binary Search on Nail Count Instead of Planks

I have already read through the answers on this question - Codility NailingPlanks.
This is not a duplicate, as I'm trying to solve this problem using a different approach - instead of running a binary search on the planks that a given nail can cover, I'm trying to run it on the total number of nails required to cover all the planks.
This is my code:
def solution(A, B, C):
min_nails = 1
max_nails = len(C)
valid = []
while (min_nails <= max_nails):
mid_nails = (min_nails + max_nails) // 2
if (is_valid_nails_amount(mid_nails,A,B,C)):
max_nails = mid_nails - 1
valid.append(mid_nails)
else:
min_nails = mid_nails + 1
return -1 if len(valid) == 0 else min(valid)
def is_valid_nails_amount(nails,A,B,C):
candidates=C[0:nails]
min_cover = min(candidates)
max_cover = max(candidates)
isValid = True
for (a,b) in zip(A,B):
if not(min_cover in range(a, b + 1) or max_cover in range(a, b + 1) or a in range(min_cover, max_cover + 1) or b in range(min_cover, max_cover + 1)):
isValid = False
break
return isValid
The algorithm begins by checking the first len(C) + 1 / 2 nails in C:
First it calculates the smallest and largest value that the nails in this range can cover (min_cover and max_cover).
Next, it looks through A & B, and checks whether each plank can be nailed by any of the nails in the range (min_cover, max_cover).
If the result is False, we update min_nails to be mid_nails + 1 and repeat. If the result is True, we store the number of nails in the valid array, and attempt to find a smaller amount of nails which would also work, by setting max_nails = mid_nails - 1
This approach scores 100% correctness, however fails on the performance tests because it produces incorrect results - for each of the performance tests, the minimum number of nails obtained is much lower than the expected result. I suspect the error would be in this line: if not(min_cover in range(a, b + 1) or max_cover in range(a, b + 1) or a in range(min_cover, max_cover + 1) or b in range(min_cover, max_cover + 1))
but I can't figure out what it is.
The problem with your if condition can be seen with this sample input:
A = [1,3,5]
B = [2,4,6]
C = [1,5,3]
print(solution(A, B, C))
This will print 2, but the expected output is 3, as all three nails are needed.
Yet, your code will have is_valid_nails_amount(2, A, B, C) return True, despite the fact that the second plank is not nailed by those two nails.
The problem is that neither of these conditions guarantees that a nail hits the plank (a, b):
a in range(min_cover, max_cover + 1)
b in range(min_cover, max_cover + 1)
Your algorithm really needs to check if there is a nail in that min/max range that is available for hitting the plank.

printing equation with variables in python

I am trying to print the equation with the variables
I have already tried to put all symbols in quotes
import random
import random
def ask():
a = raw_input("do you want the equation to be easy, medium, or hard: ")
b = int(raw_input("what is the number that you want to be the answer: "))
if(a == "easy"):
d = random.randint(1, 10)
e = random.randint(2, 5)
round(b)
print C = b - d + e - (e/2) + ((d - e) + e/2)
I wanted it to print out the equation with all the variables and symbols
when i type this in i get a syntax error
You cannot print out strings not in quotes. Put the bits you want to print out exactly as written in quotes, and print variables as is. For example:
print 'C =', b, '-', d, '+', e, '-', (e/2), '+', ((d - e/2)
Play around with that and see how you go. You'll want to think about how to do it differently if e.g. d-e/2 is negative.
Also round(b) will do nothing, it does not operate in-place.
try to put your equation in str() first,then print string
so that it will display equation before result.
then print out results
Here's what I think you want as a full solution. It accepts a single equation string as an input It then fills out that equation with the input variables, prints the resulting equation, and then evaluates it to provide a result:
import random
equation = "b - c + e - (e/2) + ((d- e) + e/2)"
b = 12
c = 24
d = random.randint(1, 10)
e = random.randint(2, 5)
# Expand the vlaues into the equation
equation = equation.replace('b', str(b)).replace('c', str(c)).replace('d', str(d)).replace('e', str(e))
# Print the equation
print "C = " + equation
# Evaluate the equation and print the result
C = eval(equation)
print "C = " + str(C)
Sample result:
C = 12 - 24 + 2 - (2/2) + ((6- 2) + 2/2)
C = -6
This code is just a demonstration of what can be done. You could take these ideas and generalize this to expand a map of variable names and values into an arbitrary expression without hard-coding the variable names. The map and equation could come, for example, from a file.

Showing input prompt in python

I am using IDLE for Python on a Mac OS. I wrote the following in a .py file:
import math
def main():
print "This program finds the real solution to a quadratic"
print
a, b, c = input("Please enter the coefficients (a, b, c): ")
discRoot = math.sqrt(b * b-4 * a * c)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print
print "The solutions are: ", root1, root2
main()
IDLE now permanently displays:
This program finds the real solution to a quadratic
Please enter the coefficients (a, b, c):
When I enter 3 numbers (ex: 1,2,3) IDLE does nothing. When I hit enter IDLE crashes (no crash report).
I quit and restarted but IDLE is now permanemtly displaying the above and won't respond to other files.
There is no real solution to the equation X^2 + 2x + 3 = 0. You will get a ValueError when trying to take the square root of b * b-4 * a * c, which is negative. You should handle this error case somehow. For example, a try/except:
import math
def main():
print "This program finds the real solution to a quadratic"
print
a, b, c = input("Please enter the coefficients (a, b, c): ")
try:
discRoot = math.sqrt(b * b-4 * a * c)
except ValueError:
print "there is no real solution."
return
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print
print "The solutions are: ", root1, root2
main()
Or you can detect that the discriminant is negative ahead of time:
import math
def main():
print "This program finds the real solution to a quadratic"
print
a, b, c = input("Please enter the coefficients (a, b, c): ")
discriminant = b * b-4 * a * c
if discriminant < 0:
print "there is no real solution."
return
discRoot = math.sqrt(discriminant)
root1 = (-b + discRoot) / (2 * a)
root2 = (-b - discRoot) / (2 * a)
print
print "The solutions are: ", root1, root2
main()
Result:
This program finds the real solution to a quadratic
Please enter the coefficients (a, b, c): 1,2,3
there is no real solution.
The math module does not support complex numbers. If you replace import math with import cmath and math.sqrt with cmath.sqrt, your script should work like a charm.
EDIT: I just read "This program finds the real solution to a quadratic". Taking into consideration that you only want real roots, you should check for negative discriminants as the Kevin has pointed out.
The reason I see for your program failing is this:
a, b, c = 1, 2, 3
num = b * b - 4 * a * c
print num
It comes out as -8.
You normally can't have a negative number within a square root.
Like what the person above me says, import cmath should work.
http://mail.python.org/pipermail/tutor/2005-July/039461.html
import cmath
a, b, c = 1, 2, 3
num = cmath.sqrt(b * b - 4 * a * c)
print num
= 2.82842712475j

What's wrong with my Extended Euclidean Algorithm (python)?

My algorithm to find the HCF of two numbers, with displayed justification in the form r = a*aqr + b*bqr, is only partially working, even though I'm pretty sure that I have entered all the correct formulae - basically, it can and will find the HCF, but I am also trying to provide a demonstration of Bezout's Lemma, so I need to display the aforementioned displayed justification. The program:
# twonumbers.py
inp = 0
a = 0
b = 0
mul = 0
s = 1
r = 1
q = 0
res = 0
aqc = 1
bqc = 0
aqd = 0
bqd = 1
aqr = 0
bqr = 0
res = 0
temp = 0
fin_hcf = 0
fin_lcd = 0
seq = []
inp = input('Please enter the first number, "a":\n')
a = inp
inp = input('Please enter the second number, "b":\n')
b = inp
mul = a * b # Will come in handy later!
if a < b:
print 'As you have entered the first number as smaller than the second, the program will swap a and b before proceeding.'
temp = a
a = b
b = temp
else:
print 'As the inputted value a is larger than or equal to b, the program has not swapped the values a and b.'
print 'Thank you. The program will now compute the HCF and simultaneously demonstrate Bezout\'s Lemma.'
print `a`+' = ('+`aqc`+' x '+`a`+') + ('+`bqc`+' x '+`b`+').'
print `b`+' = ('+`aqd`+' x '+`a`+') + ('+`bqd`+' x '+`b`+').'
seq.append(a)
seq.append(b)
c = a
d = b
while r != 0:
if s != 1:
c = seq[s-1]
d = seq[s]
res = divmod(c,d)
q = res[0]
r = res[1]
aqr = aqc - (q * aqd)#These two lines are the main part of the justification
bqr = bqc - (q * aqd)#-/
print `r`+' = ('+`aqr`+' x '+`a`+') + ('+`bqr`+' x '+`b`+').'
aqd = aqr
bqd = bqr
aqc = aqd
bqc = bqd
s = s + 1
seq.append(r)
fin_hcf = seq[-2] # Finally, the HCF.
fin_lcd = mul / fin_hcf
print 'Using Euclid\'s Algorithm, we have now found the HCF of '+`a`+' and '+`b`+': it is '+`fin_hcf`+'.'
print 'We can now also find the LCD (LCM) of '+`a`+' and '+`b`+' using the following method:'
print `a`+' x '+`b`+' = '+`mul`+';'
print `mul`+' / '+`fin_hcf`+' (the HCF) = '+`fin_lcd`+'.'
print 'So, to conclude, the HCF of '+`a`+' and '+`b`+' is '+`fin_hcf`+' and the LCD (LCM) of '+`a`+' and '+`b`+' is '+`fin_lcd`+'.'
I would greatly appreciate it if you could help me to find out what is going wrong with this.
Hmm, your program is rather verbose and hence hard to read. For example, you don't need to initialise lots of those variables in the first few lines. And there is no need to assign to the inp variable and then copy that into a and then b. And you don't use the seq list or the s variable at all.
Anyway that's not the problem. There are two bugs. I think that if you had compared the printed intermediate answers to a hand-worked example you should have found the problems.
The first problem is that you have a typo in the second line here:
aqr = aqc - (q * aqd)#These two lines are the main part of the justification
bqr = bqc - (q * aqd)#-/
in the second line, aqd should be bqd
The second problem is that in this bit of code
aqd = aqr
bqd = bqr
aqc = aqd
bqc = bqd
you make aqd be aqr and then aqc be aqd. So aqc and aqd end up the same. Whereas you actually want the assignments in the other order:
aqc = aqd
bqc = bqd
aqd = aqr
bqd = bqr
Then the code works. But I would prefer to see it written more like this which is I think a lot clearer. I have left out the prints but I'm sure you can add them back:
a = input('Please enter the first number, "a":\n')
b = input('Please enter the second number, "b":\n')
if a < b:
a,b = b,a
r1,r2 = a,b
s1,s2 = 1,0
t1,t2 = 0,1
while r2 > 0:
q,r = divmod(r1,r2)
r1,r2 = r2,r
s1,s2 = s2,s1 - q * s2
t1,t2 = t2,t1 - q * t2
print r1,s1,t1
Finally, it might be worth looking at a recursive version which expresses the structure of the solution even more clearly, I think.
Hope this helps.
Here is a simple version of Bezout's identity; given a and b, it returns x, y, and g = gcd(a, b):
function bezout(a, b)
if b == 0
return 1, 0, a
else
q, r := divide(a, b)
x, y, g := bezout(b, r)
return y, x - q * y, g
The divide function returns both the quotient and remainder.
The python program that does what you want (please note that extended Euclid algorithm gives only one pair of Bezout coefficients) might be:
import sys
def egcd(a, b):
if a == 0:
return (b, 0, 1)
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def main():
if len(sys.argv) != 3:
's program caluclates LCF, LCM and Bezout identity of two integers
usage %s a b''' % (sys.argv[0], sys.argv[0])
sys.exit(1)
a = int(sys.argv[1])
b = int(sys.argv[2])
g, x, y = egcd(a, b)
print 'HCF =', g
print 'LCM =', a*b/g
print 'Bezout identity: %i * (%i) + %i * (%i) = %i' % (a, x, b, y, g)
main()

Categories

Resources