I am supposed to write a program that prompts the user for the lengths of three sides of a triangle, determines that the three lengths can form a triangle and if so uses Heron's formula to compute the area to 4 digits of precision.This is what I have so far I don't know where or how to put in the math
import math
def main():
print()
print("Triangle Area Program")
print()
a, b, c = eval(input("Enter three lengths separated by commas: "))
print()
s = (a+b+c) / 2.0
area = sqrt(s*(s-a)*(s-b)*(s-c))
if a > b:
a, b = b, a
if a > c:
a, c = c, a
if b > c:
b, c = c, b
else:
a + b > c
print("A triangle cannot be formed.")
main()
Here's another possible version of your mathy problem:
import math
def heron(a, b, c):
return 0.25 * math.sqrt((a + (b + c)) * (c - (a - b)) * (c + (a - b)) * (a + (b - c)))
if __name__ == "__main__":
print()
print("Triangle Area Program")
print()
print()
try:
description = "Enter three lengths separated by commas: "
sides = sorted(map(float, input(description).split(',')))
if (sides[1] + sides[2]) < sides[0]:
print("A triangle cannot be formed.")
else:
a, b, c = sides
print("Area of triangle {0}-{1}-{2} is {3:.4f}".format(
sides[0], sides[1], sides[2], heron(a, b, c)))
except Exception as e:
print("Check your input!!!")
print("--> Error: {0}".format(e))
Few notes about this version:
It's parsing your floating-point input values and sorting at the same time, that way you can check directly whether a triangle can be formed or not
It's not using the naive heron formula, instead is using another one which is numerically stable
I've decided to give you another version because in the comments you'll find some good advices about yours
Here's a slightly modified version of your program that checks if the inputs are compatible in one compound conditional expression and replaces the use of eval:
import math
def main():
print("\nTriangle Area Program\n")
a, b, c = map(float, input("Enter three lengths separated by commas: ").split(','))
if a + b > c and a + c > b and b + c > a:
s = (a + b + c) / 2.0
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
return round(area, 4) # round area to four decimal places
else:
raise ValueError("The inputs you entered cannot form a triangle")
if __name__ == '__main__':
print(main())
More on avoiding eval when you can Why should exec() and eval() be avoided?
Related
I wrote a python code to find root of 2*x-4 using bisection method
def func(x):
return 2*x-4
def bisection(a,b):
if (func(a) * func(b) >= 0):
print("You have not assumed right a and b\n")
return
c = a
while ((b-a) >= 0.01):
c = (a+b)/2
if (func(c) == 0.0):
break
if (func(c)*func(a) < 0):
b = c
else:
a = c
print("The value of root is : ","%.0f"%c)
a =-2
b = 4
bisection(a, b)
Now i want that the function input should be given by the user in the form of mx+n where m and n are integers. Can anyone help how can i do that ?
m, n = list(map(int, input("Please enter the value of [m] [n] for f(x) = mx +n: ").split()))
def Input():
a, b = list(map(int, input("Enter values of [a] [b]: ").split()))
if f(a)*f(b)<0:
Bisection(a, b)
else:
print("Oops! The root of function doesn't belong to the above domain\nPlease try to again:")
Input()
def f(x):
return m*x + n
def Bisection(a, b):
c = (a+b)/2
if f(c)*f(b)<0:
Bisection(c, b)
elif f(c)*f(a)<0:
Bisection(c, a)
elif f(c)==0:
print(c)
Input()
See we know that Bisection, Newton-Raphson, or most of all Numerical methods are the iteration processes so better we use function inside of function: f(f(f(f.....) Of course! by checking the conditions.
Here, I have used elif f(c)==0 this is something which we can't use for quadratic/cubic or higher-order polynomials because getting the exact root will not be possible for all the types of equations say like f(x) = mx^2 - n where m, n > 0 However, we can define the iterations to be performed.
By asking like Please enter the number of iterations to be performed:
I tried making a program to get inputs for the variables in a quadratic equation and print the roots.
import math
def quadratic_solver(a = input("Enter the value of a "), b = input("Enter the value of b "), c = input("Enter the value of c ")):
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
if dis > 0:
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print(-b / (2 * a))
else:
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
Why does the program ask for the input values (as it should) but does not give any output?
When you put input() in the function definition, those will run without you even having to call the function; those are executed regardless, since default values are evaluated when a function is defined, not when it's called. I don't see anywhere where you're calling the function, so I'm assuming you're never actually calling it, thus leading to no print outputs while still getting the input prompts.
To fix the issues, you need to call the function, as well as put the inputs inside of it.
In addition, your a b and c values are being read as strings, but never converted to numbers, which will lead to an error about this if you don't convert them first, so I put in a conversion to float in order to make it work.
import math
def quadratic_solver(a=None, b=None, c=None):
if a is None:
a = float(input("Enter the value of a "))
if b is None:
b = float(input("Enter the value of b "))
if c is None:
c = float(input("Enter the value of c "))
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
if dis > 0:
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print(-b / (2 * a))
else:
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
if __name__ == '__main__':
quadratic_solver()
I came across an exercise, and I cannot figure out how to do it.
The exercise:
Write a function named Triangle1 that takes three integers as input variables, and prints either “Yes” or “No,” depending on whether you can, or cannot, form a triangle from sides with the given lengths. In addition, I need to, "form the triangle using python turtle with the turtle creating angles based on the given sides”.
This is what I've tried so far. However I constantly get errors pertaining to either a part of turtle not being defined in some way:
AttributeError: 'Turtle' object has no attribute 'done'
or having the process finish with an exit code of 0.
I think it might be related to using a specific program, but I can't seem to figure out how to fix this problem.
from math import *
import turtle
def draw_triangle(board, angles, sides):
A, B, C = angles
a, b, c = sides
# draw side a
board.forward(a)
# Change direction and draw side b
board.left(180-C)
board.forward(b)
# Change direction and draw side c
board.left(180-A)
board.forward(c)
board.done()
def main():
board = turtle.Turtle()
a = (int(input("Enter a value for a:")))
b = (int(input("Enter a value for b:")))
c = (int(input("Enter a value for c:")))
if a+b > c and b+c > a and a + c > b:
print("Those ARE valid sides of a triangle")
else:
print("Those ARE NOT valid sides of a triangle")
A = degrees(acos((a**2+b**2-c**2)/(2.0*a*b)))
B = degrees(acos((b**2+c**2-a**2)/(2.0*b*c)))
C = degrees(acos((c**2+a**2-b**2)/(2.0*a*c)))
draw_triangle(board, [A, B, C], [a, b, c])
main()
I expect the output of the code to draw a triangle that changes angles based on the user inputted side lengths.
This revision of the code should fix the OP's stated problems as well as the trigonometry problem (i.e. the triangles should close.) It will also use previously unused angle B to return the turtle cursor to its original heading:
from math import pi, acos
from turtle import Turtle, mainloop
def draw_triangle(board, angles, sides):
A, B, C = angles
a, b, c = sides
# draw side a
board.forward(a)
# Change direction and draw side b
board.left(pi - C)
board.forward(b)
# Change direction and draw side c
board.left(pi - A)
board.forward(c)
# If all's correct, return to starting angle
board.left(pi - B)
def main():
a = int(input("Enter a value for a: "))
b = int(input("Enter a value for b: "))
c = int(input("Enter a value for c: "))
if a + b > c and b + c > a and a + c > b:
print("Those ARE valid sides of a triangle")
else:
print("Those ARE NOT valid sides of a triangle")
A = acos((b**2 + c**2 - a**2) / (2.0 * b * c))
B = acos((c**2 + a**2 - b**2) / (2.0 * c * a))
C = acos((a**2 + b**2 - c**2) / (2.0 * a * b))
board = Turtle()
board.radians()
draw_triangle(board, [A, B, C], [a, b, c])
mainloop()
main()
The board.done() was invalid as board is a turtle an done() is a screen method. The trigonometry problem was that the three angle calculations were assigned incorrectly.
Finally, I switched the turtle to radians so that all the math can be done without the conversions to degrees.
Here is my code:
def lcm(a, b):
if b == 0:
return a
return a * b / lcm(a, b)
print lcm(5,3)
This is what I could manage so far, any idea on how to find the LCM (least common multiple) of two numbers using recursive and one function?
We have lcm(a, b) * gcd(a, b) = a * b. So we can write the following equation:
lcm(a, b) = a; if a % b == 0
lcm(a, b) ; if a % b != 0
= a * b / gcd(a, b)
= a * b / gcd(b, a % b)
= a * b / (b * (a % b) / lcm(b, a % b))
= a / (a % b) * lcm(b, a % b)
And translate to Python, we have:
def lcm(a, b):
t = a % b
if t == 0: return a
return a * lcm(b, t) / t
Edit: I didn't read the recursive / one function bit in your question cause I'm dumb. Incorporated now.
The lcm isn't a * b / lcm(a, b), it's a * b / gcd(a, b) (greatest common divisor).
So the cleanest way to do this is:
def gcd(x, y):
while y:
x, y = y, x % y
return x
def lcm(x, y):
return x * y / gcd(x, y)
If you are limited to recursion only (e.g. for an exam) then this doesn't have to be efficient, so you might as well just recursively count up until you find the lowest number that both x and y divide into:
def lcm(x, y, counter=1):
if (counter%x == 0 and counter%y == 0):
return counter
return lcm(x, y, counter+1)
That just increases counter until counter%x == 0 and counter%y == 0 is true, which is the LCM. Don't try it on large numbers though, you'll just get a stack overflow.
As stated in the other answers here lcm = a*b / gcd(a, b)but then you will need to define another function gcd(a, b) for it.
Since you needed only 1 function with recursion, maybe this piece of code will do.
N.B. : This function has one extra parameter c which should be always passed as 1 while calling it outside the function only :
def lcm(a, b, c):
d = c
m = min(a, b)
while m > 1 :
if a%m == 0 and b%m == 0 :
d*=m
return lcm(int(a/m), int(b/m), d)
else:
m-= 1
d*= a*b
return d
Using the mathematical relationship that the product of two numbers is equal to the product of the Greatest Common Divisor and the Least Common Multiplier of those two numbers: A * B = GCD(A,B) * LCM(A,B)
def gcd(a,b):
if a % b == 0: return b
return gcd(b, a % b)
def lcm(a, b):
return ((a*b) // gcd(a,b))
The first function is recursive and it's used to find the Greatest Common Divisor, it has cost O(log(n)).
This should do:
# Python Program to find the L.C.M. of two input number
# define a function
def lcm(x, y):
"""This function takes two
integers and returns the L.C.M."""
# choose the greater number
if x > y:
greater = x
else:
greater = y
while True:
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
# take input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))
I created my own easy programme.
def lcm(greater,a,b):
# while(True):
if (greater % a == 0 and greater % b == 0):
lcm1 = greater
return lcm1
else:
lcm1=lcm(greater + 1,a,b)
return lcm1
a=int(input(" Enter 1st number :"))
b=int(input(" Enter 2nd number :"))
if(a>b):
greater=a
else:
greater=b
print(lcm(greater,a,b))
I can't seem to get my function to work. When I type in 3 for a, 2 for b, and 3.61 for c. That works. However, when I try those values in a different order (Ex: 3.61 for a, 3 for b and 2 for c) It returns as false. I can't figure out what the problem is. Thanks in advance!
a = input("Enter a ")
b = input("Enter b ")
c = input("Enter c ")
def isright_angled():
if abs((a**2+b**2)-(c**2)) < 0.1 or abs((c**2-a**2)-(b**2)) < 0.1 or abs((c**2-b**2)-(a**2)) < 0.1:
return True
else:
return False
print isright_angled()
The hypotenuse, if the triangle is right-angled, will be the largest of a, b and c. You can use that to avoid duplicating the test 3 times (this is the "don't repeat yourself" principle). A second thing to avoid is that if something: return True else: return False. It's usually better expressed as simply return something. Thirdly, functions can take arguments rather than relying on global variables: this makes things easier to understand and there's then less chance of functions interfering with each other. I find a * a easier to understand than a ** 2 but that's personal taste. Putting all that together:
def is_approximately_right_angled(a, b, c):
a, b, c = sorted([a, b, c])
return abs(a * a + b * b - c * c) < 0.1
a = input('enter a ')
b = input('enter b ')
c = input('enter c ')
print is_approximately_right_angled(a, b, c)
If it's not working, you can speed up your development by adding some checks. If you were writing a big program you can write unit tests, but here just some asserts in the module will avoid you having to type a, b, c in each time to test.
I'd add something like this (before the a = input... line):
assert is_approximately_right_angled(3, 4, 5)
assert is_approximately_right_angled(3, 5, 4)
assert is_approximately_right_angled(3, 2, 3.61)
assert not is_approximately_right_angled(3, 5, 5)
With these lines in place, you can have some confidence in the code before you get to type numbers in. When you find cases where the code doesn't work you can add them as additional checks.
a = int(input("Enter the side length" ))
b = int(input("Enter the side length" ))
c = int(input("Enter the side length" ))
def is_right_triangle(a,b,c):
'''
is_right_triangle(a,b,c) -> bool
returns True if a,b,c is a right triangle with hypotenuse c
'''
a, b, c = sorted([a, b, c])
return a*a + b*b == c*c
print(is_right_triangle(a,b,c))
for more accuracy you can use
return abs(a * a + b * b - c * c) < 0.001