Python Programming Assignment: Algorithms and Application Development
VerifiedAdded on  2023/03/16
|26
|6985
|50
Homework Assignment
AI Summary
This Python 3 assignment solution encompasses a range of programming tasks designed to demonstrate understanding of fundamental programming concepts. The assignment includes implementations of various algorithms, from simple "Hello, world!" programs to more complex applications involving user input, calculations, and the generation of random numbers. It covers topics such as defining algorithms, procedural and object-oriented programming characteristics, and the use of an Integrated Development Environment (IDE). The solution also explores debugging processes and the importance of coding standards. The code snippets provided demonstrate how to create menu-driven interfaces, handle user input, perform calculations, and implement game logic. Furthermore, the assignment touches upon external API calls, data manipulation, and file handling. The solution includes code for time calculations, geometric area and perimeter computations, and analysis of student examination results. Finally, the assignment includes a bouncing ball game and a menu-driven program to practice basic mathematical operations, demonstrating a comprehensive approach to programming fundamentals.

Python 3
Submitted by:
Date:
Submitted by:
Date:
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser

Table of content
Introduction
Single program which comprises the various tasks (1.1-1.10)
LO1 Define basic algorithms to carry out an operation and outline the process of programming
an application.
LO2 Explain the characteristics of procedural, object-orientated and event driven programming,
conduct an analysis of a suitable Integrated Development Environment (IDE)
LO3 Implement basic algorithms in code using an IDE
LO4 Determine the debugging process and explain the importance of a coding standard
Conclusion
Reference
Introduction
Single program which comprises the various tasks (1.1-1.10)
LO1 Define basic algorithms to carry out an operation and outline the process of programming
an application.
LO2 Explain the characteristics of procedural, object-orientated and event driven programming,
conduct an analysis of a suitable Integrated Development Environment (IDE)
LO3 Implement basic algorithms in code using an IDE
LO4 Determine the debugging process and explain the importance of a coding standard
Conclusion
Reference

1.1 Hello C# (Menu Item 1)
import time
name = input('Enter your name: ')
time = input('Enter time of the day: ')
print('Hello, world!')
currentTime = time.strftime('%H:%M')
if currentTime.hour < 12 :
print('Good morning')
if currentTime.hour > 12 :
print('Good afternoon')
if currentTime.hour > 6 :
print('Good evening')
1.2 Your Name Characters (Menu item 2)
for i in range(0, 5):
for j in range(0, i+1):
print("0",end="")
print()
1.3 The Area and the perimeter of a Rectangle (Menu item 3)
print("Enter 'x' for exit.");
side1 = input("Enter length of first side: ");
if side1 == 'x':
exit();
else:
side2 = input("Enter length of second side: ");
side3 = input("Enter length of third side: ");
a = float(side1);
b = float(side2);
c = float(side3);
s = (a + b + c)/2;
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5;
print("\nArea of Triangle = %0.2f" %area);
import time
name = input('Enter your name: ')
time = input('Enter time of the day: ')
print('Hello, world!')
currentTime = time.strftime('%H:%M')
if currentTime.hour < 12 :
print('Good morning')
if currentTime.hour > 12 :
print('Good afternoon')
if currentTime.hour > 6 :
print('Good evening')
1.2 Your Name Characters (Menu item 2)
for i in range(0, 5):
for j in range(0, i+1):
print("0",end="")
print()
1.3 The Area and the perimeter of a Rectangle (Menu item 3)
print("Enter 'x' for exit.");
side1 = input("Enter length of first side: ");
if side1 == 'x':
exit();
else:
side2 = input("Enter length of second side: ");
side3 = input("Enter length of third side: ");
a = float(side1);
b = float(side2);
c = float(side3);
s = (a + b + c)/2;
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5;
print("\nArea of Triangle = %0.2f" %area);
⊘ This is a preview!⊘
Do you want full access?
Subscribe today to unlock all pages.

Trusted by 1+ million students worldwide

1.4 Time of Journey (Menu item 4)
import simplejson, urllib
import re
import time
import operator
import os
import sys
import argparse
from collections import defaultdict
REMOVE_HTML_TAGS = r'<[^>]+>'
GEOCODE_BASE_URL =
'http://maps.googleapis.com/maps/api/geocode/json'
DIRECTIONS_BASE_URL =
'http://maps.googleapis.com/maps/api/directions/json'
def geocode(address, **geo_args):
geo_args.update({
'address': address
})
url = GEOCODE_BASE_URL + '?' + urllib.urlencode(geo_args)
result = simplejson.load(urllib.urlopen(url))
return result['results']
def reverse_geocode(lat, lng):
geo_args = {
'latlng': "%s,%s" % (lat, lng)
}
url = GEOCODE_BASE_URL + '?' + urllib.urlencode(geo_args)
result = simplejson.load(urllib.urlopen(url))
return result['results']
def directions(source, destination, **geo_args):
geo_args.update({
'origin': source,
'destination': destination
})
import simplejson, urllib
import re
import time
import operator
import os
import sys
import argparse
from collections import defaultdict
REMOVE_HTML_TAGS = r'<[^>]+>'
GEOCODE_BASE_URL =
'http://maps.googleapis.com/maps/api/geocode/json'
DIRECTIONS_BASE_URL =
'http://maps.googleapis.com/maps/api/directions/json'
def geocode(address, **geo_args):
geo_args.update({
'address': address
})
url = GEOCODE_BASE_URL + '?' + urllib.urlencode(geo_args)
result = simplejson.load(urllib.urlopen(url))
return result['results']
def reverse_geocode(lat, lng):
geo_args = {
'latlng': "%s,%s" % (lat, lng)
}
url = GEOCODE_BASE_URL + '?' + urllib.urlencode(geo_args)
result = simplejson.load(urllib.urlopen(url))
return result['results']
def directions(source, destination, **geo_args):
geo_args.update({
'origin': source,
'destination': destination
})
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser

url = DIRECTIONS_BASE_URL + '?' + urllib.urlencode(geo_args)
return simplejson.load(urllib.urlopen(url))
def output_routes(mode, routes):
timings = defaultdict(lambda: 0)
distances = defaultdict(lambda: 0)
for route in routes:
for leg in route['legs']:
print "Distance: ", leg['distance']['text']
print "Duration: ", leg['duration']['text']
for step in leg['steps']:
travel_mode = step['travel_mode']
if 'html_instructions' in step:
direction_text = re.sub(REMOVE_HTML_TAGS, '
', step['html_instructions'])
else:
direction_text = '(no direction text)'
distance = step['distance']
duration = step['duration']
encoded_direction_text =
direction_text.encode('latin1', errors='ignore')
print "%s (%s, %s, %s)" %
(encoded_direction_text, travel_mode,
duration['text'], distance['text'])
timings["%s-%s" % (mode, travel_mode)] +=
duration['value']
distances["%s-%s" % (mode, travel_mode)] +=
distance['value']
return timings, distances
if __name__ == '__main__':
ap = argparse.ArgumentParser()
ap.add_argument("--dry-run", required=False, default=False,
action='store_true', help="Don't make API calls")
ap.add_argument("--min-lng", required=False, default=103.73,
type=float, help="Minimum longitude (Default 103.73)")
ap.add_argument("--max-lng", required=False, default=103.84,
type=float, help="Maximum longitude (Default 103.84)")
ap.add_argument("--min-lat", required=False, default=1.27,
type=float, help="Minimum latitude (Default 1.27)")
ap.add_argument("--max-lat", required=False, default=1.345,
type=float, help="Maximum latitude (Default 1.345)")
return simplejson.load(urllib.urlopen(url))
def output_routes(mode, routes):
timings = defaultdict(lambda: 0)
distances = defaultdict(lambda: 0)
for route in routes:
for leg in route['legs']:
print "Distance: ", leg['distance']['text']
print "Duration: ", leg['duration']['text']
for step in leg['steps']:
travel_mode = step['travel_mode']
if 'html_instructions' in step:
direction_text = re.sub(REMOVE_HTML_TAGS, '
', step['html_instructions'])
else:
direction_text = '(no direction text)'
distance = step['distance']
duration = step['duration']
encoded_direction_text =
direction_text.encode('latin1', errors='ignore')
print "%s (%s, %s, %s)" %
(encoded_direction_text, travel_mode,
duration['text'], distance['text'])
timings["%s-%s" % (mode, travel_mode)] +=
duration['value']
distances["%s-%s" % (mode, travel_mode)] +=
distance['value']
return timings, distances
if __name__ == '__main__':
ap = argparse.ArgumentParser()
ap.add_argument("--dry-run", required=False, default=False,
action='store_true', help="Don't make API calls")
ap.add_argument("--min-lng", required=False, default=103.73,
type=float, help="Minimum longitude (Default 103.73)")
ap.add_argument("--max-lng", required=False, default=103.84,
type=float, help="Maximum longitude (Default 103.84)")
ap.add_argument("--min-lat", required=False, default=1.27,
type=float, help="Minimum latitude (Default 1.27)")
ap.add_argument("--max-lat", required=False, default=1.345,
type=float, help="Maximum latitude (Default 1.345)")

ap.add_argument("--step-lng", required=False,
default=0.00125,
type=float, help="Increment longitude amount (Default
0.00125)")
ap.add_argument("--step-lat", required=False,
default=0.00125,
type=float, help="Increment latitude amount (Default
0.00125)")
args = vars(ap.parse_args())
print args
# load existing timings
if os.path.exists('timings.csv'):
timings = [ row.strip().split('\t') for row in
file('timings.csv') ]
else:
timings = []
print 'Found %d existing timings' % len(timings)
latlngs = dict(('%s,%s' % (k,v), True) for (k,v,_,_,_,_) in
timings)
if not args['dry_run']:
results = geocode(address="The Pinnacle @ Duxton")
data = results[0]
location = data['geometry']['location']
lat, lng = location['lat'], location['lng']
source = "%s,%s" % (lat, lng)
print source
with open('source.txt', 'w') as sourcef:
sourcef.write("%s,%s\n" % (lat, lng))
results = reverse_geocode(lat, lng)
print 'Reverse geocoded address for lat,lng: %.3f,%.3f' %
(lat, lng)
print '\n'.join([ x['formatted_address'] for x in results
])
print
time.sleep(5)
eight_am =
int(time.mktime(time.struct_time([2014,7,14,8,0,0,0,0,0])))
# starting longitude
default=0.00125,
type=float, help="Increment longitude amount (Default
0.00125)")
ap.add_argument("--step-lat", required=False,
default=0.00125,
type=float, help="Increment latitude amount (Default
0.00125)")
args = vars(ap.parse_args())
print args
# load existing timings
if os.path.exists('timings.csv'):
timings = [ row.strip().split('\t') for row in
file('timings.csv') ]
else:
timings = []
print 'Found %d existing timings' % len(timings)
latlngs = dict(('%s,%s' % (k,v), True) for (k,v,_,_,_,_) in
timings)
if not args['dry_run']:
results = geocode(address="The Pinnacle @ Duxton")
data = results[0]
location = data['geometry']['location']
lat, lng = location['lat'], location['lng']
source = "%s,%s" % (lat, lng)
print source
with open('source.txt', 'w') as sourcef:
sourcef.write("%s,%s\n" % (lat, lng))
results = reverse_geocode(lat, lng)
print 'Reverse geocoded address for lat,lng: %.3f,%.3f' %
(lat, lng)
print '\n'.join([ x['formatted_address'] for x in results
])
time.sleep(5)
eight_am =
int(time.mktime(time.struct_time([2014,7,14,8,0,0,0,0,0])))
# starting longitude
⊘ This is a preview!⊘
Do you want full access?
Subscribe today to unlock all pages.

Trusted by 1+ million students worldwide

lng_f = args['min_lng']
min_lat_f = args['min_lat']
while lng_f < args['max_lng']:
# starting latitude
lat_f = args['max_lat']
while lat_f >= min_lat_f:
print 'Querying directions for (%.6f, %.6f)' %
(lat_f, lng_f)
key = '%.6f,%.6f' % (lat_f, lng_f)
if latlngs.has_key(key):
lat_f -= args['step_lat']
print 'Timing already exists - skipping.'
continue
if not args['dry_run']:
results = reverse_geocode(lat_f, lng_f)
print 'Reverse geocoded address for lat,lng:
%.3f,%.3f' % (lat_f, lng_f)
print '\n'.join([ x['formatted_address'] for x in
results ])
print
durations = defaultdict(lambda: 0)
distances = defaultdict(lambda: 0)
if not args['dry_run']:
for mode in ['driving','walking','transit']:
params = {
'mode': mode,
'region': 'sg',
'alternatives': 'false',
'departure_time': eight_am
}
data = directions(source, '%s,%s' % (lat_f,
lng_f), **params)
print data['status']
while data['status'] == 'OVER_QUERY_LIMIT':
min_lat_f = args['min_lat']
while lng_f < args['max_lng']:
# starting latitude
lat_f = args['max_lat']
while lat_f >= min_lat_f:
print 'Querying directions for (%.6f, %.6f)' %
(lat_f, lng_f)
key = '%.6f,%.6f' % (lat_f, lng_f)
if latlngs.has_key(key):
lat_f -= args['step_lat']
print 'Timing already exists - skipping.'
continue
if not args['dry_run']:
results = reverse_geocode(lat_f, lng_f)
print 'Reverse geocoded address for lat,lng:
%.3f,%.3f' % (lat_f, lng_f)
print '\n'.join([ x['formatted_address'] for x in
results ])
durations = defaultdict(lambda: 0)
distances = defaultdict(lambda: 0)
if not args['dry_run']:
for mode in ['driving','walking','transit']:
params = {
'mode': mode,
'region': 'sg',
'alternatives': 'false',
'departure_time': eight_am
}
data = directions(source, '%s,%s' % (lat_f,
lng_f), **params)
print data['status']
while data['status'] == 'OVER_QUERY_LIMIT':
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser

print 'Pausing for five minutes...'
time.sleep(300)
data = directions(source, '%s,%s' %
(lat_f, lng_f), **params)
if len(data['routes']) > 0:
timings, dist = output_routes(mode,
data['routes'])
durations.update(timings)
distances.update(dist)
print 'Timings:'
print timings.viewitems()
print 'Distances:'
print dist.viewitems()
time.sleep(2)
print sorted(durations.iteritems(),
key=operator.itemgetter(1))
get_stats = lambda d: [ d['driving-DRIVING'],
d['transit-TRANSIT'],
d['transit-WALKING'], d['walking-WALKING'] ]
with open('timings.csv','a+') as outf:
stats = get_stats(durations)
params = [lat_f, lng_f]; params.extend(stats)
outf.write("%.6f\t%.6f\t%s\t%s\t%s\t%s\n" %
tuple(params))
with open('distances.csv','a+') as outf:
stats = get_stats(distances)
params = [lat_f, lng_f]; params.extend(stats)
outf.write("%.6f\t%.6f\t%s\t%s\t%s\t%s\n" %
tuple(params))
lat_f -= args['step_lat']
lng_f += args['step_lng']
1.5 The Student Examination Results Analysis (Menu item 5)
time.sleep(300)
data = directions(source, '%s,%s' %
(lat_f, lng_f), **params)
if len(data['routes']) > 0:
timings, dist = output_routes(mode,
data['routes'])
durations.update(timings)
distances.update(dist)
print 'Timings:'
print timings.viewitems()
print 'Distances:'
print dist.viewitems()
time.sleep(2)
print sorted(durations.iteritems(),
key=operator.itemgetter(1))
get_stats = lambda d: [ d['driving-DRIVING'],
d['transit-TRANSIT'],
d['transit-WALKING'], d['walking-WALKING'] ]
with open('timings.csv','a+') as outf:
stats = get_stats(durations)
params = [lat_f, lng_f]; params.extend(stats)
outf.write("%.6f\t%.6f\t%s\t%s\t%s\t%s\n" %
tuple(params))
with open('distances.csv','a+') as outf:
stats = get_stats(distances)
params = [lat_f, lng_f]; params.extend(stats)
outf.write("%.6f\t%.6f\t%s\t%s\t%s\t%s\n" %
tuple(params))
lat_f -= args['step_lat']
lng_f += args['step_lng']
1.5 The Student Examination Results Analysis (Menu item 5)

print("The average of the Exam is", round(Exam_average, 2))
if 90 <= Final_grade <= 100:
return 'A'
elif 80 <= Final_grade <= 89:
return 'B'
elif 70 <= Final_grade <= 79:
return 'C'
elif 60 <= Final_grade <= 40:
return 'D'
else:
return 'F'
1.6 The Random Number Generator (Menu item 6)
import random
# Function to generate
# and append them
# start = starting range,
# end = ending range
# num = number of
# elements needs to be appended
def Rand(start, end, num):
res = []
for j in range(num):
res.append(random.randint(start, end))
return res
# Driver Code
num = 8
start = 1
end = 79
print(Rand(start, end, num))
1.7 The Sum of the Elements of an Array (Menu item 7)
def _sum(arr,n):
# return sum using sum
# inbuilt sum() function
if 90 <= Final_grade <= 100:
return 'A'
elif 80 <= Final_grade <= 89:
return 'B'
elif 70 <= Final_grade <= 79:
return 'C'
elif 60 <= Final_grade <= 40:
return 'D'
else:
return 'F'
1.6 The Random Number Generator (Menu item 6)
import random
# Function to generate
# and append them
# start = starting range,
# end = ending range
# num = number of
# elements needs to be appended
def Rand(start, end, num):
res = []
for j in range(num):
res.append(random.randint(start, end))
return res
# Driver Code
num = 8
start = 1
end = 79
print(Rand(start, end, num))
1.7 The Sum of the Elements of an Array (Menu item 7)
def _sum(arr,n):
# return sum using sum
# inbuilt sum() function
⊘ This is a preview!⊘
Do you want full access?
Subscribe today to unlock all pages.

Trusted by 1+ million students worldwide

return(sum(arr))
# driver function
arr=[]
# input values to list
arr = [12, 3, 4, 15]
# calculating length of array
n = len(arr)
ans = _sum(arr,n)
# display sum
print (\'Sum of the array is \',ans)
1.8 Bouncing Ball Game (Menu item 8)
from tkinter import *
import time
import random
WIDTH = 800
HEIGHT = 500
tk = Tk()
canvas = Canvas(tk, width=WIDTH, height=HEIGHT, bg="black")
tk.title("Drawing")
canvas.pack()
colors = ['red', 'green', 'blue', 'orange', 'yellow', 'cyan',
'magenta',
'dodgerblue', 'turquoise', 'grey', 'gold', 'pink']
class Ball:
def __init__(self):
self.size = random.randrange(200, 400)
color = random.choice(colors)
self.shape = canvas.create_rectangle(0, 0, self.size,
self.size, fill=color)
self.speedx = random.randrange(1, 10)
self.speedy = random.randrange(1, 10)
def update(self):
# driver function
arr=[]
# input values to list
arr = [12, 3, 4, 15]
# calculating length of array
n = len(arr)
ans = _sum(arr,n)
# display sum
print (\'Sum of the array is \',ans)
1.8 Bouncing Ball Game (Menu item 8)
from tkinter import *
import time
import random
WIDTH = 800
HEIGHT = 500
tk = Tk()
canvas = Canvas(tk, width=WIDTH, height=HEIGHT, bg="black")
tk.title("Drawing")
canvas.pack()
colors = ['red', 'green', 'blue', 'orange', 'yellow', 'cyan',
'magenta',
'dodgerblue', 'turquoise', 'grey', 'gold', 'pink']
class Ball:
def __init__(self):
self.size = random.randrange(200, 400)
color = random.choice(colors)
self.shape = canvas.create_rectangle(0, 0, self.size,
self.size, fill=color)
self.speedx = random.randrange(1, 10)
self.speedy = random.randrange(1, 10)
def update(self):
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser

canvas.move(self.shape, self.speedx, self.speedy)
pos = canvas.coords(self.shape)
if pos[2] >= WIDTH or pos[0] <= 0:
self.speedx *= -1
if pos[3] >= HEIGHT or pos[1] <= 0:
self.speedy *= -1
ball_list = []
for i in range(100):
ball_list.append(Ball())
while True:
for ball in ball_list:
ball.update()
tk.update()
time.sleep(0.01)
1.9 Maths practice questions (Menu item 9)
print("Enter 'x' for exit.");
print("Enter any two number: ");
num1 = input();
num2 = input();
if num1 == 'x':
exit();
else:
ch = input("Enter operator (+,-,*,/): ");
if ch == '+':
res = int(num1) + int(num2);
print(num1, "+", num2, "=", res);
elif ch == '-':
res = int(num1) - int(num2);
print(num1, "-", num2, "=", res);
elif ch == '*':
res = int(num1) * int(num2);
print(num1, "*", num2, "=", res);
elif ch == '/':
res = int(num1) / int(num2);
print(num1, "/", num2, "=", res);
else:
print("Strange input..exiting..");
1.10 Exit (Menu item 10)
pos = canvas.coords(self.shape)
if pos[2] >= WIDTH or pos[0] <= 0:
self.speedx *= -1
if pos[3] >= HEIGHT or pos[1] <= 0:
self.speedy *= -1
ball_list = []
for i in range(100):
ball_list.append(Ball())
while True:
for ball in ball_list:
ball.update()
tk.update()
time.sleep(0.01)
1.9 Maths practice questions (Menu item 9)
print("Enter 'x' for exit.");
print("Enter any two number: ");
num1 = input();
num2 = input();
if num1 == 'x':
exit();
else:
ch = input("Enter operator (+,-,*,/): ");
if ch == '+':
res = int(num1) + int(num2);
print(num1, "+", num2, "=", res);
elif ch == '-':
res = int(num1) - int(num2);
print(num1, "-", num2, "=", res);
elif ch == '*':
res = int(num1) * int(num2);
print(num1, "*", num2, "=", res);
elif ch == '/':
res = int(num1) / int(num2);
print(num1, "/", num2, "=", res);
else:
print("Strange input..exiting..");
1.10 Exit (Menu item 10)

def print_menu(): ## Your menu design here
print 30 * "-" , "MENU" , 30 * "-"
print "1. Menu Option 1"
print "2. Menu Option 2"
print "3. Menu Option 3"
print "4. Menu Option 4"
print "5. Exit"
print 67 * "-"
loop=True
while loop: ## While loop which will keep going until
loop = False
print_menu() ## Displays menu
choice = input("Enter your choice [1-5]: ")
if choice==1:
print "Menu 1 has been selected"
## You can add your code or functions here
elif choice==2:
print "Menu 2 has been selected"
## You can add your code or functions here
elif choice==3:
print "Menu 3 has been selected"
## You can add your code or functions here
elif choice==4:
print "Menu 4 has been selected"
## You can add your code or functions here
elif choice==5:
print "Menu 5 has been selected"
## You can add your code or functions here
loop=False # This will make the while loop to end as not
value of loop is set to False
else:
# Any integer inputs other than values 1-5 we print an
error message
raw_input("Wrong option selection. Enter any key to try
again..")
print 30 * "-" , "MENU" , 30 * "-"
print "1. Menu Option 1"
print "2. Menu Option 2"
print "3. Menu Option 3"
print "4. Menu Option 4"
print "5. Exit"
print 67 * "-"
loop=True
while loop: ## While loop which will keep going until
loop = False
print_menu() ## Displays menu
choice = input("Enter your choice [1-5]: ")
if choice==1:
print "Menu 1 has been selected"
## You can add your code or functions here
elif choice==2:
print "Menu 2 has been selected"
## You can add your code or functions here
elif choice==3:
print "Menu 3 has been selected"
## You can add your code or functions here
elif choice==4:
print "Menu 4 has been selected"
## You can add your code or functions here
elif choice==5:
print "Menu 5 has been selected"
## You can add your code or functions here
loop=False # This will make the while loop to end as not
value of loop is set to False
else:
# Any integer inputs other than values 1-5 we print an
error message
raw_input("Wrong option selection. Enter any key to try
again..")
⊘ This is a preview!⊘
Do you want full access?
Subscribe today to unlock all pages.

Trusted by 1+ million students worldwide
1 out of 26

Your All-in-One AI-Powered Toolkit for Academic Success.
 +13062052269
info@desklib.com
Available 24*7 on WhatsApp / Email
Unlock your academic potential
Copyright © 2020–2025 A2Z Services. All Rights Reserved. Developed and managed by ZUCOL.