Question

Write code on best Python style and with appropriate indentation. 1. Given that you have function...

Write code on best Python style and with appropriate indentation.

1. Given that you have function f that accepts a kwargs argument and does not have a return. You also have a variable d that has been assigned a dictionary. Write a line of code that passes variable d to function f.

2a) Complete the following code to build the states dictionary. The USPresidents.txt file has a number of lines of data, with each line containing two pieces of data: a two letter state abbreviation and the name of a president born in that state. The dictionary keys should be the state abbreviation and the dictionary values should be a count of how many presidents were born in that state (this is just like one of your lab exercises). Only build the one dictionary – don’t build any lists, etc. State = {} File = open(USPresidents.txt”,”r”) For line in file:

2b) Iterate through the states dictionary to print the key and value for each item in the dictionary.

3a) Write a complete Square class. It should have an __init__ method and a getArea method. The __init__ method should accept side (the length of the side of the squre) as a parameter. 3b) Write a complete Cube class. It should inherit from the Square class and should have an __init__ method and a getVolume mehod. The __init__ method should accept side as a parameter.

3c) Initialize variable S with a square object with a side of 3.

3d) Print the area of square 9.

3e) Initialize variable c with a cube object with a side of 4.

3f) Print the volume of cube C.

4a) Given that you have a Liquid class that can be initialized with any amount of gallons, liters, ounces, etc, write the first line of the method that will allow you to add together two Liquid objects using operator overloading. Again, write ONLY the first line ( method definition) – you do NOT have to write the entire method.

4b) Given that you have L1 and L2 which are instances of the Liquid class, write a line of code that uses operator overloading to add them together and assign the result to L3.

5) Write a function called calcTotal. It should have a required parameter called price and an optional parameter called lowRate with a default value of 0.08. The function should return the price including the calculated tax.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the python program:

Answer 1:

#function uses key worded args
def kwargsFun(**kwargs):
    for key, value in kwargs.items():
        print ("%s == %s" %(key, value))

d={"1": "one", "2": "two", "3": "three" }

kwargsFun(**d)

Output:

3 == three
2 == two
1 == one


Answer 2:


State={}
File=open("USPresidents.txt","r")
for line in File:
   a=line.split(" ")
   if a[0] not in State:
      State[a[0]] = 1
   else:
      State[a[0]]=State[a[0]] + 1

for key,val in State.items():
    print key, "=>", val

Output:

BT => 1
ST => 2

Answer 3a-f:

class square():
    def __init__(self,length):
        self.area=length
    def getArea(self):
        return self.area**2
   
class cube(square):
    def __init__(self, side):
        super().__init__(length = side)
        self.side=side
    def getVolume(self):
        return super().getArea() * self.side
       
       
       
   
   

S=square(3);
print("area of a square is", S.getArea())

V=cube(4);
print("Volume of a cube is", V.getVolume())

Output:

area of a square is 9
Volume of a cube is 64


Answer 4a, 4b:

class liquid:
    def __init__(self, liters, gallons, ounces):
        self.a = liters
        self.b = gallons
        self.c = ounces

     # adding two objects
    def __add__(self, other):
        self.a=self.a + other.a
        self.b=self.b + other.b
        self.c=self.c + other.c
        return self

   
L1 = liquid(4,5,6)
L2 = liquid(7,8,1)

L3 = L1 + L2

print("liters is ", L3.a)
print("gallons is ",L3.b)
print("ounces is ",L3.c)

Output:

liters is 11
gallons is 13
ounces is 7


ANswer 5:

def calcTotal(price, lowRate=0.8):
    return price+lowRate
   
   
print("Opitonal argument not specified", calcTotal(10))

print("Opitonal argument specified ", calcTotal(10, 20))
   

Output:

Opitonal argument not specified 10.8
Opitonal argument specified 30

Screen SHot for all program:

Add a comment
Know the answer?
Add Answer to:
Write code on best Python style and with appropriate indentation. 1. Given that you have function...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Lab 10C - Creating a new class This assignment assumes that you have read and understood...

    Lab 10C - Creating a new class This assignment assumes that you have read and understood the following documents: http://www.annedawson.net/Python3_Intro_OOP.pdf http://www.annedawson.net/Python3_Prog_OOP.pdf and that you're familiar with the following example programs: http://www.annedawson.net/python3programs.html 13-01.py, 13-02.py, 13-03.py, 13-04.py Instructions: Complete as much as you can in the time allowed. Write a Python class named "Car" that has the following data attributes (please create your own variable names for these attributes using the recommended naming conventions): - year (for the car's year of manufacture)...

  • %%%%Python Question%%% Work from the template acrostic.py, which you can find on the ELMS page for...

    %%%%Python Question%%% Work from the template acrostic.py, which you can find on the ELMS page for this assignment. • In the Generator class, write an __init__() method with two parameters: self and the path to a text file containing one word per line. This method should read the words from the file, strip off leading and trailing whitespace, and store them in a dictionary where each key is a lower-case letter and each corresponding value is a list of words...

  • (IN PYTHON) You are to develop a Python program that will read the file Grades-1.txt that...

    (IN PYTHON) You are to develop a Python program that will read the file Grades-1.txt that you have been provided on Canvas. That file has a name and 3 grades on each line. You are to ask the user for the name of the file and how many grades there are per line. In this case, it is 3 but your program should work if the files was changed to have more or fewer grades per line. The name and...

  • 1. Assume you have a Car class that declares two private instance variables, make and model....

    1. Assume you have a Car class that declares two private instance variables, make and model. Write Java code that implements a two-parameter constructor that instantiates a Car object and initializes both of its instance variables. 2. Logically, the make and model attributes of each Car object should not change in the life of that object. a. Write Java code that declares constant make and model attributes that cannot be changed after they are initialized by a constructor. Configure your...

  • Write a function named "loadStateDict(filename) that takes a filename and returns a dictionary of 2-character state...

    Write a function named "loadStateDict(filename) that takes a filename and returns a dictionary of 2-character state codes and state names. The file has four columns and they are separated by commas. The first column is the state full name and the second column is the state code. You don't have to worry about column 3 & 4. You should eliminate any row that is without a state code. Save the two columns into a dictionary with key = state code...

  • In this problem, you should write one function named copy and increment. This function will have...

    In this problem, you should write one function named copy and increment. This function will have one parameter, which you can assume will be a list of integers. This function should return a copy of the parameter list, in which each number from the parameter list has been increased by 1. The function should not modify the values in the parameter list. For example, the code: values - 20, 40, 10, 60, 77, 2) other copy and incrementales) print values...

  • PYTHON (A voting machine consists of an election district, together with the names of the candidates...

    PYTHON (A voting machine consists of an election district, together with the names of the candidates and the number of votes cast for each candidate. Define a VotingMachine class, wrote a docstring for the class, and define the following three class methods: 1. An initialization method. The initialization method should: * take a string parameter, electionDistrict, and assign it to the instance attribute elctionDistrict of the voting machine being created. * create an instance attribute named candidates for the voting...

  • Python vUniess you need to edit, it's safer to stay in Enable Editing Propiem 1 Write...

    Python vUniess you need to edit, it's safer to stay in Enable Editing Propiem 1 Write a class definition line and a one line docstring for the class Dog. Write an_ nit_ method for the class Dog that gives each dog its own name and breed. Test this on a successful creation of a Dog object import dop sugar dog.Dog( Sugar, border collie) >>>sugar.name Sugar >sugar.breed Problem 2 Add a data attribute tricks of type list to each Dog instance...

  • Create a new program in Mu and save it as ps4.4.1.py and take the code below...

    Create a new program in Mu and save it as ps4.4.1.py and take the code below and fix it as indicated in the comments: # Write a function called "save_leaderboard" that accepts a # single list of tuples as a parameter. The tuples are of the # form (leader_name, score) # The function should open a file called "leaderboard.txt", # and write each of the tuples in the list to a line in the file. # The name and score...

  • Write a program that does the following in Python Code: Write a new Class called Famous_Day_Born...

    Write a program that does the following in Python Code: Write a new Class called Famous_Day_Born which is a subclass of Famous_Person. Add a method to calculate the day of the week the person was born and print out all of the corresponding information using the overridden print method. Use the following code below as a starting point. ////////////////////////////////////////////////////// from datetime import datetime class Famous_Person(object): def __init__(self, last, first, month,day, year): self.last = last self.first = first self.month = month...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT