Skip to content

Commit 7d355e8

Browse files
author
Mark Charlton
committed
Wk 9 done
1 parent 84ce441 commit 7d355e8

15 files changed

+314
-1
lines changed

Assessment/Wk7/character_gen.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ def move_points(s_class):
227227
print ( f"You require {req_p} extra points to become a {s_target}." )
228228

229229
if int(req_p*2)>int(free_p):
230-
print ( f"You only have {free_p} free points, (and you need {req_p*2}). \nSadly that's not enough free points to become an {s_target}. \nPlease try again.")
230+
print ( f"You only have {free_p} free points, (and you need {req_p*2}). \nSadly that's not enough free points to become a {s_target}. \nPlease try again.")
231231
else :
232232
print ( f"You have {free_p} points available and you only need {req_p*2} free points!")
233233

Assessment/Wk8/swap_ints.jpg

47.5 KB
Loading

Assessment/Wk9/alphabetical.jpg

74.8 KB
Loading

Assessment/Wk9/alphabetical.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Sort 5 strings alphabetically.
2+
3+
# inits
4+
a_string=[]
5+
6+
def print_me(lst1):
7+
for i in range(len(lst1)):
8+
print ( f'{i+1}: {lst1[i]}')
9+
print ("")
10+
11+
# get user input
12+
for i in range(5):
13+
tmp_var = input ( f"Please enter string {i+1}: " )
14+
if tmp_var.strip() == "":
15+
break
16+
a_string.append(tmp_var)
17+
18+
if len(a_string)==5:
19+
print ( f'Initial list is: ')
20+
print_me( a_string )
21+
22+
a_string.sort()
23+
print ( f'Sorted list is: ')
24+
print_me( a_string )
25+
26+
a_string_words = [' '.join(sorted(str.split(" "))).strip() for str in a_string]
27+
a_string_words.sort()
28+
print ( f'Internally Sensibly Sorted list is: ')
29+
print_me(a_string_words)
30+
31+
a_string_chars = [(''.join(sorted([*str]))).strip() for str in a_string]
32+
a_string_chars.sort()
33+
print ( f'Internally Unsensibly Sorted Stripped list is: ')
34+
print_me(a_string_chars)

Assessment/Wk9/insertion_sort.jpg

24.7 KB
Loading

Assessment/Wk9/insertion_sort.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
## Insertion sort implementation
2+
3+
import os
4+
import sys
5+
6+
sys.path.append(os.path.abspath('..\\inc\\'))
7+
import helpers as h
8+
9+
## Direction is D for Descending, pretty much anything else for Ascending
10+
def ins_sort(l_data, direction = "D"):
11+
for i in range(1,len(l_data)):
12+
tmp_val=l_data[i]
13+
j=i-1
14+
15+
# build the test
16+
if direction=="D":
17+
s_test=f"{l_data[j]}<{tmp_val}"
18+
else:
19+
s_test=f"{l_data[j]}>{tmp_val}"
20+
21+
while j >=0 and eval(s_test):
22+
l_data[j+1] = l_data[j]
23+
j -= 1
24+
25+
# build the test
26+
if direction=="D":
27+
s_test=f"{l_data[j]}<{tmp_val}"
28+
else:
29+
s_test=f"{l_data[j]}>{tmp_val}"
30+
l_data[j+1]=tmp_val
31+
return l_data
32+
33+
l_test_data=[] # [2,5,3,6,2,67,3,5,7,3,2,5,76,3,2,65,765,2,8,3,7]
34+
a_direction={"A":"Ascending",
35+
"D":"Descending"}
36+
37+
for i in range(5):
38+
tmp_int = h.get_int("Please enter an integer: ",1,9999)
39+
l_test_data.append(tmp_int)
40+
41+
s_sort =""
42+
while s_sort!="A" and s_sort != "D":
43+
s_sort = input ("Please select the direction of sort, [A]scending or [D]escending: ").upper()
44+
45+
print ("You provided: ")
46+
print (l_test_data)
47+
print ( f"You selected sorting {a_direction[s_sort]}")
48+
l_sorted = ins_sort(l_test_data, s_sort)
49+
print ( "Sorted that looks like: ")
50+
print (l_sorted)

Assessment/Wk9/shop_list.jpg

47 KB
Loading

Assessment/Wk9/shop_list.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# order a shopping list by price descending
2+
3+
4+
# Screen control params
5+
CLEAR = '\x1b[2K'
6+
RESET = '\033[2J'
7+
BLINKON = '\033[32;5m'
8+
BLINKOFF = '\033[0m'
9+
REVON = "\033[7m"
10+
REVOFF = "\033[0m"
11+
BLUEON = "\033[34m" # Blue text.
12+
REDON= "\033[31m" # Red text.
13+
GREENON = "\033[32m" # Green text.
14+
COLOUROFF = "\033[0m" #Reset special formatting (such as colour).
15+
16+
def get_item():
17+
s_item=input(f"Please enter item {len(d_items)+1}: ")
18+
if s_item != "":
19+
try:
20+
f_price=float(input(f"Please enter the {s_item} price: "))
21+
except:
22+
# Error occured!
23+
s_item=""
24+
f_price="0"
25+
26+
if s_item != "":
27+
return s_item, f_price
28+
return "",0
29+
30+
#inits
31+
d_items={} # {'iteam 1': 1.99, 'item 2': 40.0, 'item 3': 20.0, 'item 4': 99.0, 'item 5': 404.0, 'item 6': 3.45}
32+
s_item="Z"
33+
34+
print (RESET)
35+
print (REVON + "Shopping List Sorter II " + REVOFF)
36+
print (" - bringing order to chaos")
37+
print (BLUEON + "--------------------------" + COLOUROFF)
38+
39+
print ( f"Please enter 5 items and their prices. ")
40+
print (BLUEON + "--------------------------" + COLOUROFF)
41+
print ( f" *** {REDON}Press <enter> on blank item to exit list entry{COLOUROFF} ***\n")
42+
while s_item > "":
43+
s_item, f_price = get_item()
44+
if s_item=="":
45+
break
46+
47+
d_items[s_item]=f_price
48+
49+
if len(d_items) > 0:
50+
l_items_sorted=sorted(d_items.items(), key=lambda item: item[1], reverse=True)
51+
52+
i_max_len=max([len(key) for key in d_items.keys()])
53+
i_max_len = int(i_max_len)+2
54+
55+
print ( "Your Shopping List: ")
56+
print (f'{"Item":{i_max_len}} {"Price":>7}' )
57+
print ( "=" * (i_max_len+9))
58+
for t_item in l_items_sorted:
59+
print (f'{t_item[0]:{i_max_len}} £{t_item[1]:>7.2f}' )

Assessment/Wk9/tally_chart.jpg

10.7 KB
Loading

Assessment/Wk9/tally_chart.py

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
# Do some voting and the like.
2+
3+
import os
4+
import sys
5+
import time
6+
import random as r
7+
import matplotlib.pyplot as mpl
8+
9+
sys.path.append(os.path.abspath('..\\inc\\'))
10+
11+
import screen as s
12+
13+
names = [ "Liam", "Olivia", "Noah", "Emma", "Oliver", "Ava", "Elijah", "Charlotte", "William", "Sophia", "James", "Amelia", "Benjamin", "Isabella", "Lucas", "Mia", "Henry", "Evelyn", "Alexander", "Harper", "Michael", "Abigail", "Ethan", "Emily", "Daniel", "Elizabeth", "Matthew", "Mila", "Jackson", "Ella", "Sebastian", "Avery", "Aiden", "Sofia", "Logan", "Camila", "Mason", "Aria", "Ezra", "Scarlett", "Grayson", "Victoria", "Carter", "Madison", "Luke", "Luna", "Jayden", "Grace", "Levi", "Chloe", "Isaac", "Penelope", "Lincoln", "Riley", "Nicholas", "Zoey", "David", "Lily", "Connor", "Ellie", "Wyatt", "Nora", "Owen", "Hazel", "Caleb", "Aurora", "Ryan", "Addison", "Gabriel", "Hannah", "Nathan", "Stella", "Leah", "Maya", "Isaiah", "Aaliyah", "Eli", "Nova", "Hunter", "Eleanor", "Landon", "Paisley", "Nicholas", "Naomi", "Jeremiah", "Ariana", "Ezekiel", "Claire", "Aaron", "Elena"]
14+
15+
a_candidates={}
16+
a_results={}
17+
18+
def init_candidates():
19+
global a_candidates
20+
l_names=r.sample(names,5)
21+
for name in l_names:
22+
a_candidates[name]=0
23+
24+
25+
def get_vote():
26+
global a_candidates
27+
28+
l_candidates=list(a_candidates.keys())
29+
r.shuffle(l_candidates)
30+
display_candidates(l_candidates)
31+
try:
32+
i_vote=int ( input ("Please enter the number of your chosen candidate [-1 to quit]: ") )
33+
if i_vote == -1:
34+
return -1
35+
elif 1 <= i_vote <= len(l_candidates):
36+
a_candidates[l_candidates[i_vote-1]] += 1
37+
return 1
38+
else:
39+
print ( "Invalid vote cast" )
40+
time.sleep(1)
41+
return 0
42+
except:
43+
print ( "Invalid vote cast" )
44+
time.sleep(1)
45+
return 0
46+
47+
def print_results():
48+
global a_results
49+
# l_results= [('Harper', 8), ('Owen', 7), ('Aaliyah', 5), ('Connor', 4), ('Aaron', 1)]
50+
l_results=sorted(a_candidates.items(), key=lambda cand: cand[1], reverse=True)
51+
#print ( l_results )
52+
a_results=dict(l_results)
53+
#print ( a_results )
54+
55+
print ( s.RESET )
56+
57+
print ("The voting results are:")
58+
for cand in l_results:
59+
print ( f'{cand[0]:10} {cand[1]:>3}')
60+
61+
def display_candidates(l_cand):
62+
# clear the screen
63+
print (s.RESET)
64+
65+
print ("Your Candidates:")
66+
for i in range(len(l_cand)):
67+
print ( f'{i+1}) {l_cand[i]} ')
68+
69+
def create_pie():
70+
# create a pie chart
71+
mpl.pie(a_results.values(), labels=a_results.keys() , autopct='%1.1f%%')
72+
# add a title
73+
mpl.title('Talent Contest Votes')
74+
# create a legend
75+
legend_labels = [f"{k} ({v})" for k, v in a_results.items()]
76+
mpl.legend(legend_labels, title="Candidates", loc="lower right", bbox_to_anchor=(1, 0, 0.5, 1))
77+
mpl.subplots_adjust(right=0.7)
78+
79+
# show the plot
80+
mpl.show()
81+
82+
# actually do something.
83+
84+
init_candidates()
85+
while True:
86+
ret = get_vote()
87+
if ret == -1:
88+
break
89+
90+
print_results()
91+
92+
f_pie = input("Do you want a pie chart of the results [Y/N]? ").upper()
93+
if f_pie == "Y":
94+
create_pie()

0 commit comments

Comments
 (0)