Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
180 views

Python Programming: Guru Nanak Dev Engg College

The document contains the contents page of a Python practical file submitted by a student. It lists 21 problems/exercises for the student to complete related to Python programming concepts like momentum, rent calculation, triangle properties, file processing etc. The student has to write Python code and test cases for each problem.

Uploaded by

Umang Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
180 views

Python Programming: Guru Nanak Dev Engg College

The document contains the contents page of a Python practical file submitted by a student. It lists 21 problems/exercises for the student to complete related to Python programming concepts like momentum, rent calculation, triangle properties, file processing etc. The student has to write Python code and test cases for each problem.

Uploaded by

Umang Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Guru Nanak Dev Engg College

Practical File

Python Programming
LPCIT-105

Submitted by: - Submitted to: -


Himanshu Mahajan Prof. Rupinder Kaur
C.R.N – 2021150
U.R.N - 2104587
D2-IT-B2
Contents

1. An object’s momentum is its mass multiplied by its


velocity. Write a program that accepts an object’s
mass (in kilograms) and velocity (in meters per second)
as inputs and then outputs its momentum..............................6
2. Five Star Retro Video rents VHS tapes and DVDs.
to the same connoisseurs who like to buy LP record
albums. The store rents new videos for $3.00 a night,
and oldies for $2.00 a night. Write a program that the
clerks at Five Star Retro Video can use to calculate the
total charge for a customer’s video rentals. The
program should prompt the user for the number of
each type of video and output the total Cost...........................7
3. (a). Write a program that calculates and displays
the value of a light-year.
(b). Write a program that takes as input a number
of kilometers and prints the corresponding number
of nautical miles.....................................................................8-9
4. Write a program that accepts the lengths of three sides of a
triangle as inputs. The program output should indicate
whether or not the triangle is an equilateral triangle.....10-11
5. Write a program that accepts the lengths of three sides of a
triangle as inputs. The program output should indicate
whether or not the triangle is a right triangle. Recall from
the Pythagorean theorem that in a right triangle, the square
of one side equals the sum of the squares of the other two
sides.....................................................................................12-13
6. The greatest common divisor of two positive integers, A and
B, is the largest number that can be evenly divided into both
of them. Euclid’s algorithm can be used to find the greatest
common divisor (GCD) of two positive integers...................14
7. Write a script named dif.py. This script should prompt the
user for the names of two text files and compare the contents
of the two files to see if they are the same. If they are, the
script should simply output "Yes". If they are not, the script
should output "No", followed by the first lines of each file
that differ from each other. The input loop should read and
compare lines from each file. The loop should break as soon
as a pair of different lines is found…………………..…15-16
8. Write a script named copyfile.py. This script should prompt
the user for the names of two text files. The contents of the
first file should be input and written to the second
file……………………………………………………...…17-18
9. A bit shift is a procedure whereby the bits in a bit string are
moved to the left or to the right. For example, we can shift
the bits in the string 1011 two places to the left to produce
the string 1110. Note that the leftmost two bits are wrapped
around to the right side of the string in this operation.
Define two scripts, shiftLeft.py and shiftRight.py, that
expect a bit string as an input. The script shiftLeft shifts the
bits in its input one place to the left, wrapping the leftmost
bitto the rightmost position. The script shiftRight performs
the inverse operation. Each script prints the resulting
string……………………………………………………….…19
10. Write a program that inputs a text file. The program
should print the unique words in the file in alphabetical
order...................................................................................20-21
11. A file concordance tracks the unique words in a file
and their frequencies. Write a program that displays a
concordance for a file. The program should output the
unique words and their frequencies in alphabetical order.
Variations are to track sequences of two words and their
frequencies, or n words and their frequencies................22-23
12. Write a program that allows the user to navigate the
lines of text in a file. The program should prompt the user
for a filename and input the lines of text into a list. The
program then enters a loop in which it prints the number of
lines in the file and prompts the user for a line number.
Actual line numbers range from 1 to the number of lines in
the file. If the input is 0, the program quits. Otherwise, the
program prints the line associated with that
number...............................................................................24-25
13. A list is sorted in ascending order if it is empty or each
item except the last one is less than or equal to its successor.
Define a predicate isSorted that expects a list as an
argument and returns True if the list is sorted, or returns
False otherwise...................................................................26-27
14. Define and test a function myRange. This function
should behave like Python’s standard range function, with
the required and optional arguments, but it should return a
list. Do not use the range function in your
implementation!.................................................................28-29
15. Write a program that computes and prints the average
of the numbers in a text file. You should make use of two
higher-order functions to simplify the design.................30-31
16. Write GUI-based program that implements the tax
calculator program............................................................32-33
17. Write a GUI-based program that allows the user to
convert temperature values between degrees Fahrenheit and
degrees Celsius. The interface should have labeled entry
fields for these two values. These components should be
arranged in a grid where the labels occupy the first row and
the corresponding fields occupy the second row. At start-up,
the Fahrenheit field should contain 32.0, and the Celsius
field should contain 0.0. The third row in the window
contains two command buttons, labeled >>>> and <<<
When the user presses the first button, the program should
use the data in the Fahrenheit field to compute the Celsius
value, which should then be output to the Celsius field. The
second button should perform the inverse function.......34-36
18. Write a GUI-based program that implements an image
browser for your computer’s file system. The look, feel, and
program logic should be like those of the simple text file
bowser developed in this chapter. The file dialog should
filter for GIF image files, and create and open a PhotoImage
when a file is accessed.......................................................37-40
19. Add three methods to the Student class that compare
two Student objects. One method should test for equality. A
second method should test for less than. The third method
should test for greater than or equal to. In each case, the
method returns the result of the comparison of the two
students’ names. Include a main function that tests all of the
comparison operators…………………………………...41-44
20. This project assumes that you have completed Project
1. Place several Student objects into a list and shuffle it.
Then run the sort method with this list and display all of the
students’ information……………………………………45-48
21. Geometric shapes can be modeled as classes. Develop
classes for line segments, circles, and rectangles. Each shape
object should contain a Turtle object and a color that allow
the shape to be drawn in a Turtle graphics window . Factor
the code for these features (instance variables and methods)
into an abstract Shape class. The Circle, Rectangle, and Line
classes are all subclasses of Shape. These subclasses include
other information about the specific types of shapes, such as
a radius or a corner point and a draw method. Write a
script that uses several instances of the different shape
classes to draw a house and a stick figure……………...49-53
1 An object’s momentum is its mass multiplied by its velocity.
Write a program that accepts an object’s mass (in kilograms)
and velocity (in meters per second) as inputs and then outputs
its momentum.

Code: -
#getting the value of the mass in float
mass = float(input("mass(kg) : "))
#getting the value of the velocity in float
velocity = float(input("velocity(m/s) : "))
#implementing the values of the mass and velocity in the formula
momentum = mass*velocity
#Display the momentum
print("the object's momentum in (kg.m/s) is : ",momentum)

Output: -
2 Five Star Retro Video rents VHS tapes and DVDs to the same
connoisseurs who like to buy LP record albums. The store
rents new videos for $3.00 a night, and oldies for $2.00 a
night. Write a program that the clerks at Five Star Retro
Video can use to calculate the total charge for a customer’s
video rentals. The program should prompt the user for the
number of each type of video and output the total Cost.

Code: -
# Request the input
videos=int(input("enter no. of new : "))
oldies=int(input("enter no. of oldie : "))
# Calculate the result
result=(videos*3)+(oldies*2)
# Display the total cost
print("the total cost is","$",result)

Output: -
3 (A). Write a program that calculates and displays the value of
a light-year.
(B). Write a program that takes as input a number of
kilometers and prints the corresponding number of nautical
miles. Use the following approximations:
• A kilometer represents 1/10,000 of the distance between the North Pole and
the equator.
• There are 90 degrees, containing 60 minutes of arc each, between the North
Pole and the equator.
• A nautical mile is 1 minute of an arc.

(A)
Code: -

# Solving (a) part


# Define
year=365
hours=24*year
minutes=hours*60
seconds=minutes*60
# Calculate speed of light
speedoflight=3*10^8
lightyear=speedoflight*seconds
# Display the speed of light
print("light travels",lightyear,"meters in a year")

Output: -
(B)
Code: -

# Solving (b) part


# Request the input
kilometers = int(input("enter amount of kilometers :"))
# Calculate the values
degreesPerMin = 90*60
oneKilo = degreesPerMin/10000
nauticalmile = oneKilo*kilometers
# Display the results
print(kilometers,"is",nauticalmile,"Nautical miles")

Output: -
4 Write a program that accepts the lengths of three sides of a
triangle as inputs. The program output should indicate
whether or not the triangle is an equilateral triangle.

Code: -

# get the length of the first side


A = int(input("enter the length of A : "))
# get the length of the second side
B = int(input("enter the length of B : "))
# get the length of the third side
C = int(input("enter the length of C : "))
# if the length of all the sides are equal then
if A == B == C:
print("TRIANGLE IS EQUILATERAL")
# otherwise the triangle is not an equilateral
else:
print("TRIANGLE IS NOT EQUILATERAL")

Output: -
5 Write a program that accepts the lengths of three sides of a
triangle as inputs. The program output should indicate
whether or not the triangle is a right triangle. Recall from the
Pythagorean theorem that in a right triangle, the square of
one side equals the sum of the squares of the other two sides.

Code: -

# get the length of the first side


A = int(input("enter the length of A : "))
# get the length of the second side
B = int(input("enter the length of B : "))
# get the length of the third side
C = int(input("enter the length of C : "))
# if the square of the hypotenuse side is equal to the sum of squares of the other
2 sides then

if C^2 == ((A^2)+(B^2)):
print("IT IS A RIGHT TRIANGLE")
# otherwise it is not a right triangle
else:
print("IT IS NOT A RIGHT TRIANGLE")

Output: -
6 The greatest common divisor of two positive integers, A and
B, is the largest number that can be evenly divided into both
of them. Euclid’s algorithm can be used to find the greatest
common divisor (GCD) of two positive integers. You can use
this algorithm in the following manner:
(a). Compute the remainder of dividing the larger number by the smaller
number.
(b). Replace the larger number with the smaller number and the smaller
number with the remainder.
(c). Repeat this process until the smaller number is zero. The larger number
at this point is the GCD of A and B.
Write a program that lets the user enter two integers and then prints each
step in the process of using the Euclidean algorithm to find their GCD.

Code: -

# Request input
small = int(input("Enter the smaller number: "))
large = int(input("Enter the larger number: "))
# Calculate
for i in range(1, small+1):
if (small % i == 0) and (large % i == 0):
gcd = i
print("\nThe greatest common divisor is {}" .format(gcd))

Output: -
7 Write a script named dif.py. This script should prompt the
user for the names of two text files and compare the contents
of the two files to see if they are the same. If they are, the
script should simply output "Yes". If they are not, the script
should output "No", followed by the first lines of each file
that differ from each other. The input loop should read and
compare lines from each file. The loop should break as soon
as a pair of different lines is found.

Code: -

# Take the inputs


fileName1 = input("Enter the first file name: ")
fileName2 = input("Enter the second file name: ")
# Open the input files
inputFile1 = open(fileName1, 'r')
inputFile2 = open(fileName2, 'r')
# Read each pair of lines and compare them
while True:
line1 = inputFile1.readline()
line2 = inputFile2.readline()
if line1 == "" and line2 == "": # Ends of both files
print("Yes")
break
elif line1 != line2:
print("No")
print(line1)
print(line2)
break
Output: -
8 Write a script named copyfile.py. This script should prompt
the user for the names of two text files. The contents of the
first file should be input and written to the second file.

Code: -

file1=input("Enter First Filename : ")


file2=input("Enter Second Filename : ")
# open file in read mode
fn1 = open(file1, 'r')
# open other file in write mode
fn2 = open(file2, 'w')
# read the content of the file line by line
cont = fn1.readlines()
#type(cont)
for i in range(0, len(cont)):
fn2.write(cont[i])
# close the file
fn2.close()
print("Content of first file copied to second file ")
# open file in read mode
fn2 = open(file2, 'r')
# read the content of the file
cont1 = fn2.read()
# print the content of the file
print("Content of Second file :")
print(cont1)
# close all files
fn1.close()
fn2.close()

Output: -
9 A bit shift is a procedure whereby the bits in a bit string are
moved to the left or to the right. For example, we can shift the
bits in the string 1011 two places to the left to produce the
string 1110. Note that the leftmost two bits are wrapped
around to the right side of the string in this operation. Define
two scripts, shiftLeft.py and shiftRight.py, that expect a bit
string as an input. The script shiftLeft shifts the bits in its
input one place to the left, wrapping the leftmost bitto the
rightmost position. The script shiftRight performs the inverse
operation. Each script prints the resulting string.
Code: -
Shift right
bits = input("Enter a string of bits: ")
if len(bits) > 1:
bits = bits[-1] + bits[:-1]
print(bits)

Output: -

Shift left
bits = input("Enter a string of bits: ")
if len(bits) > 1:
bits = bits[1:] + bits[0]
print(bits)

Output: -
10 Write a program that inputs a text file. The program should
print the unique words in the file in alphabetical order.

Code: -

fname = input("Enter file name: ")


fh = open(fname)
lst = list()
# list for the desired output
words=[]

for line in fh:


# to read every line of file.txt
words += line.split()
words.sort()
# display the sorted words
print("The unique words in alphabetical order are:")
for word in words:
if word in lst:
# if element is repeated
continue
# do nothing
else:
# else if element is not in the list
lst.append(word)
print(word)
#print(lst)
Output: -
11 A file concordance tracks the unique words in a file and their
frequencies. Write a program that displays a concordance for
a file. The program should output the unique words and their
frequencies in alphabetical order. Variations are to track
sequences of two words and their frequencies, or n words and
their frequencies.

Code: -

#read the file from the user


file_name=input("Enter the file name which is in the computer : ")
#open the read file with read mode
file = open(file_name,"r")
#initialise the empty dictionary
words_freq={}
#read file and split the words
#and iterate over each word in the file
#if new word is recognised it will be added to word_freq dictionary
#else increment the word count
for w in file.read().split():
if w not in words_freq:
words_freq[w] = 1
else:
words_freq[w] += 1
#closing the input file
file.close();
#sort the list and print the word the its frequency
for k in sorted(words_freq):
print(k,":",words_freq[k])
Output: -
12 Write a program that allows the user to navigate the lines of
text in a file. The program should prompt the user for a
filename and input the lines of text into a list. The program
then enters a loop in which it prints the number of lines in the
file and prompts the user for a line number. Actual line
numbers range from 1 to the number of lines in the file. If the
input is 0, the program quits. Otherwise, the program prints
the line associated with that number.

Code: -

# Take the input file name


inName = input("Enter the input file name: ")
# Open the input file and read the text
inputFile = open(inName, 'r')
lines = []
for line in inputFile:
lines.append(line)
# Loop for line numbers from the user until she enters 0
# and prints the line's number followed by the line
while True:
print("The file has", len(lines), "lines.")
if len(lines) == 0:
break
lineNumber = int(input("Enter a line number [0 to quit]: "))
if lineNumber == 0:
break
elif lineNumber >= len(lines):
print("ERROR: line number must be less than", len(lines))
else:
print(lineNumber, ": ", lines[lineNumber])

Output: -
13 A list is sorted in ascending order if it is empty or each item
except the last one is less than or equal to its successor. Define
a predicate isSorted that expects a list as an argument and
returns True if the list is sorted, or returns False otherwise.

Code: -

def isSorted(lyst):
"""Returns True if lyst is sorted in ascending
order or False otherwise."""
if len(lyst) == 0 or len(lyst) == 1:
return True
else:
for index in range(len(lyst) - 1):
if lyst[index] > lyst[index + 1]:
return False
return True
def main():
lyst = []
print(isSorted(lyst))
lyst = [1]
print(isSorted(lyst))
lyst = list(range(10))
print(isSorted(lyst))
lyst[9] = 3
print(isSorted(lyst))

main()
Output: -
14 Define and test a function myRange. This function should
behave like Python’s standard range function, with the
required and optional arguments, but it should return a list.
Do not use the range function in your implementation!

Code: -
def myRange(start, stop = None, step = None):
lyst = []
if stop == None and step == None:
stop = start
start = 0
step = 1
if start < stop:
if step == None:
step = 1
elif step <= 0:
return lyst
while start < stop:
lyst.append(start)
start += step
else:
if step == None or step > -1:
return lyst
while start > stop:
lyst.append(start)
start += step
return lyst
def main():
print(myRange(10))
print(myRange(1, 10))
print(myRange(1, 10, 2))
print(myRange(10, 1, -1))

main()

Output: -
15 Write a program that computes and prints the average of the
numbers in a text file. You should make use of two higher-
order functions to simplify the design.

Code: -

from functools import reduce


def numbersInFile(file_name):
numbers=[]
with open(file_name, 'r') as file:
num_list=file.read().splitlines()
for i in num_list:
numbers+=i.split(' ')
return numbers

def summation(x,y): return x+y


def main():
file_name=input('Enter the input file name: ')
numbers=list(map(int,numbersInFile(file_name)))
num_length=len(numbers)
total=reduce(summation,numbers)
average=total/num_length
print(f'The average is {average}')

if __name__=='__main__':
main()
Output: -
16 Write GUI-based program that implements the tax calculator
program

Code: -
from breezypythongui import EasyFrame
class TaxCodeDemo(EasyFrame):
"""Application window for the tax calculator."""
def __init__(self):
"""Sets up the window and the widgets."""
EasyFrame.__init__(self, title = "Tax Calculator")
# Label and field for the income
self.addLabel(text = "Income",
row = 0, column = 0)
self.incomeField = self.addFloatField(value = 0.0,
row = 0,
column = 1)
# Label and field for the number of dependents
self.addLabel(text = "Dependents",
row = 1, column = 0)
self.depField = self.addIntegerField(value = 0,
row = 1,
column = 1)
# The command button
self.addButton(text = "Compute", row = 3, column = 0,
columnspan = 2, command = self.computeTax)
# Label and field for the tax
self.addLabel(text = "Total tax",
row = 4, column = 0)
self.taxField = self.addFloatField(value = 0.0,
row = 4,
column = 1,
precision = 2)
# The event handler method for the button
def computeTax(self):
"""Obtains the data from the input fields and uses
them to compute the tax, which is sent to the
output field."""
income = self.incomeField.getNumber()
numDependents = self.depField.getNumber()
tax = (income - numDependents) * .15
self.taxField.setNumber(tax)
#Instantiate and pop up the window.
TaxCodeDemo().mainloop()

Output: -
17 Write a GUI-based program that allows the user to convert
temperature values between degrees Fahrenheit and degrees
Celsius. The interface should have labeled entry fields for
these two values. These components should be arranged in a
grid where the labels occupy the first row and the
corresponding fields occupy the second row. At start-up, the
Fahrenheit field should contain 32.0, and the Celsius field
should contain 0.0. The third row in the window contains two
command buttons, labeled >>>> and <<< When the user
presses the first button, the program should use the data in
the Fahrenheit field to compute the Celsius value, which
should then be output to the Celsius field. The second button
should perform the inverse function
Code: -
from tkinter import *
class ConvertGUI(Frame):
def __init__(self):
"""Set up the window and widgets."""
Frame.__init__(self)
self.master.title("Temperature Converter")
self.grid()
self._fahrVar = DoubleVar()
self._celsiusVar = DoubleVar()
self._fahrVar.set(32.0)
self._celsiusVar.set(0.0)
self._fahrLabel = Label(self, text = "Fahrenheit")
self._fahrLabel.grid(row = 0, column = 0)
self._fahrEntry = Entry(self, textvariable = self._fahrVar)
self._fahrEntry.grid(row = 1, column = 0)
self._celsiusLabel = Label(self, text = "Celsius")
self._celsiusLabel.grid(row = 0, column = 1)
self._celsiusEntry = Entry(self, textvariable = self._celsiusVar)
self._celsiusEntry.grid(row = 1, column = 1)
self._toCelsiusButton = Button(self, text = ">>>>",
command = self._toCelsius)
self._toCelsiusButton.grid(row = 2, column = 0)
self._toFahrButton = Button(self, text = "<<<<",
command = self._toFahr)
self._toFahrButton.grid(row = 2, column = 1)
def _toCelsius(self):
"""Event handler for the toCelsius button."""
fahr = self._fahrVar.get()
celsius = (fahr - 32) * 5 / 9
self._celsiusVar.set(celsius)
def _toFahr(self):
"""Event handler for the toFahr button."""
celsius = self._celsiusVar.get()
fahr = celsius * 9 / 5 + 32
self._fahrVar.set(fahr)
def main():
ConvertGUI().mainloop()
main()
Output: -
18 Write a GUI-based program that implements an image
browser for your computer’s file system. The look, feel, and
program logic should be like those of the simple text file
bowser developed in this chapter. The file dialog should filter
for GIF image files, and create and open a PhotoImage when
a file is accessed.

Code: -
from tkinter import *
import os
import os.path
class ImageBrowser(Frame):
def __init__(self):
"""Sets up the window and the widgets."""
Frame.__init__(self)
self.master.title("Image Browser")
self.master.rowconfigure(0, weight = 1)
self.master.columnconfigure(0, weight = 1)
self.grid(sticky = W+E+N+S)
# Set up the pane and add the list box and its
# scroll bar
self._listPane = Frame(self)
self._listPane.grid(row = 0, column = 0,
sticky = N+S)
self._yScroll = Scrollbar(self._listPane,
orient = VERTICAL)
self._yScroll.grid(row = 0, column = 1,
sticky = N+S)
self._listBox = Listbox(self._listPane,
width = 20,
height = 10,
selectmode = SINGLE,
yscrollcommand = \
self._yScroll.set)
self._listBox.grid(row = 0, column = 0,
sticky = N+S)
self._yScroll["command"] = self._listBox.yview
# Set up the input field, image label, and button
self._pathVar = StringVar()
self._input = Entry(self,
textvariable = self._pathVar,
width = 70)
self._input.grid(row = 0, column = 1,
sticky = N)
self._imageLabel = Label(self, text = "")
self._imageLabel.grid(row = 1, column = 1)
self._goButton = Button(self,
text = "Go",
command = self._go)
self._goButton.grid(row = 1, column = 0)
# Configure the list pane to expand
self.rowconfigure(0, weight = 1)
self._listPane.rowconfigure(0, weight = 1)
self._getPathAndFiles()
def _getPathAndFiles(self):
"""Sets the field and the list box with the path of the cwd
and the directories and the .gif files in that directory,
respectively."""
self._path = os.getcwd()
self._pathVar.set(self._path)
fileList = filter(lambda f: ".gif" in f or os.path.isdir(f),
os.listdir(self._path))
index = self._listBox.size() - 1
while self._listBox.size() > 0:
self._listBox.delete(index)
index -= 1
self._listBox.insert(END, "..")
for f in fileList:
self._listBox.insert(END, f)
self._listBox.activate(0)
def _go(self):
"""Moves to a directory or shows an image."""
(index) = self._listBox.curselection()
item = self._listBox.get(index)
if os.path.isfile(item):
# It's a file, so load the image
self._image = PhotoImage(file = item)
self._imageLabel["image"] = self._image
else:
# It's a directory, so move to it and refresh the view
os.chdir(item)
self._getPathAndFiles()
self._imageLabel["image"] = None
self._image = None
def main():
"""Instantiate and pop up the window."""
ImageBrowser().mainloop()
main()

Output: -
19 Add three methods to the Student class that compare two
Student objects. One method should test for equality. A
second method should test for less than. The third method
should test for greater than or equal to. In each case, the
method returns the result of the comparison of the two
students’ names. Include a main function that tests all of the
comparison operators.

Code: -
"""Resources to manage a student's name and test scores.
Includes methods for comparisons and testing for equality."""
from functools import reduce
class Student(object):
"""Represents a student."""
def __init__(self, name, number):
"""All scores are initially 0."""
self._name = name
self._scores = []
for count in range(number):
self._scores.append(0)
def getName(self):
"""Returns the student's name."""
return self._name
def setScore(self, i, score):
"""Resets the ith score, counting from 1."""
self._scores[i - 1] = score
def getScore(self, i):
"""Returns the ith score, counting from 1."""
return self._scores[i - 1]
def getAverage(self):
"""Returns the average score."""
sum = reduce(lambda x, y: x + y, self._scores)
return sum / len(self._scores)
def getHighScore(self):
"""Returns the highest score."""
return reduce(lambda x, y: max(x, y), self._scores)
def __str__(self):
"""Returns the string representation of the student."""
return "Name: " + self._name + "\nScores: " + \
" ".join(map(str, self._scores)
def __lt__(self, other):
"""Returns self < other, with respect
to names."""
return self._name < other._name
def __gt__(self, other):
"""Returns self > other, with respect
to names."""
return not (self == other or self < other)
def __le__(self, other):
"""Returns self <= other, with respect
to names."""
return self == other or self < other
def __ge__(self, other):
"""Returns self >= other, with respect
to names."""
return self == other or self > other
def __eq__(self, other):
"""Tests for equality."""
if self is other:
return True
elif type(self) != type(other):
return False
else:
return self._name == other._name
def main():
"""Tests equality and comparisons."""
s1 = Student("Ken", 10)
s2 = Student("Mary", 10)
s3 = Student("Ken", 10)
print("False:", s1 == s2)
print("True:", s1 == s3)
print("True:", s1 == s1)
print("False:", s1 is s3)
print("True:", s1 < s2)
print("True:", s2 > s1)
print("True:", s2 >= s1)
print("True:", s1 >= s3)
print("True:", s1 <= s2)
print("True:", s1 <= s3)

main()
Output: -
20 This project assumes that you have completed Project 1. Place
several Student objects into a list and shuffle it. Then run the
sort method with this list and display all of the students’
information

Code: -
"""Resources to manage a student's name and test scores.
Includes methods for comparisons and testing for equality.
Tests the class by putting students into random order in a list
and then sorting them."""
from functools import reduce
class Student(object):
"""Represents a student."""
def __init__(self, name, number):
"""All scores are initially 0."""
self._name = name
self._scores = []
for count in range(number):
self._scores.append(0)
def getName(self):
"""Returns the student's name."""
return self._name
def setScore(self, i, score):
"""Resets the ith score, counting from 1."""
self._scores[i - 1] = score
def getScore(self, i):
"""Returns the ith score, counting from 1."""
return self._scores[i - 1]
def getAverage(self):
"""Returns the average score."""
sum = reduce(lambda x, y: x + y, self._scores)
return sum / len(self._scores)
def getHighScore(self):
"""Returns the highest score."""
return reduce(lambda x, y: max(x, y), self._scores)
def __str__(self):
"""Returns the string representation of the student."""
return "Name: " + self._name + "\nScores: " + \
" ".join(map(str, self._scores))
def __lt__(self, other):
"""Returns self < other, with respect
to names."""
return self._name < other._name
def __gt__(self, other):
"""Returns self > other, with respect
to names."""
return not (self == other or self < other)
def __le__(self, other):
"""Returns self <= other, with respect
to names."""
return self == other or self < other
def __ge__(self, other):
"""Returns self >= other, with respect
to names."""
return self == other or self > other
def __eq__(self, other):
"""Tests for equality."""
if self is other:
return True
elif type(self) != type(other):
return False
else:
return self._name == other._name
import random
def main():
"""Tests sorting."""
# Create the list and put 5 students into it
lyst = []
for count in range(5):
s = Student("Name" + str(count + 1), 10)
lyst.append(s)
# Shuffle and print the contents
random.shuffle(lyst)
print("Unsorted list of students:")
for s in lyst:
print(s)
# Sort and print the contents
lyst.sort()
print("\nSorted list of students:")
for s in lyst:
print(s)

main()
Output: -
21 Geometric shapes can be modeled as classes. Develop classes
for line segments, circles, and rectangles. Each shape object
should contain a Turtle object and a color that allow the
shape to be drawn in a Turtle graphics window . Factor the
code for these features (instance variables and methods) into
an abstract Shape class. The Circle, Rectangle, and Line
classes are all subclasses of Shape. These subclasses include
other information about the specific types of shapes, such as a
radius or a corner point and a draw method. Write a script
that uses several instances of the different shape classes to
draw a house and a stick figure.

Code: -
Shapes.py
"""
Defines classes for line segments, circles, and rectangles using a turtle
object to draw them.
"""
import math
class Shape(object):
"""Represents a shape with a color and a turtle."""
def __init__(self, turtle, color):
self._turtle = turtle
self._color = color
def getColor(self):
return self._color
def setColor(self, color):
self._color = color
class Line(Shape):
"""Represents a line segment."""
def __init__(self, x1, y1, x2, y2, turtle, color):
Shape.__init__(self, turtle, color)
self._x1 = x1
self._x2 = x2
self._y1 = y1
self._y2 = y2
def draw(self):
"""Draws a line."""
(r, g, b) = self._color
self._turtle.up()
self._turtle.goto(self._x1, self._y1)
self._turtle.pencolor(r, g, b)
self._turtle.down()
self._turtle.goto(self._x2, self._y2)
class Circle(Shape):
"""Represents a circle."""
def __init__(self, x, y, radius, turtle, color):
Shape.__init__(self, turtle, color)
self._x = x
self._y = y
self._radius = radius
def draw(self):
"""Draws a circle."""
(r, g, b) = self._color
amount = 2.0 * math.pi * self._radius / 120.0
self._turtle.up()
self._turtle.goto(self._x + self._radius, self._y)
self._turtle.setheading(90)
self._turtle.down()
self._turtle.pencolor(r, g, b)
for count in range(120):
self._turtle.left(3)
self._turtle.forward(amount)
class Rectangle(Shape):
"""Represents a rectangle."""
def __init__(self, x, y, width, height, turtle, color):
Shape.__init__(self, turtle, color)
self._x = x
self._y = y
self._width = width
self._height = height
def draw(self):
"""Draws a rectangle."""
(r, g, b) = self._color
self._turtle.up()
self._turtle.goto(self._x, self._y)
self._turtle.setheading(0)
self._turtle.down()
self._turtle.pencolor(r, g, b)
self._turtle.forward(self._width)
self._turtle.left(-90)
self._turtle.forward(self._height)
self._turtle.left(-90)
self._turtle.forward(self._width)
self._turtle.left(-90)
self._turtle.forward(self._height)

main.py
"""
output:
Draws a stick figure and a house using shape classes.
"""
from shapes import Circle, Line, Rectangle
from turtle import Turtle
def main():
"""Draws a house and stick figure."""
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
turtle = Turtle()
turtle.hideturtle()
# Draw the stick figure
face = Circle(100, 0, 10, turtle, black)
body = Line(100, -10, 100, - 80, turtle, black)
arms = Line(80, -40, 120, -40, turtle, black)
leftLeg = Line(100, -80, 80, -100, turtle, black)
rightLeg = Line(100, -80, 120, -100, turtle, black)
face.draw()
body.draw()
arms.draw()
leftLeg.draw()
rightLeg.draw()
# Draw the house
front = Rectangle(-180, 0, 120, 60, turtle, black)
door = Rectangle(-100, -30, 15, 30, turtle, blue)
roof1 = Line(-180, 0, -160, 20, turtle, red)
roof2 = Line(-160, 20, -80, 20, turtle, red)
roof3 = Line(-80, 20, -60, 0, turtle, red)
front.draw()
door.draw()
roof1.draw()
roof2.draw()
roof3.draw()

main()

Output: -

You might also like