Question

In: Computer Science

Please fix all of the errors in this Python Code. import math """ A collection of...

Please fix all of the errors in this Python Code.
import math

""" A collection of methods for dealing with triangles specified by the length
    of three sides (a, b, c)

    If the sides cannot form a triangle,then return None for the value

"""

## @TODO - add the errlog method and use wolf fencing to identify the errors in this code



def validate_triangle(sides):
    """
    This method should return True if and only if the sides form a valid triangle
        Given three side lengths, the sum of smallest two should be greater than longest sides

    :param sides: a tuple with side lengths
    :return: True if sides form a triangle, False otherwise
    """

    return True

def get_angle(sides):
    """
    Returns the angle C defined for the triangle defined by side lengths (a, b, c)
    first value in the tuple point
    :param sides: a tuple with 3 side lengths
    :return: the angle (in radians) of the angle opposite side c; return None if invalid
    """
    # Using the law of cosines
    #  c^2 = a^2 + b^2 - 2abcos(C)
    #  cos(C) = (a^2 + b^2 - c^2)/(2ab)

    a = sides[1]
    b = sides[2]
    c = sides[3]

    num = math.pow(a, 2) + math.pow(b,2) + math.pow(c,2)
    den = 2*a*b

    val = num/den

    angle = math.acos(val)

    return angle

def get_height(sides):
    """
    Returns the height of triangle defined by side lengths (a, b, c)

    Given angle C between sides a & b, the height h from side b to vertex of a and c is
    given by sin(C) = h/a so that h = a*sin(C)
       /|\
      / | \
    a/  |  \ c
    / C |h  \
   /____|____\
         b
    :param sides:
    :return: height from b side to a-c vertex; None if invalid sides
    """

    C = get_angle(sides) # angle formed by sides a and b, opposite side c
    height = sides[0]*math.sin(C)
    return height

def get_area(sides):
    """
    Returns the area of triangle defined by side lengths (a, b, c)
    :param sides:
    :return: area
    """

    base   = sides[1]
    height = get_height(sides)
    area = (1/2.)*base*height
    return area

def get_area_heron(sides):
    """
    Returns the area of triangle defined by side lengths (a, b, c)
    using https://www.mathsisfun.com/geometry/herons-formula.html

    This method is intended to be correct to assist you in debugging other methods

    :param sides:
    :return: area
    """
    if (not validate_triangle(sides)):
        return None

    a  = sides[0]
    b  = sides[1]
    c  = sides[2]
    s  = 0.5*(a + b + c)
    area = math.sqrt(s*(s-a)*(s-b)*(s-c))
    return area

print('name is',__name__)
if __name__ == "__main__":
    sides = (3, 4, 5)
    areaHeron = get_area_heron(sides) # This should be 6.0
    area      = get_area(sides)
    print('Area of triangle with sides={} is {} {}'.format(str(sides), str(area), str(areaHeron)))

    sides = (4, 5, 3)
    areaHeron = get_area_heron(sides) # This should be 6.0 (same as 3,4,5)
    area      = get_area(sides)
    print('Area of triangle with sides={} is {} {}'.format(str(sides), str(area), str(areaHeron)))

    sides = (2, 2, 2*math.sqrt(2)) # equilateral right triangle
    areaHeron = get_area_heron(sides) # This should be 2.0
    area      = get_area(sides)
    print('Area of triangle with sides={} is {} {}'.format(str(sides), str(area), str(areaHeron)))

    sides = (4, 4, 5) # This is an invalid triangle
    areaHeron = get_area_heron(sides) #
    area      = get_area(sides)
    print('Area of triangle with sides={} is {} {}'.format(str(sides), str(area), str(areaHeron)))

    sides = (3, 4, 8) # This is an invalid triangle
    areaHeron = get_area_heron(sides) # This should be None
    area      = get_area(sides)
    print('Area of triangle with sides={} is {} {}'.format(str(sides), str(area), str(areaHeron)))

    sides = (3, 4) # This is an invalid triangle
    areaHeron = get_area_heron(sides) # This should be None
    area      = get_area(sides)
    print('Area of triangle with sides={} is {} {}'.format(str(sides), str(area), str(areaHeron)))

Solutions

Expert Solution

There are some errors in the main function also, the following is the code after correcting those errors.

Corrected python code:

import math

""" A collection of methods for dealing with triangles specified by the length
    of three sides (a, b, c)

    If the sides cannot form a triangle,then return None for the value

