'Turtle' object has no attribute 'done' as well as code freezes - python

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.

Related

Function using input() for default parameters -- inputs collected but no output printed

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()

How to resize an aspect ratio of an image to be in a limit

I have a homework of basic Python, and can't do anything with it. I need to write a program where you give two numbers (a,b) which are 2 sides of an imaghe, then it computes and changes both sides' size to be in the given limit (2 Mp, 2*1024*1024), keeping the aspect ratio. This is what I've done so far:
a = int(input("a= "))
b = int(input("b= "))
hanyados = float(a/b)
if a * b <= 2*1024*1024:
print ("we dont have to change anything")
else:
while a * b > 2 * 1024 * 1024:
--algorithm of resizing here--
print (a)
print (b)
Thank you for your help!
since a/b is hanyados, a = b * hanyados, and a * b = b * b * hanyados = 2Mp.
so b * b = 2Mp / hanyados, or b = sqrt(2Mp/ hanyados). And then determine a from above (a = b * hanyados). That's the logic, you can write the code.

Quadratic Equation Solver Math Domain Error

I am trying to make a quadratic equation solver, but each time I run it, it displays a math domain error. Can anyone help me fix it? I am sorta new to Python.
import math
def quadratic(a, b, c):
return [((-b + i * math.sqrt(b**2 - 4*a*c)) / (2 * a)) for i in (-1,1)]
a = int(input("What is the value of a? "))
b = int(input("What is the value of b? "))
c = int(input("What is the value of c? "))
print(quadratic(a, b, c))
Your code works in general, but should check if b**4-a*c is positive. That is (probably) why you are getting an error
def quadratic(a, b, c):
D = b**2 - 4*a*c
if D >= 0:
return [((-b + i * math.sqrt(D)) / (2 * a)) for i in (-1, 1)]
else:
return None

Finding the Area of a Triangle using if else statements

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?

True/False right angle function in python

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

Categories