"""

## @TODO - add the errlog method and use wolf fencing to identify the errors in this code



def validate_triangle(sides):
    """
    This method should return True if and only if the sides form a valid triangle
        Given three side lengths, the sum of smallest two should be greater than longest sides

    :param sides: a tuple with side lengths
    :return: True if sides form a triangle, False otherwise
    """

    sides = list(sides)
    sides.sort()

    if len(sides) != 3 or sides[0] + sides[1] <= sides[2]:
        return False

    return True

def get_angle(sides):
    """
    Returns the angle C defined for the triangle defined by side lengths (a, b, c)
    first value in the tuple point
    :param sides: a tuple with 3 side lengths
    :return: the angle (in radians) of the angle opposite side c; return None if invalid
    """
    # Using the law of cosines
    #  c^2 = a^2 + b^2 - 2abcos(C)
    #  cos(C) = (a^2 + b^2 - c^2)/(2ab)

    a = sides[0]
    b = sides[1]
    c = sides[2]

    if not validate_triangle(sides):
        return None

    num = math.pow(a, 2) + math.pow(b,2) - math.pow(c,2)
    den = 2*a*b

    val = num/den

    angle = math.acos(val)

    return angle

def get_height(sides):
    """
    Returns the height of triangle defined by side lengths (a, b, c)

    Given angle C between sides a & b, the height h from side b to vertex of a and c is
    given by sin(C) = h/a so that h = a*sin(C)
       /|\
      / | \
    a/  |  \ c
    / C |h  \
   /____|____\
         b
    :param sides:
    :return: height from b side to a-c vertex; None if invalid sides
    """

    if not validate_triangle(sides):
        return None
    
    C = get_angle(sides) # angle formed by sides a and b, opposite side c
    height = sides[0]*math.sin(C)
    return height

def get_area(sides):
    """
    Returns the area of triangle defined by side lengths (a, b, c)
    :param sides:
    :return: area
    """

    if not validate_triangle(sides):
        return None

    base   = sides[1]
    height = get_height(sides)
    area = (1/2)*base*height
    return area

def get_area_heron(sides):
    """
    Returns the area of triangle defined by side lengths (a, b, c)
    using https://www.mathsisfun.com/geometry/herons-formula.html

    This method is intended to be correct to assist you in debugging other methods

    :param sides:
    :return: area
    """
    if (not validate_triangle(sides)):
        return None

    a  = sides[0]
    b  = sides[1]
    c  = sides[2]
    s  = 0.5*(a + b + c)
    area = math.sqrt(s*(s-a)*(s-b)*(s-c))
    return area

print('name is',__name__)
if __name__ == "__main__":
    sides = (3, 4, 5)
    areaHeron = get_area_heron(sides) # This should be 6.0
    area      = get_area(sides)
    print('Area of triangle with sides={} is {} {}'.format(str(sides), str(area), str(areaHeron)))

    sides = (4, 5, 3)
    areaHeron = get_area_heron(sides) # This should be 6.0 (same as 3,4,5)
    area      = get_area(sides)
    print('Area of triangle with sides={} is {} {}'.format(str(sides), str(area), str(areaHeron)))

    sides = (2, 2, 2*math.sqrt(2)) # equilateral right triangle
    areaHeron = get_area_heron(sides) # This should be 2.0
    area      = get_area(sides)
    print('Area of triangle with sides={} is {} {}'.format(str(sides), str(area), str(areaHeron)))

    sides = (4, 4, 5) # This is a valid triangle
    areaHeron = get_area_heron(sides) #
    area      = get_area(sides)
    print('Area of triangle with sides={} is {} {}'.format(str(sides), str(area), str(areaHeron)))

    sides = (3, 4, 8) # This is an invalid triangle
    areaHeron = get_area_heron(sides) # This should be None
    area      = get_area(sides)
    print('Area of triangle with sides={} is {} {}'.format(str(sides), str(area), str(areaHeron)))

    sides = (3, 4) # This is an invalid triangle
    areaHeron = get_area_heron(sides) # This should be None
    area      = get_area(sides)
    print('Area of triangle with sides={} is {} {}'.format(str(sides), str(area), str(areaHeron)))


Sample execution of the above code:


Related Solutions

Please fix all the errors in this Python program. import math def solve(a, b, c): """...
Please fix all the errors in this Python program. import math def solve(a, b, c): """ Calculate solution to quadratic equation and return @param coefficients a,b,class @return either 2 roots, 1 root, or None """ #@TODO - Fix this code to handle special cases d = b ** 2 - 4 * a * c disc = math.sqrt(d) root1 = (-b + disc) / (2 * a) root2 = (-b - disc) / (2 * a) return root1, root2 if...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner;...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner; public class Booolean0p {        public class BooleanOp {            public static void main(String[] args) {                int a = 0, b = 0 , c = 0;                Scanner kbd = new Scanner(System.in);                System.out.print("Input the first number: ");                a = kbd.nextInt();                System.out.print("Input...
fix this code in python and show me the output. do not change the code import...
fix this code in python and show me the output. do not change the code import random #variables and constants MAX_ROLLS = 5 MAX_DICE_VAL = 6 #declare a list of roll types ROLLS_TYPES = [ "Junk" , "Pair" , "3 of a kind" , "5 of a kind" ] #set this to the value MAX_ROLLS pdice = [0,0,0,0,0] cdice = [0,0,0,0,0] #set this to the value MAX_DICE_VAL pdice = [0,0,0,0,0,0] cdice = [0,0,0,0,0,0] #INPUT - get the dice rolls i...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public static void main(String[] args) {        System.out.println("This program will ask the user for three sets of two numbers and will calculate the average of each set.");        Scanner input = new Scanner(System.in);        int n1, n2;        System.out.print("Please enter the first number: ");        n1 = input.nextInt();        System.out.print("Please enter the second number: ");        n2 =...
Python 3 Fix the code and rovide the correct indentation Code: import tkinter as tk from...
Python 3 Fix the code and rovide the correct indentation Code: import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook from tkinter import messagebox from datetime import datetime window = tk.Tk() window.title("daily logs") window.grid_columnconfigure(1,weight=1) window.grid_rowconfigure(1,weight=1) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money =...
fix all errors in code below: PLEASE DO ASAP, THIS IS IN MATLAB %Welcome Message fprintf('****Welcome...
fix all errors in code below: PLEASE DO ASAP, THIS IS IN MATLAB %Welcome Message fprintf('****Welcome to Comida Mexicana De Mentiras****\n'); flag =0; while flag ==1 % Asking the user for the order choice = input('Please enter your order \n 1. Burrito Bowl \n 2.Burrito \n 3. Tacos \n Enter 1 or 2 or 3: ','s'); switch choice case choice==1 % For Burrito Bowl BaseCost = 4; [Protein, PC] = proteinChoice(); [FinalAmount,~]= AmountCalculator(BaseCost,PC); displayMessage("Burrito Bowl",Protein,FinalAmount); case choice==2 end end %...
Python 3 Calendar does not showing up Fix code: # required library import tkinter as tk...
Python 3 Calendar does not showing up Fix code: # required library import tkinter as tk from tkcalendar import DateEntry import xlsxwriter # frame window = tk.Tk() window.title("daily logs") #window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=3, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money = tk.Entry(window) # arraging barcode.grid(row=0, column=1) product.grid(row=1, column=1) money.grid(row=2, column=1) cal = DateEntry(window, width=12, year=2019,...
Please convert this code written in Python to Java: import string import random #function to add...
Please convert this code written in Python to Java: import string import random #function to add letters def add_letters(number,phrase):    #variable to store encoded word    encode = ""       #for each letter in phrase    for s in phrase:        #adding each letter to encode        encode = encode + s        for i in range(number):            #adding specified number of random letters adding to encode            encode = encode +...
In Java please Cipher.java: /* * Fix me */ import java.util.Scanner; import java.io.PrintWriter; import java.io.File; import...
In Java please Cipher.java: /* * Fix me */ import java.util.Scanner; import java.io.PrintWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class Cipher { public static final int NUM_LETTERS = 26; public static final int ENCODE = 1; public static final int DECODE = 2; public static void main(String[] args) /* FIX ME */ throws Exception { // letters String alphabet = "abcdefghijklmnopqrstuvwxyz"; // Check args length, if error, print usage message and exit if (args.length != 3) { System.out.println("Usage:\n"); System.out.println("java...
Please fix this python code for me DOWN_PAYMENT_RATE = 0.10 ANNUAL_INTEREST_RATE = 0.12 MONTHLY_PAYMENTS_RATE = 0.05...
Please fix this python code for me DOWN_PAYMENT_RATE = 0.10 ANNUAL_INTEREST_RATE = 0.12 MONTHLY_PAYMENTS_RATE = 0.05 purchasePrice = float(input("Enter the purchase price: ")) month = 1 payment = purchasePrice * MONTHLY_PAYMENTS_RATE startingBalance = purchasePrice print("\n%s%19s%18s%19s%10s%17s" % ("Month", "Starting Balance", "Interest to Pay", "Principal to Pay", "Payment", "Ending Balance")) while startingBalance > 0:     interestToPay = startingBalance * ANNUAL_INTEREST_RATE / 12     principalToPay = payment - interestToPay     endingBalance = startingBalance - payment     print("%2d%16.2f%16.2f%18.2f%18.2f%15.2f" % (month, startingBalance, interestToPay, principalToPay, payment,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT