Exercise Guide AdvancedPython Part 1
Exercise Guide AdvancedPython Part 1
com
GUIDE
Mentor:
✓ Tran Duy Thanh
✓ Email: thanhtd@uel.edu.vn
✓ Phone: 0987773061
✓ Blog for self-study: https://tranduythanh.com
-2021-
Page | 1
Tran Duy Thanh https://tranduythanh.com
1. AUTHOR
Tran Duy Thanh was received Bachelor of Computer Science from the
Industrial University of Ho Chi Minh City, and Bachelor of Business
Administration from the University of Economics in Ho Chi Minh City,
Vietnam.
Also, he received his M.S. degree in computer science from University of
Information Technology, Vietnam National University Ho Chi Minh City
(VNU-HCM), Vietnam.
He has become Full Lecturer in Faculty of Information Systems, University of
Economics and Law, Vietnam National University Ho Chi Minh City (VNU)-HCM,
Vietnam.
He is becoming Ph.D. Candidate of Department of Data Informatics, (National) Korea
Maritime and Ocean University, Busan 49112, Republic of Korea (South Korea).
His research interests are social network analysis, big data, AI and robotics.
He received Best Paper Award the 15th International Conference on Multimedia
Information Technology and Applications (MITA 2019)
He is co-author books: Basic mobile application development (ISBN: 978-604-73-5672-
0), Advanced mobile application development (ISBN: 978-604-73-5673-7), Basic
programming techniques (ISBN: 978-604-73-7187-7), Advanced programming techniques
(ISBN: 978-604-73-7493-9).
Page | 2
Tran Duy Thanh https://tranduythanh.com
2. BUY ME A COFFEE
Page | 3
Tran Duy Thanh https://tranduythanh.com
3. ACKNOWLEDGMENTS
❖ Sincere thanks to Professors at Department of Data Science, (National) Korea Maritime
and Ocean University, Busan 49112, Republic of Korea (South Korea). Exercises,
documents and teaching methods and problem approach I have consulted from Professors
in KMOU via Advanced Computer Engineering course, Introduction to Big Data
Optimization course… I did all the exercises myself and gave detailed instructions on how
to program, and applied the problem approach from the Professors, helping to increase the
programming thinking for learners.
❖ Also, thank you to my colleagues in the Data Science Lab 407 who have supported me a
lot in the past few days.
Page | 4
Tran Duy Thanh https://tranduythanh.com
4. WHO READS?
❖ All students have basic knowledge of Python. Or have taken this Python course,
https://unica.vn/?aff=11929(search Tran Duy Thanh) or click the link
https://unica.vn/lam-chu-python-trong-4-tuan?aff=11929
❖ Teachers want to access new teaching methods or use them as reference materials
when teaching
❖ Students who want to improve their knowledge of Python programming and new
programming thinking methods
❖ The company wants to train employees.
❖ And those who are interested in Python.
Page | 5
Tran Duy Thanh https://tranduythanh.com
TABLE OF CONTENTS
1. AUTHOR..................................................................................................................... 2
2. BUY ME A COFFEE .................................................................................................. 3
3. ACKNOWLEDGMENTS ........................................................................................... 4
4. WHO READS? ............................................................................................................ 5
5. Exercise 1 - Automatic coffee ordering machine ...................................................... 20
5.1. Learning Objectives ............................................................................................. 20
5.1.1. Basic learning objectives ........................................................................... 20
5.1.2. In-depth learning objectives ...................................................................... 20
5.1.3. Problem situation ....................................................................................... 20
5.2. Problem analysis .................................................................................................. 20
5.2.1. The role of the computer ............................................................................ 20
5.2.2. User ............................................................................................................ 20
5.2.3. Input ........................................................................................................... 20
5.2.4. Output ........................................................................................................ 20
5.2.5. Data ............................................................................................................ 21
5.3. Full algorithm skeleton ........................................................................................ 21
5.4. Algorithm efficiency ............................................................................................ 22
5.5. Programming ........................................................................................................ 22
5.5.1. Variables .................................................................................................... 22
5.5.2. input() ......................................................................................................... 22
5.5.3. Programming-the whole program .............................................................. 22
5.6. Testing and debugging ......................................................................................... 23
6. Exercise 2 - Automatic coffee ordering machine (improve) ..................................... 25
6.1. Problem situation ................................................................................................. 25
6.2. Programming-the whole program ........................................................................ 25
6.3. Testing and debugging ......................................................................................... 26
7. Exercise 3 - Number guessing game machine ........................................................... 29
7.1. Learning Objectives ............................................................................................. 29
7.1.1. Basic learning objectives ........................................................................... 29
Page | 6
Tran Duy Thanh https://tranduythanh.com
Page | 7
Tran Duy Thanh https://tranduythanh.com
Page | 8
Tran Duy Thanh https://tranduythanh.com
Page | 9
Tran Duy Thanh https://tranduythanh.com
Page | 10
Tran Duy Thanh https://tranduythanh.com
Page | 11
Tran Duy Thanh https://tranduythanh.com
Page | 12
Tran Duy Thanh https://tranduythanh.com
Page | 13
Tran Duy Thanh https://tranduythanh.com
Page | 14
Tran Duy Thanh https://tranduythanh.com
Page | 15
Tran Duy Thanh https://tranduythanh.com
Page | 16
Tran Duy Thanh https://tranduythanh.com
Page | 17
Tran Duy Thanh https://tranduythanh.com
Page | 18
Tran Duy Thanh https://tranduythanh.com
Page | 19
Tran Duy Thanh https://tranduythanh.com
Page | 20
Tran Duy Thanh https://tranduythanh.com
• Change
5.2.5. Data
• Integer constant representing the price of each cup of coffee
• Integer variable representing the number of each cup
• Integer variable representing the total amount
5.3. Full algorithm skeleton
start
Print out a list of drinks and prices that can be selected at the time
Wait for user input to know how many drinks for each drink
For each drink, the price of a drink * calculate the number of glasses and get
the sum
End
Page | 21
Tran Duy Thanh https://tranduythanh.com
sum = 0
sum += noA*2500
sum += noL*3000
Page | 22
Tran Duy Thanh https://tranduythanh.com
sum += noC*3000
Page | 23
Tran Duy Thanh https://tranduythanh.com
Page | 24
Tran Duy Thanh https://tranduythanh.com
Page | 25
Tran Duy Thanh https://tranduythanh.com
plistUserChoose.append(noQuantity)
# confirm continue or not
question=input("Do you want to choose another food?(yes/no):")
# if no, finish choosing the food/drink
if question=='no':
break
print("The list of ordered food/drink:")
sum = 0
print("Food Name\tPrice\tQuantity\tMoney")
#the loop to print all food/drink that user has chosen
for i in range(len(blistUserChoose)):
# get the food name from user's choosing
foodName=blist[blistUserChoose[i]-1]
# get quantity that user bought
quantity=plistUserChoose[i]
# get the unit price for food/drink
unitPrice=plist[blistUserChoose[i]-1]
# calculate money for each food/drink
money=quantity*unitPrice
# sum every food/drink
sum=sum+money
# print detail information for each item
print(foodName,"\t",unitPrice,"\t",quantity,"\t\t\t",money)
print("\tThe total amount is:\t",sum," money ")
money=0
while True:#loop for user to pay money
strmoney=input("Enter the amount to be paid >>")
if strmoney.isdigit()==False:
print(strmoney," is not valid, it should be a digit numer ")
else:
money=int(strmoney)
if money<0:
print(strmoney, " is not valid number, it should be positive")
else:
if money < sum:
print("Not enough money., you have to pay ",sum," money ")
else:
print("Paid is successfully!")
if money>sum:
print("Change is", money - sum, " money")
break
print("Thank you so much! see you again!")
Page | 26
Tran Duy Thanh https://tranduythanh.com
Program will ask user choose food/drink by enter the No [1-6], the number is automatic
changing when the list changes.
2-User can add the item by enter 1,2,3,4,5 or 6. If the value is not in the range, the
program will ask user enter value again
User can choose many food/drink, If user enters a not valid value, program will ask the
user enter value again. And when user finish choosing food/drink. The confirmation will
Page | 27
Tran Duy Thanh https://tranduythanh.com
be shown with 4 columns: Food Nam, Price, Quantity and money; And the total money is
displayed.
3-User enter the money: It must >= the total money. There are 3 cases in here:
-money paid <money→show error, not enough money
-money paid =money→show paid successfully
-money paid >money→show paid successfully and the change for user.
The picture above shows the input money that user has to pay. When user enters 10.000, it
is not enough money, the program will ask user input again. After that user enters 13000,
the program will show successfully and the change (500) for user.
I put my code in github, here is the link:
https://github.com/thanhtd32/advancedpython_part1/blob/main/Exercise2.py
Page | 28
Tran Duy Thanh https://tranduythanh.com
Page | 29
Tran Duy Thanh https://tranduythanh.com
start
It tells you the result of the comparison so you can predict the next number
End
Page | 30
Tran Duy Thanh https://tranduythanh.com
7.4. Programming
7.4.1. Variables
• palyerName: The name of the person playing the game
• guessNumber: Numbers generated as random numbers
• limit: Limit number of times
• count: Limit number of times
• playAgain: Whether the game continues
7.4.2. input()
The player's input-input() function
Generate random numbers-randint() function
#Necessary to use random numbers
import random
ansNumber=random.randint(1,30)
Page | 31
Tran Duy Thanh https://tranduythanh.com
ansNumber=random.randint(1,30)
print("Nice to meet you, "+ playerName +", I have a number between 1 and 30.
Guess it\n");
while playAgain=='YES':
print(limit,"You only have to guess 5 times")
while count<=limit and guessNumber!=ansNumber:
guessNumber=int(input("Please enter the guessed number->"))
if guessNumber==ansNumber:
break#If you get the correct answer, exit the inner while
statement.
elif guessNumber<ansNumber:
print("The guessed number is less than the number with the
computer.")
else:
print("The guessed number is greater than the number with the
computer.")
count=count+1
if guessNumber == ansNumber:
print(count, "I got it right once!! Congratulations\n")
if limit > 1:
limit = limit - 1
else:
print("The number of computers is ", ansNumber)
limit = limit + 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
-time 1: I guess 15
The guessed number is greater than the number with the computer. So, the computer
number is on the left 15.
Page | 32
Tran Duy Thanh https://tranduythanh.com
-time 2: I guess 7
The guessed number is less than the number with the computer. So, the computer number
is on the right 7.
So the time 3, I guess 11:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
-time 3: I guess 11
The guessed number is greater than the number with the computer. So, the computer
number is on the left 11
So, the time 4, I guess 9:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
-time 4: I guess 9
Page | 33
Tran Duy Thanh https://tranduythanh.com
Test case 2.
Not follow the binary algorithms
Page | 34
Tran Duy Thanh https://tranduythanh.com
Page | 35
Tran Duy Thanh https://tranduythanh.com
start
When the number of games is reached, the game ends and the number of hits
is reported
End
Page | 36
Tran Duy Thanh https://tranduythanh.com
8.4. Programming
8.4.1. Variables
• correctAns: Correct number
• wrongAns: Wrong count
• Count: Number of games
8.4.2. input()
import random and time modules for random number and time measurements
randint() to generate random multiplication tables
When the 5th stage comes out, a random number is generated.
import random #Import random module
import time#Import time-related modules
Page | 37
Tran Duy Thanh https://tranduythanh.com
count=count-1
print("%d X %d?" %(a,b))
startTime=time.time() #Measure reaction time
product=int(input())
endTime=time.time()
print("I answered in seconds %1.f "%(endTime-startTime))
Page | 38
Tran Duy Thanh https://tranduythanh.com
correctAns=0#Right count
wrongAns=0#Wrong count
#a list to check duplicate random number (for number a
duplicateListA=[]
#a list to check duplicate random number (for number b)
duplicateListB=[]
#45 second, if user answers over limitTime, the result is refused
limitTime=45
count=int(input("How many times should I do??"))
while count!=0:
#Generate numbers from 3rd to 9th
a=random.randint(3,9)
b=random.randint(3,9)
# If it is 5th stage, random number is generated again
if a==5 or b==5:
continue
isDuplicated=False
for i in range(len(duplicateListA)):#loop to check duplicate random number
if duplicateListA[i]==a and duplicateListB[i]==b:
isDuplicated=True
break
Page | 39
Tran Duy Thanh https://tranduythanh.com
Page | 40
Tran Duy Thanh https://tranduythanh.com
Test case 2.
Page | 41
Tran Duy Thanh https://tranduythanh.com
Page | 42
Tran Duy Thanh https://tranduythanh.com
10.2.5.Data
List of the books:
start
Propose a search method among book name, author name, and publisher name
If there is a book you are looking for, print out the information of the entire
book
End
Page | 43
Tran Duy Thanh https://tranduythanh.com
Page | 44
Tran Duy Thanh https://tranduythanh.com
elif choice=='2':
kwd="Author"
break
elif choice=='3':
kwd="Publisher"
break
else:
print("Invalid input.")
Page | 45
Tran Duy Thanh https://tranduythanh.com
else:
print("Invalid input.")
userin=input(kwd+">>>")
find=False
for onebook in mybooks:
if userin==onebook[kwd]:
print("Title:", onebook["Title"])
print("Author:", onebook["Author"])
print("Publisher:", onebook["Publisher"])
print("Price", onebook["Price"])
find=True
if find==False:
print("There are no books found..")
Page | 46
Tran Duy Thanh https://tranduythanh.com
Page | 47
Tran Duy Thanh https://tranduythanh.com
Page | 48
Tran Duy Thanh https://tranduythanh.com
#Description:
# These codes I improved from exercise 6o:
# 1. Book input
# 2. Search by book name
# 3. Search by author name
# 4. Search by publisher name
# 5. End
# with input a new book:
#title>>
#Author's name>>
#Publisher>>
#price>>
#Publication year>>
mybooks=[
{"Title": "Android App Development", "Author": "Thanh Tran",
Page | 49
Tran Duy Thanh https://tranduythanh.com
Page | 50
Tran Duy Thanh https://tranduythanh.com
When user enters a new book, Program will show and allow user enter attribute of the
book as above.
And asking user want to continue enter another book or not. If user says ‘Y’ the
program will continue entering, says ‘N’ the program will finish enter new book:
Page | 51
Tran Duy Thanh https://tranduythanh.com
When user press number 2, program will ask user enter the book title. If user enters
“BlockChain”, it will show the details of the book that it found out.
3-Search by author name (press number 3):
Page | 52
Tran Duy Thanh https://tranduythanh.com
User can enter the author’s name to find. If program cannot find the book, it will show
not found:
As picture above, user enters “VNU” publisher. Program will show the results that it
found out.
Page | 53
Tran Duy Thanh https://tranduythanh.com
5-End program! (press number 5). The program will stop and say thank you!:
Page | 54
Tran Duy Thanh https://tranduythanh.com
Page | 55
Tran Duy Thanh https://tranduythanh.com
start
If the alarm time is not displayed correctly, an error message is output and the
process is terminated.
Wait until the alarm time is reached (using the system function to resume the
execution failure during the difference between the current time and the alarm time)
End
Page | 56
Tran Duy Thanh https://tranduythanh.com
12.4. Programming
12.4.1.Variables
• alarm_time: Alarm time string set by the user.
• alarm_hms: To set the alarm time. minute. A list organized by dividing by seconds
12.4.2.Some utilities library
• String creation for the current time-time module's strftime() function
• Alarm time input-input() function
print("current time:",time.strftime("%H:%M:%S"))
alarm_time=input("Alarm time:")
• Alarm time input format check-String object method split()
alarm_time=input("Alarm time:")
alarm_hms=alarm_time.split(':')
if len(alarm_hms)==3 and 0<=int(alarm_hms[0]) \
and 0<=int(alarm_hms[1]) and 0<=int(alarm_hms[2]):
pass
else:
print("There is an error in the entered alarm time display.")
Hold program execution for a specified time –time module’s sleep() function
Beep() function of winsoud module to sound a specific frequency for a specified time
time.sleep(int(alarm_hms[0])* 60 * 60+ int(alarm_hms[1]) * 60 + int(alarm_hms[2]))
for i in range(1, 10):
winsound.Beep(i * 100, 200)
12.4.3.Programming-the whole program
The whole program is shown as below.
#Coder: Tran Duy Thanh
#Email: thanhtd@uel.edu.vn
#Phone: 0987773061
#Blog for self-study: https://duythanhcse.wordpress.com
#Facebook for solving coding problem: https://www.facebook.com/groups/communityuni
import time
import winsound
print("current time:",time.strftime("%H:%M:%S"))
alarm_time=input("Alarm time:")
alarm_hms=alarm_time.split(':')
if len(alarm_hms)==3 and 0<=int(alarm_hms[0]) \
and 0<=int(alarm_hms[1]) and 0<=int(alarm_hms[2]):
time.sleep(int(alarm_hms[0])* 60 * 60
+ int(alarm_hms[1]) * 60 + int(alarm_hms[2]))
for i in range(1, 10):
winsound.Beep(i * 100, 200)
else:
print("There is an error in the entered alarm time display.")
Page | 57
Tran Duy Thanh https://tranduythanh.com
Page | 58
Tran Duy Thanh https://tranduythanh.com
print("current time:",time.strftime("%H:%M:%S"))
alarm_time=input("Alarm time:")
alarm_hms=alarm_time.split(':')
Page | 59
Tran Duy Thanh https://tranduythanh.com
When time is over, program will show message “The time is over”. Because current time
is “16:45:58”, but the alarm is “6:45:20”
Case 3: User sets the absolute time but the time is not valid:
#hour: 0->23 #minute: 0->59 #second: 0->59
The alarm time is not correct, hour= 25, minute = 60.. Program will show message “Time
is not valid”
Case 4: User enters not correcting the format of time:
If user enters a not correcting the format of time, program will show “There is an error in
the entered alarm time display.”
I put my code in GitHub, here is the link:
https://github.com/thanhtd32/advancedpython_part1/blob/main/Exercise9.py
Page | 60
Tran Duy Thanh https://tranduythanh.com
Page | 61
Tran Duy Thanh https://tranduythanh.com
Page | 62
Tran Duy Thanh https://tranduythanh.com
start
End
14.5. Programming
14.5.1.Variables
• value: The final result of all calculations applied cumulatively up to the current point.
• Tokens: A list in which the components (operators and string representations of
operands) are stored in order.
• operator: String corresponding to the operator among the components of the
inputted each operation command
• operand: The value obtained by converting the operand string to real type among
the components of the input operation command
Page | 63
Tran Duy Thanh https://tranduythanh.com
14.5.2.Some explanations
• Accumulated variable initialization value=0
while True:
• Infinite repetition of work print("\nCurrent value:",value)
instructions until user request line=input("Enter the work command:")
• Output of values referenced by tokens=line.split()
if len(tokens)>0:
accumulated variables pass
• User action instruction analysis -
split() function
Page | 64
Tran Duy Thanh https://tranduythanh.com
operator=tokens[0]
if len(tokens) ==1:
if operator =='x':
break
print("Wrong work order!!!!")
elif len(tokens)==2:
operand=float(tokens[1])
if operator== '=':
value=operand
elif operator=='+':
value+=operand
elif operator=='*':
value*=operand
elif operator=='/' or operator=='%':
if operand!=0:
if operator=='/':
value/=operand
else:
value%=operand
else:
print("#Illegal operation command (divided by zero)!!)")
else:
print("Wrong work order!!")
else:
print("Wrong work order!!")
14.6. Testing and debugging
Run program.
Test case 1. Test the wrong work order.
Page | 65
Tran Duy Thanh https://tranduythanh.com
Test case 2.
Page | 66
Tran Duy Thanh https://tranduythanh.com
When the calculation command “+ 28 54 76” is applied, there are three data values that
can be referenced as cumulative variables.
It should be the same as when the calculation commands “+ 28”, “+ 54”, “+ 76” are
applied consecutively
value=0
while True:
print("\nCurrent value:",value)
line=input("Enter the work command:")
tokens=line.split()
if len(tokens)>0:
operator=tokens[0]
if len(tokens) ==1:
if operator =='x':
break
print("Wrong work order!!")
else:
listOperand=[]#a list to store all operands
isAllOperandValid=True
# loop to store all operands into listOperand
for i in range(1,len(tokens)):
if tokens[i].isdigit() == False:
isAllOperandValid=False
break
operand = float(tokens[i])
listOperand.append(operand)
if isAllOperandValid == True:
if operator== '=':
# get the last operand to asign for value
value=listOperand[len(listOperand)-1]
elif operator=='+':
# loop and plus all operand into value variable
for operand in listOperand:
value+=operand;
Page | 67
Tran Duy Thanh https://tranduythanh.com
elif operator=='-':
# loop and minus all operand into value variable
for operand in listOperand:
value-=operand;
elif operator=='*':
# loop and multiply all operand into value variable
for operand in listOperand:
value*= operand;
elif operator=='^':#loop and exponential all operand into value variable
for operand in listOperand:
value=pow(value,operand)
elif operator=='/' or operator=='%':
checkDividedZore=False
for operand in listOperand: # loop to check diveded by zero
if operand==0:
checkDividedZore=True
break
if checkDividedZore==False:
if operator=='/':
# loop and devide all operand into value variable
for operand in listOperand:
value /= operand;
else:
# loop and mod all operand into value variable
for operand in listOperand:
value %= operand;
else:
print("Illegal operation command (divided by zero)!!")
else:
print("Operator is not exist![=,+,-,*,/,%,^]")
else:
print("Some operand is not valid!")
else:
print("Invalid string input format")
Page | 68
Tran Duy Thanh https://tranduythanh.com
Page | 69
Tran Duy Thanh https://tranduythanh.com
The format is right, but the value of operand is not correct (it has x, a value)
I put my code in GitHub, here is the link:
https://github.com/thanhtd32/advancedpython_part1/blob/main/Exercise11.py
Page | 70
Tran Duy Thanh https://tranduythanh.com
Page | 71
Tran Duy Thanh https://tranduythanh.com
start
Initialize with the correct number and the wrong number variable 0
It tells you the number that was correct and the number that was wrong
End
Page | 72
Tran Duy Thanh https://tranduythanh.com
16.4. Programming
16.4.1.Variables
• correctAns: Number of guessed pattern reasoning.
• wrongAns: Number of hearing pattern inferences.
• Pattern1, pattern2, pattern3, pattern4, pattern5: Numeric pattern storage list
16.4.2.Some explanations
• Variable initialization
• Create numeric pattern
correctAns=0
wrongAns=0
#Various number patterns
pattern1=[2, 4, 6, 8]
pattern2=[13, 16, 19, 22]
pattern3=[2, 3, 5, 7, 11]
pattern4=[1, 1, 2, 3, 5, 8]
pattern5=[31, 28, 31, 30]
• Calling the pattern inference function
• Return correct and incorrect counts
pattern1=[2, 4, 6, 8]
pattern2=[13, 16, 19, 22]
pattern3=[2, 3, 5, 7, 11]
pattern4=[1, 1, 2, 3, 5, 8]
pattern5=[31, 28, 31, 30]
for i in range(len(pattern)-1):
print(pattern[i],end=" ")
if guessAns == pattern[len((pattern))-1]:
correctAns = correctAns +1
print("Well done. Congratulations")
Page | 73
Tran Duy Thanh https://tranduythanh.com
else:
wrongAns=wrongAns + 1
print("The correct answer is %d" %(pattern[len((pattern))-1]))
return correctAns,wrongAns
for i in range(len(pattern)-1):
print(pattern[i],end=" ")
if guessAns == pattern[len((pattern))-1]:
correctAns = correctAns +1
print("Well done. Congratulations")
else:
wrongAns=wrongAns + 1
print("The correct answer is %d" %(pattern[len((pattern))-1]))
return correctAns,wrongAns
correctAns=0
wrongAns=0
#Various number patterns
pattern1=[2, 4, 6, 8]
pattern2=[13, 16, 19, 22]
pattern3=[2, 3, 5, 7, 11]
pattern4=[1, 1, 2, 3, 5, 8]
pattern5=[31, 28, 31, 30]
Page | 74
Tran Duy Thanh https://tranduythanh.com
Test case 1.
Page | 75
Tran Duy Thanh https://tranduythanh.com
Page | 76
Tran Duy Thanh https://tranduythanh.com
Page | 77
Tran Duy Thanh https://tranduythanh.com
Each pattern, program will show a random position by? mark. User has to guess this
number. When finish 5 patterns, It will give the result with the total of correct and wrong
answer. You see 5 patterns, correct 3, wrong 2 in the first testing.
Besides, program will ask User want to re-play the quiz game by enter y letter, let’s test
second testing:
In the second testing, I just guessed right 5 value. In this case, the position (? Mark) is
random, it is difference with the first testing.
Now, the third testing, we continue to enter ‘y’ to re-play Quiz Game.
In this testing, I enter not valid value, such as: 4as, 5.5 →program will show error as above
(red rectangle). I use try... except to catch the user problem. User has to re enter valid value
to continue to another pattern.
Move to the fourth testing, in this case we will enter ‘n’ to stop the program:
Page | 78
Tran Duy Thanh https://tranduythanh.com
When user enter ‘n’, program will say “thank you so much for your playing the Quiz Game”
and after that I will stop.
def playQuiz(patterns) function: Because in this case, patterns is a global variable so we
can def playQuiz() without parameter, however this function with parameter is better than
without parameter because we can pass any pattern 2D array in here to test.
I put my code in GitHub, here is the link:
https://github.com/thanhtd32/advancedpython_part1/blob/main/Exercise13.py
Page | 79
Tran Duy Thanh https://tranduythanh.com
Page | 80
Tran Duy Thanh https://tranduythanh.com
start
Find the most frequent value and score range and print it out
Find the smallest frequency value and score and print it out
End
Page | 81
Tran Duy Thanh https://tranduythanh.com
18.4. Programming
18.4.1.Variables
• toiecScores: TOEIC score
• counters: frequency by score
• scoreBase: score base
• maxCount: largest frequency count
• minCount: least frequent
18.4.2.Some explanations
• Finding the frequency in units of 100 points
• Distribution from 0 point to 900 point
• Divided by 100 by operator //
def frequency(toiecScores):
counters=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for toiecScore in toiecScores:
counters[toiecScore//100]+=1
return counters
• The following function finds the most frequent
• The index of the list is multiplied by 100 to determine the TOEIC score.
def max_frequency(counters):
max=0
scoreBase=0
N=len(counters)
for i in range(N):
if max<counters[i]:
max=counters[i]
scoreBase=i * 100
return scoreBase,max
• The following function finds the smallest frequency
• Initialize the min value to 11
def min_frequency(counters):
scoreBase=0
N = len(counters)
min=11
for i in range(N):
if counters[i] !=0 and min >counters[i]:
scoreBase = i * 100
min = counters[i]
return scoreBase, min
• TOEIC score is given as a list
• Call frequency() function to find frequency
• Find the largest frequency and score
Page | 82
Tran Duy Thanh https://tranduythanh.com
counters =frequency(toiecScores)
scoreBase,maxCount=max_frequency(counters)
scoreBase,minCount=min_frequency(counters)
def max_frequency(counters):
max=0
scoreBase=0
N=len(counters)
for i in range(N):
if max<counters[i]:
max=counters[i]
scoreBase=i * 100
return scoreBase,max
def min_frequency(counters):
scoreBase=0
N = len(counters)
min=11
for i in range(N):
if counters[i] !=0 and min >counters[i]:
scoreBase = i * 100
min = counters[i]
return scoreBase, min
toiecScores=[510,630,750,780,620,805,930,650,840,670]
counters =frequency(toiecScores)
scoreBase,maxCount=max_frequency(counters)
Page | 83
Tran Duy Thanh https://tranduythanh.com
scoreBase,minCount=min_frequency(counters)
Page | 84
Tran Duy Thanh https://tranduythanh.com
Page | 85
Tran Duy Thanh https://tranduythanh.com
#This function use to count the frequency of each Score that Student acquired
def countFrequency(toiecScores,toiecScoreCheck):
count=0
for toiecScore in toiecScores:
if toiecScoreCheck==toiecScore:
count = count +1
return count
#this function print all score of Student and calculate the Frequency and Rate:
def frequencyIndividual(toiecReduceAndSortScores):
print("Score\tFre\tFre. Rate")
lenOfToiecScores=len(toiecScores)
for toiecScoreCheck in toiecReduceAndSortScores:
fre=countFrequency(toiecScores,toiecScoreCheck)
rate=round((fre/lenOfToiecScores)*100,2)
print (toiecScoreCheck,"\t",fre,'\t',rate,"%")
#this function use to show the Frequency and the Rate with complex range:
def frequencyClassified(toiecScores):
counters =frequency(toiecScores)
print("\tScore\t\tFre\t\tFre. Rate")
for i in range(len(counters)):
if counters[i]!=0:
baseScore=i*100
rate=round((counters[i]/len(toiecScores))*100,2)
rightRange=baseScore+99
if rightRange >990 :
rightRange=990
print("[",baseScore,"-",rightRange,"]","\t",counters[i],"\t\t",rate,"%")
#this function get all max frequency that the same value
def max_frequency_all(toiecScores):
counters = frequency(toiecScores)
maxFrequency=findMaxValue(counters)
list_scoreBase=[]#the list to store all scorebase that the same max frequency
N=len(counters)
for i in range(N):
if maxFrequency==counters[i]:#if the same max value, we store in to the list
list_scoreBase.append(i * 100)
return list_scoreBase,maxFrequency
#this function gets the value: list_scoreBase,maxFrequency from max_frequency_all function and print data out
def printAllMaxFrequency():
list_scoreBase,maxFrequency=max_frequency_all(toiecScores)
print("Max Frequency = ",maxFrequency)
print("The range of the Scores base have the same max frequency:")
print("Score\tFre\t\tFre. Rate")
Page | 86
Tran Duy Thanh https://tranduythanh.com
#this function get all min frequency that the same value
def min_frequency_all(toiecScores):
counters = frequency(toiecScores)
minFrequency=findMinValue(counters)
list_scoreBase=[]#the list to store all scorebase that the same min frequency
N=len(counters)
for i in range(N):
if minFrequency==counters[i]:#if the same max value, we store in to the list
list_scoreBase.append(i * 100)
return list_scoreBase,minFrequency
#this function gets the value: list_scoreBase,minFrequency from min_frequency_all function and print data out
def printAllMinFrequency():
list_scoreBase,minFrequency=min_frequency_all(toiecScores)
print("Min Frequency = ",minFrequency)
print("The range of the Scores base have the same min frequency:")
print("Score\tFre\t\tFre. Rate")
rate = round((minFrequency / len(toiecScores)) * 100, 2)
for baseScore in list_scoreBase:
print(baseScore, "\t", minFrequency, "\t\t", rate, "%")
#this function use to calculate the Average Toiec Score that Student Acquired
def averageOfToiecScore(toiecScores):
avg=sum(toiecScores)/len(toiecScores)
return int(round(avg,0))
toiecReduceAndSortScores=reduceAndSortScores(toiecScores)
frequencyIndividual(toiecReduceAndSortScores)
# 2.List all Score with range comple for Student acquired: Base Score-Frequency- Frequency rate
frequencyClassified(toiecScores)
Page | 87
Tran Duy Thanh https://tranduythanh.com
You can see all data is printed with 3 columns: Score, Frequency and Frequency Rate.
Program calculate data and print all, we can easily watch the data. However, when the
score has many values, it is difficult to statistical. In this case, please go to test case 2.
Case 2: List all Score with range complex for Student acquired: Base Score-Frequency-
Frequency rate:
frequencyClassified(toiecScores)
Page | 88
Tran Duy Thanh https://tranduythanh.com
The result is: Scores is grouped by the base score; program will show frequency and the
rate foreach base score. That is easy to statistical.
Case 3: See all the scores with the same max frequency:
printAllMaxFrequency()
In case 2, you see base scores [700-799] and [900-990] have the same max frequency. So
in case 3, the program will show these base scores.
Case 4: See all the scores with the same min frequency:
printAllMinFrequency ()
In case 2, you see base scores [100-199] and [400-499] have the same min frequency. So
in case 4, the program will show these base scores.
Case 5: A function to find the average of the TOEIC students acquired.:
print("Average Toeic Score that Student acquired=",averageOfToiecScore(toiecScores))
In case 5, the program will calculate the average score and round up to integer value and
print out.
I put my code in GitHub, here is the link:
https://github.com/thanhtd32/advancedpython_part1/blob/main/Exercise15.py
Page | 89
Tran Duy Thanh https://tranduythanh.com
Page | 90
Tran Duy Thanh https://tranduythanh.com
• The Republic of Korea uses UTC+9, the time zone of which 9 hours are added to
Coordinated Universal Time (UTC), and the time is called Pacific Standard Time
(PST). Pacific Daylight-Saving Time (PDT) is used during summer time
• In the summer time period, there is a time difference of -16 hours, and in other
periods, an additional hour is added.
• Since the program only considers countries with a later time than Korea, if the time
becomes negative when the time is subtracted, it is considered that the correction
should be made in order of day, month, and year
20.3. Full algorithm skeleton
start
Understand how the year, month, day, and time change due to the time
difference, and define a function to find the leap year in the changing month.
At this time, because the travel period is summer, consider summer time.
Calculate the time difference and define the procedure to change if the day,
month, and year must be changed
Calculate and print the time difference between the two countries
End
Page | 91
Tran Duy Thanh https://tranduythanh.com
20.4. Programming
20.4.1.Variables
• yy: The year in which the parallax was applied as a parameter of the function
is_leap_year()
• yy, mm, dd, hh, min: The current year, month, hour, and minute of Korea are
displayed as local variables of the function jetlag().
• today: Current time in Korea
• date: A string containing the current date and time in California as a local variable
of the function jetlag()
• gap: The time difference between the two countries, negative numbers are the time
difference between the countries that are later in time than Korea.
20.4.2.Some explanations
module datetime: import datetime
datetime.datetime.now(): Python's datetime module provides a datetime class that stores
both date and time information. The method now() of the Datetime class gives the current
time. The Datetime class contains properties such as year (year), month (month), day (day),
hour (hour), minute (minute), second (second), and microsecond (multiple seconds)
current time: Displays the current time as year/month/date/hour:minute.
• today=datetime.datetime.now()
• today.strftime(‘%Y%m%d %H:%M’)
Function to find leap year is_leap_year():
The function is_leap_year() that finds the number of years tells us that the value of the
parameter yy is divided by 400 and is not divided by 400 or is not divided by 100, but is
divided by 4, which means that it is a leap year.
def is_leap_year(yy):
return yy % 400 == 0 or (yy%100) and yy%4==0
Function jetlag()
• The current country's year, month, day, hour, minute, and time difference are
taken as parameters and the time of the region (California) is calculated.
• Time adjustment
• Adjustment of the day
Page | 92
Tran Duy Thanh https://tranduythanh.com
def jetlag(yy, mm, dd, hh, mi, gap): #Function to calculate parallax
hh +=gap #Korea and California time difference
if hh < 0 : #If the time is negative, adjust the date
dd = dd - 1
hh += 24
if dd ==0: #When the adjusted date reaches 0, the month is adjusted.
mm = mm-1
if mm ==0: #If the adjusted month is 0, adjust the year
mm = 12
yy -= 1
if mm in [4, 6, 9, 11]: #Calculate the last day of the adjusted month
dd = 30 #30 days last
elif mm in [1,3,5,7,8,10,12]:#The last day is the 31st
dd=31
else: #The leap month needs to be calculated
if is_leap_year(yy): #Leap year
dd = 29
else:
dd =28 #If it's not a leap month
date= "%d/%d/%d %d:%d" % (yy,mm,dd, hh,mi)
return date
def jetlag(yy, mm, dd, hh, mi, gap): #Function to calculate parallax
hh +=gap #Korea and California time difference
if hh < 0 : #If the time is negative, adjust the date
dd = dd - 1
hh += 24
if dd ==0: #When the adjusted date reaches 0, the month is adjusted.
mm = mm-1
if mm ==0: #If the adjusted month is 0, adjust the year
mm = 12
yy -= 1
if mm in [4, 6, 9, 11]: #Calculate the last day of the adjusted month
dd = 30 #30 days last
elif mm in [1,3,5,7,8,10,12]:#The last day is the 31st
dd=31
else: #The leap month needs to be calculated
if is_leap_year(yy): #Leap year
dd = 29
else:
Page | 93
Tran Duy Thanh https://tranduythanh.com
date=jetlag(today.year,today.month,today.day,today.hour,today.minute,gap)
print("California Current Date and Time:",date)
Page | 94
Tran Duy Thanh https://tranduythanh.com
Page | 95
Tran Duy Thanh https://tranduythanh.com
Countries with GMT timezone is saved in excel, we use pandas library to read.
The whole program is shown as below.
#Coder: Tran Duy Thanh
#Email: thanhtd@uel.edu.vn
#Phone: 0987773061
#Blog for self-study: https://duythanhcse.wordpress.com
#Facebook for solving coding problem: https://www.facebook.com/groups/communityuni
#Description:
#These codes I improved from Exercise 16.
#1.calculate the time difference for each country by saving the time difference of
# different countries in a list and selecting a country
#2.save all country over the world into Excel to calculate the time difference for each country
#3.Make a menu for user choosing
import datetime
import pandas as pd
#some default country and jetlag
jetlagCountries = [-16, -8, 2, -2, -2, -1, -13, 1, -7]
countries = ["San Francisco", "London", "Sydney", "Jakarta", "Viet Nam", "China", "New York",
"Vladivostok","Amsterdam"]
#for loading excel data (for all countries over the world)
#in this case I use international GMT time to calculate different time over the World with Korea
#all data will be read from EXCEL file with pandas library
jetlagMoreCountries = []
morecountries = []
korea_gmt=9
Page | 96
Tran Duy Thanh https://tranduythanh.com
def printCountries(countries,isSmall=True):
print("Countries:")
for i in range(len(countries)):
if isSmall:
print(f'{i+1}.{countries[i]:<20}',end="")
else:
print(f'{i + 1}.{countries[i]:<50}', end="")
if isSmall and (i+1) % 3 ==0:
print()
elif isSmall==False and ((i+1) % 4) ==0:
print()
print()
#this function use to show the current date for country by index
def showDateTimeForCountry(country,gap):
today = datetime.datetime.now()
print("You choose country:" + country)
print("Current date and time in Korea:", today.strftime("%Y/%m/%d %H:%M"))
date = jetlag(today.year, today.month, today.day, today.hour, today.minute, gap)
print(country, "Current Date and Time:", date)
#this function will show list of country over the world or list of default,
#user can see and choose easily
#function will find the gap and country to calculate the different time
#isLittle=True, mean: countries,jetlagCountries is from default
#isLittle=False, mean: countries and GMT time is all over the World (Excel file)
def showDiffrentTimeCountries(countries,jetlagCountries,isLittle=True):
while True:#loop to re-enter many countries to test
printCountries(countries,isLittle) #print all countries, user can choose easily
country=input("Please enter [index] or [name of country] or [exit] to break function:")
isOkToShow=False
index=-1
if country.isdigit()==True: # if use find country by index
index=int(country)
if index>0 and index <= len(countries):
country = countries[index - 1]
if isLittle ==True:
gap = jetlagCountries[index-1]
else:
gmtCountry = jetlagCountries[index - 1]
gap = korea_gmt - gmtCountry
isOkToShow=True
elif country.lower()=="exit":#if exit
break
else:#if user find country by name
country = country.lower()
for i in range(len(countries)):
if (countries[i].lower() == country):
index = i
break
if index>=0:
country = countries[index]
if isLittle ==True:
gap = jetlagCountries[index]
else:
gmtCountry = jetlagCountries[index]
gap = korea_gmt - gmtCountry
Page | 97
Tran Duy Thanh https://tranduythanh.com
isOkToShow=True
if isOkToShow==True:#is ok to show date for country
if isLittle==False:
gap = gap *-1;
showDateTimeForCountry(country, gap)
else:
print("The index or country name [%s] is not exit!"%country)
#function to read all countries from Excel
#in this case, gap must be recalcuted before GMT is be used
def showMoreCountries():
if len(morecountries)==0:#the first time we load data from Excel
data = pd.read_excel(r'data_exercise17/Timezone-countries.xlsx')#read data
df = pd.DataFrame(data, columns=['Country- City','GMT TimeZone'])
for i in range(len(df.index)-1):
morecountries.append(df.iloc[i]["Country- City"])
jetlagMoreCountries.append(float(df.iloc[i]["GMT TimeZone"]))
#Reuse showDiffrentTimeCountries
showDiffrentTimeCountries(morecountries,jetlagMoreCountries,False)
#this function is main function
#give 3 options for user
def doDiffrentTimeCountry():
while True:
print("1.Little Countries")#do with default countries in the list in memory
print("2.More Countries")#do with all country over the world in Excel
print("3.Exit application")#exit application
choice=input("Please enter your choice:")
if choice=="1":
showDiffrentTimeCountries(countries,jetlagCountries,True)
elif choice=="2":
showMoreCountries()
elif choice=="3":
print("Thank you for using the app!")
exit()
else:
print("Please choose correcting number")
#call main function to use the application
doDiffrentTimeCountry()
All countries in the default list will be showed, use can enter index (1→n) or and the
[name of country] or exit to break the function.
Test case 2: Now we press 5 and enter:
Datetime of Vietnam will be showed and comparing with the Korea time
Test case 3: We can find by country name (press VietName instead 5):
Datetime of Vietnam will be showed and comparing with the Korea time, about 2 hours
Test case 4:
The time in Vietnam is after Korea, now We just test Sydney:
Page | 99
Tran Duy Thanh https://tranduythanh.com
Program can not find the country and show “The index or country name [cambodia] is
not exit!”
Test case 6: User can enter “exit” to break the function little countries, I will be backed
to the main menu list:
Test case 7: User choose 2 to use “More countries”, this function will read data of all
countries over the World from Excel file by pandas library:
Page | 100
Tran Duy Thanh https://tranduythanh.com
The results:
All the test case in mode 2 “More Countries” are the same mode 1 “Little Countries”.
Now let’s take a look some test case:
Test case 8: I enter 191 (it means Vietnam)
The datetime is showed about. Time of Vietnam is after Korean time about 2 hours
Page | 101
Tran Duy Thanh https://tranduythanh.com
Maybe some data I collected in the excel file is not 100% exactly, but the data format is
GMT, user can easily to choose and see the time for each country. Sorry about that.
Page | 102
Tran Duy Thanh https://tranduythanh.com
Page | 103
Tran Duy Thanh https://tranduythanh.com
start
Write a function that can get the student class attribute value
End
Page | 104
Tran Duy Thanh https://tranduythanh.com
22.4. Programming
22.4.1.Variables
• name: Student name
• midScore, finalScore, projectScore: Student score
• student1: Student object.
22.4.2.Some explanations
Student class definition
Initialization using __init__()
Write method (function) to inform attribute value
Write sum and average method (function)
#Class definition
class Student:
def __init__(self,name, midScore, finalScore, projectScore):
self.name=name
self.midScore=midScore
self.finalScore=finalScore
self.projectScore=projectScore
def get_name(self):
return self.name
def get_sum(self):
return self.sum
def get_avg(self):
return self.avg
def calculate(self):
self.sum=self.midScore+ self.finalScore + self.projectScore
self.avg=self.sum/3
Students' name, midterm, and final exams are entered.
Create object student1
name=input("Enter your name:")
midScore=int(input("Enter midterm grades:"))
finalScore=int(input("Enter final exam grades:"))
projectScore=int(input("Enter assignment grade"))
#Object creation
student1=Student(name,midScore,finalScore,projectScore)
Call calculate() using the created object student1
Define get() method and set() to access or change property data
Page | 105
Tran Duy Thanh https://tranduythanh.com
student1.calculate()
print("Student name=",student1.get_name())
print("Sum=",student1.get_sum())
print("Average=",student1.get_avg())
#Class definition
class Student:
def __init__(self,name, midScore, finalScore, projectScore):
self.name=name
self.midScore=midScore
self.finalScore=finalScore
self.projectScore=projectScore
def get_name(self):
return self.name
def get_sum(self):
return self.sum
def get_avg(self):
return self.avg
def calculate(self):
self.sum=self.midScore+ self.finalScore + self.projectScore
self.avg=self.sum/3
#Object creation
student1=Student(name,midScore,finalScore,projectScore)
#Sum and average calculation method call
student1.calculate()
print("Student name=",student1.get_name())
print("Sum=",student1.get_sum())
print("Average=",student1.get_avg())
Page | 106
Tran Duy Thanh https://tranduythanh.com
Page | 107
Tran Duy Thanh https://tranduythanh.com
#Description:
#These codes I improved from Exercise 18.
# 1.Create an enum to calculate Ranking for Student
# 2.Create getRanking method to calculate ranking for Student
# 3.Create printInfor and printInforWithTitle to print information for Student
# 4.make a loop with menu to test some test case for Student
# 4.1.make a new Student
# 4.2.make a list to store and print all Student that entered
# 4.3.Find a student
# 4.4.Exit the application
from enum import Enum
#enum for ranking
#name is A,B,C,D, F level
#value is description for the level
class Ranking(Enum):
A = "90->100"
B = "80->89"
C = "70->79"
D = "60->69"
F = "<60"
#Class definition
class Student:
def __init__(self,name, midScore, finalScore, projectScore):
self.name=name
Page | 108
Tran Duy Thanh https://tranduythanh.com
self.midScore=midScore
self.finalScore=finalScore
self.projectScore=projectScore
def get_name(self):
return self.name
def get_sum(self):
return self.sum
def get_avg(self):
return self.avg
def calculate(self):
self.sum=self.midScore+ self.finalScore + self.projectScore
self.avg=round(self.sum/3)
def getRanking(self):
if self.avg >=90:
self.ranking=Ranking.A
elif self.avg>=80:
self.ranking = Ranking.B
elif self.avg>=70:
self.ranking=Ranking.C
elif self.avg>=60:
self.ranking = Ranking.D
else:
self.ranking = Ranking.F
return self.ranking
# print information only
def printInfor(self):
print(f'{self.get_name():<15}{self.get_sum():<10}{self.get_avg():<10}'
f'{self.getRanking().name:<10}{self.getRanking().value:<10}')
# print information with title
def printInforWithTitle(self):
print(f'{"Name":<15}{"Sum":<10}{"Avg":<10}{"Rank":<10}{"(Note)":<10}')
self.printInfor()
listOfStudent=[]#list to save student
while True:#loop to test student
print("1.Enter a new grade Student")
print("2.Print All grade Student")
print("3.Find a Student")
print("4.Exit")
choose=input("Please choose[1..4]>>")
if choose=="1":
name=input("Student Name:")
#Enter midterm grades
midScore=int(input("Enter midterm grades:"))
#Enter final exam grades
finalScore=int(input("Enter final exam grades:"))
#Enter assignment grade
projectScore=int(input("Enter assignment grade:"))
# Object creation
stObj=Student(name,midScore,finalScore,projectScore)
#Sum and average calculation method call
stObj.calculate()
print("Student infor that you entered:")
stObj.printInforWithTitle()
listOfStudent.append(stObj)
elif choose =="2":
Page | 109
Tran Duy Thanh https://tranduythanh.com
print("List Of Students:")
print(f'{"Name":<15}{"Sum":<10}{"Avg":<10}{"Rank":<10}{"(Note)":<10}')
for stObj in listOfStudent:
stObj.printInfor()
elif choose =="3":
name = input("Enter Student Name you want to find:")
foundObj=None
for stObj in listOfStudent:
if stObj.get_name().lower()==name.lower():
foundObj=stObj
break
if foundObj==None:
print("Can not find student name ",name)
else:
foundObj.printInforWithTitle()
elif choose =="4":
print("Thank you for your using the app")
break
Input
Output
Page | 110
Tran Duy Thanh https://tranduythanh.com
In test case 1, we enter a new Student as above. When finishing input the data, information
for this Student will be showed.
Test case 2: Enter a new more Grade Student with D level, press 1
Input
Output
Test case 3: Enter a new more Grade Student with C level, press 1
Input
Output
Test case 4: Enter a new more Grade Student with B level, press 1
Input
Output
Test case 5: Enter a new more Grade Student with F level, press 1
Input
Output
Page | 111
Tran Duy Thanh https://tranduythanh.com
Output
Input
Result
Page | 112
Tran Duy Thanh https://tranduythanh.com
Page | 113
Tran Duy Thanh https://tranduythanh.com
Page | 114
Tran Duy Thanh https://tranduythanh.com
start
Class basket Think about what kind of performances there will be. Defines the
add() method that holds the item, delete() that deletes the item that was held,
and the printitems() method that prints the item in the shopping cart.
Let's print out the contents of the shopping cart when we put everything in it.
End
Page | 115
Tran Duy Thanh https://tranduythanh.com
24.4. Programming
24.4.1.Variables
• Basket: class name
• Id,total, noitems: properties of class basket
• This indicates whose shopping cart (id) is, how much is the total amount (total), and
how many items (noitems) are contained in it.
• Items, prices, quantity: properties of class Baset
• Each item's name (items), unit price (prices), and quantity (quantity) are displayed.
It is defined as a list because it can contain multiple items for the same item.
• cjBasket, jsBasket: object variables of class basket
24.4.2.Some explanations
Constructor definition of class Basket:
class Basket:
def __init__(self,id):
self.id=id
self.items=[]
self.prices=[]
self.quantity=[]
self.total=0
self.noitems=0
Define add method of class Basket
The method add takes the name of the item, the price, how many items to buy, item,
price, and qty as parameters and adds each as an attribute variable value of class Basket.
def add(self,item,price,qty):
self.items.append(item)
self.prices.append(price)
self.quantity.append(qty)
self.total +=price *qty
self.noitems += 1
Define delete method of class Basket
def delete(self,item,qty):
for i in range(self.noitems):
if item == self.items[i]:
self.quantity[i]-=qty
self.total -=self.prices[i]*qty
if self.quantity[i]==0:
self.noitems -=1
del self.items[i]
del self.quantity[i]
del self.prices[i]
break
Page | 116
Tran Duy Thanh https://tranduythanh.com
When the user designates an item to be deleted, it is deducted from the total amount using
the quantity and unit price, and after reducing the number of items by one, when the number
of items reaches 0, they are deleted from the shopping cart.
Create 2 Basket class instances
cjBasket =Basket("Thanh Tran")
jsBasket =Basket("Pham Dieu")
cjBasket.add("banana",5000,2)
cjBasket.add("Milk",3000,1)
jsBasket.add("Ramen",5900,1)
jsBasket.add("Coffee",10000,2)
cjBasket.printitems()
jsBasket.printitems()
Delete 1 bottle of milk from cjBasket and 1 box of coffee mix from jsBasket.
cjBasket.delete("Milk",1)
cjBasket.printitems()
jsBasket.delete("Coffee Mix",1)
jsBasket.printitems()
Printitems() method that prints the contents of the shopping cart
def printitems(self):
print(self.id,"shopping cart")
for i in range(self.noitems):
print(self.items[i],self.prices[i],self.quantity[i])
print("** total = ",self.total, ", noitems= ",self.noitems)
Page | 117
Tran Duy Thanh https://tranduythanh.com
for i in range(self.noitems):
if item == self.items[i]:
self.quantity[i]-=qty
self.total -=self.prices[i]*qty
if self.quantity[i]==0:
self.noitems -=1
del self.items[i]
del self.quantity[i]
del self.prices[i]
break
def printitems(self):
print(self.id,"shopping cart")
for i in range(self.noitems):
print(self.items[i],self.prices[i],self.quantity[i])
print("** total = ",self.total, ", noitems= ",self.noitems)
Page | 118
Tran Duy Thanh https://tranduythanh.com
#Description:
#These codes I improved from Exercise 20.
#1. improve add method when item is the same name->update quantity and total
#2. improve delete method->check quantity is valid or not, return True/False
#3. improve printitems method -> text align to print
#4. call Baseket object and test all method of Baset
class Basket:
def __init__(self,id):
self.id=id
self.items=[]
self.prices=[]
self.quantity=[]
self.total=0
self.noitems=0
def add(self,item,price,qty):
#if item is the same name
if self.items.__contains__(item) ==True:
position=self.items.index(item)
totalPrevious=self.prices[position]*self.quantity[position]
self.prices[position]=price
#update quantity for item
self.quantity[position]=qty+self.quantity[position]
#remove total of previous
self.total=self.total-totalPrevious
Page | 119
Tran Duy Thanh https://tranduythanh.com
Page | 120
Tran Duy Thanh https://tranduythanh.com
cjBasket.printitems()
else:
print("delete 1 quanlity of milk is NOT successful")
if cjBasket.delete("milk",2)==True:
print("delete 2 quanlity of milk is successful")
cjBasket.printitems()
else:
print("delete 2 quanlity of milk is NOT successful")
if cjBasket.delete("milk",2)==True:
print("delete 2 quanlity of milk is successful")
cjBasket.printitems()
else:
print("delete 2 quanlity of milk is NOT successful")
Page | 121
Tran Duy Thanh https://tranduythanh.com
Quantity of banana is
updated to 5 (previous is 2)
Test case 3: Run code and call add method with item same name “apple”:
#call add function with the same item (apple already input)
cjBasket.add("apple",3000,3)
#call print items function
cjBasket.printitems()
The result:
Quantity of banana is
updated to 4 (previous is 1)
Test case 2, 3. Quantity is updated for item. And the total is also updated
Test case 4: Run code and call delete method with item name “milk” and quantity is 1:
#test delete function:
if cjBasket.delete("milk",1)==True:
print("delete 1 quanlity of milk is successful")
cjBasket.printitems()
else:
print("delete 1 quanlity of milk is NOT successful")
The result:
Page | 122
Tran Duy Thanh https://tranduythanh.com
Test case 5: Run code and continue call delete method with item name “milk” and quantity
is 2:
if cjBasket.delete("milk",2)==True:
print("delete 2 quanlity of milk is successful")
cjBasket.printitems()
else:
print("delete 2 quanlity of milk is NOT successful")
The result:
In this test case, all quantity of milk is removed, so the Milk item is also removed from
the list.
Test case 6: Run code and continue call delete method with item name “milk” and quantity
is 2:
if cjBasket.delete("milk",2)==True:
print("delete 2 quanlity of milk is successful")
cjBasket.printitems()
else:
print("delete 2 quanlity of milk is NOT successful")
The result:
Because milk Item is removed from the list, so we cannot remove it anymore
I put my code in GitHub, here is the link:
https://github.com/thanhtd32/advancedpython_part1/blob/main/Exercise21.py
Page | 123
Tran Duy Thanh https://tranduythanh.com
Page | 124
Tran Duy Thanh https://tranduythanh.com
26.2.2.User
• Whenever the main story of the random round question-and-answer begins, the
words to memorize are printed out in the corresponding cycle.
• When the cycle of random question-and-answer starts, it supports the user to decide
how many times to repeat the question-and-answer cycle.
• Guidance on correct answers when incorrect answers are given to questions about
words.
26.2.3.Input
• Spelling and meaning of words to be learned by memorization
• The answer to each question (the meaning of a word) (the spelling of the word)
• Number of rounds for each random Q&A cycle
26.2.4.Output
• Input request message for words to be registered
• A list of words to cycle through
• Input request message for the number of question-and-answer rounds
• Questions about the target word for memorization learning
• Whether or not the answer to the question is correct
• A message indicating that memorization learning has ended
26.2.5.Data
• Persistent data: spelling and meaning of registered words
• Data updated by random traversal question-and-answer cycle: a traversal set, a set
of words with incorrect answers more than once
26.3. Algorithm Efficiency
• Supports the user to set the cycle (number of question-and-answer rounds) to the
most suitable value for himself/herself
• As an efficient implementation method for random traversal question-and-answer,
the traversal set is composed of a list, the words on the list are randomly rearranged,
and then the question-and-answer process is used in turn.
Page | 125
Tran Duy Thanh https://tranduythanh.com
start
After creating a vocabulary book that will be used for randomly looping Q&A
learning, register the entered words and initialize the iteration set to include
all the words
Using the vocabulary, repeat the following operations until all words
in the traversal set have been removed.
End
Page | 126
Tran Duy Thanh https://tranduythanh.com
26.5. Programming
26.5.1.Variables
• wdict: A dictionary of input words to learn by memorization
• voc: Vocabulary object used for managing and learning registered words
• nQNA: The number of Q&As entered by the user to set the random Q&A period.
• meaning: meaning of the word being questioned and answered
• answer: Spell the word entered by the user as an answer to the question.
26.5.2.Some explanations
• Constructor of vocabulary registration management/learning support class
Vocabulary
o self.words : a copy of the dictionary object where the registered words are
stored
o self.untrained : A set of words that are incorrect at least once during a random
iterative question-and-answer cycle
• Vocabulary's method renew() : Prepares a random question-and-answer cycle of a
new cycle
o self.target : Selects as the learning target only the words that are wrong at
least once among the iterative questions and answers of the previous cycle
o Random relocation of learning words for random traversal Q&A : shuffle()
function of random module
def __init__(self,wdict):
self.words=wdict.copy()
self.untrained=set(self.words)
self.renew()
def renew(self):
self.target=list(self.untrained)
random.shuffle(self.target)
self.untrained=set() #empty set
• Vocabulary's method check() : Checks the noon of the answer given by the user
o Arguments: the key suggested as a question (the meaning of the word) and
the value entered as an answer (the spelling of the word)
o If the argument key is not registered in the registered word dictionary
self.words, a None object is returned.
o If the word value passed as an argument is the correct answer, an Ellipsis
object is returned. If the answer is incorrect, it is added to the set
self.untrained.
Page | 127
Tran Duy Thanh https://tranduythanh.com
voc=Vocabulary(wdict)
• Iterative Q&A processing in one cycle: Repeat Q&A of all words as much as the
value referenced by the variable nQNA
o At the beginning of each traversal, the Vocabulary object's method shuffle()
is called to randomly rearrange the words to be answered.
o When the iteration question and answer of one cycle is over, the method of
Vocabulary object is called renew() to update the iteration set.
for index in range(0,nQNA):
voc.shuffle()
for meaning in voc.target_keys():
answer=input("What word means '"+meaning+"'?")
word=voc.check(meaning,answer)
if word is Ellipsis:
print("is the correct answer")
else:
print("The correct answer is'"+word+"'")
voc.renew()
Page | 128
Tran Duy Thanh https://tranduythanh.com
import random
class Vocabulary:
def __init__(self,wdict):
self.words=wdict.copy()
self.untrained=set(self.words)
self.renew()
def renew(self):
self.target=list(self.untrained)
random.shuffle(self.target)
self.untrained=set() #empty set
def target_keys(self):
return self.target
def shuffle(self):
random.shuffle(self.target)
voc=Vocabulary(wdict)
while len(voc.target_keys())>0:
print("\nwords to memorize:",voc.target_keys())
nQNA=int(input("Number of questions and answers per word:"))
print()
for index in range(0,nQNA):
voc.shuffle()
for meaning in voc.target_keys():
answer=input("What word means '"+meaning+"'?")
Page | 129
Tran Duy Thanh https://tranduythanh.com
word=voc.check(meaning,answer)
if word is Ellipsis:
print("is the correct answer")
else:
print("The correct answer is'"+word+"'")
voc.renew()
print("\nWord learning is over")
Test case 2:
Page | 130
Tran Duy Thanh https://tranduythanh.com
Test Case 2 Quat is wrong 1 time. So next time go to test case 3 (you should do yourself)
I put my code in GitHub, here is the link:
https://github.com/thanhtd32/advancedpython_part1/blob/main/Exercise22.py
Page | 131
Tran Duy Thanh https://tranduythanh.com
Page | 132
Tran Duy Thanh https://tranduythanh.com
Page | 133
Tran Duy Thanh https://tranduythanh.com
Because we have to test with many vocabularies so it is difficult to enter from the program.
I create database in excel. And coding to read all vocabularies from excel.
All codes:
#Coder: Tran Duy Thanh
#Email: thanhtd@uel.edu.vn
#Phone: 0987773061
#Blog for self-study: https://duythanhcse.wordpress.com
#Facebook for solving coding problem: https://www.facebook.com/groups/communityuni
#Description:
#These codes I improved from Exercise 22.
#Improved the word memorization program if there many vocabularies to learn, take 5 sample vocabularies
to learn
#1.Update Vocabulary class
# 1.1 use random.sample (see takeVocabularyToLearn(self) function)
# 1.2 Difference operator ‘-’ (see updateUnmemorized(self) functin)
# 1.3 updated 2 new attribute: self.unmemorized (any vocabularies is unmemorized),
# and self.memorized (for memorized for each periodic
# 1.4 update check to save memorized word or not
# 1.5 static method buildVocabularyDatabase to read vocabularies from Excel (many vocabularies)
# 1.6 method printAllVocabularies(self) -> print all original vocabularies
# 1.7 method printStatusProgressingLearning(self)-> show status progressing learning
#2. Create a new class VocabularyExecutor
# this class use to create 4 option menuitem
# 2.1 Overview Vocabulary -> show all vocabularies from Vocabulary Object
# 2.2 Re-Learn Vocabulary -> learners can re learn vocabularies
# 2.3 Continue learning Vocabulary -> learners can continue to learn vocabulary
# It means: learner can learn vocabulary day by day, can stop software and continue learn from history
# program saved vocabulary to object file and restored for learner to continue to learn
# 2.4 Exit program
import pickle
import random
import pandas as pd
class Vocabulary:
def __init__(self,wdict):
self.words=wdict.copy()
self.untrained=set(self.words)
self.unmemorized=self.untrained.copy()
self.memorized=set()#variable save to correct vocabulary for each periodic
Page | 134
Tran Duy Thanh https://tranduythanh.com
def updateUnmemorized(self):
self.unmemorized = self.unmemorized - self.memorized
def target_keys(self):
return self.target
def shuffle(self):
random.shuffle(self.target)
#this static method used to build vocabulary database from Excel
@staticmethod
def buildVocabularyDatabase():
wdict = {} # empty dictionary
data = pd.read_excel(r'data_exercise23/Database_Vocabulary.xlsx') # read data
df = pd.DataFrame(data, columns=['English Language', 'Korean Language'])
for i in range(len(df.index)):
english = df.iloc[i]["English Language"]
korean = df.iloc[i]["Korean Language"]
wdict[korean] = english
voc = Vocabulary(wdict)
return voc
Page | 135
Tran Duy Thanh https://tranduythanh.com
Page | 136
Tran Duy Thanh https://tranduythanh.com
#this function use to save the vocabularies and progressing learning to file
#so we can restore to continue learning
def persistenceVocabulary(self):
with open(self.filename, 'wb') as output: # Overwrites any existing file.
pickle.dump(self.voc, output, pickle.HIGHEST_PROTOCOL)
Page | 137
Tran Duy Thanh https://tranduythanh.com
Program will pick 5 vocabularies from list (using random.sample method). Now learner
can enter the number of question and answers by word, eg: 2
Page | 139
Tran Duy Thanh https://tranduythanh.com
Program will show 5 another vocabulary: Only word is wrong from previous periodic +
new vocabularies. But program pick randomizes vocabularies.
This time we enter number of questions and answers by word is 1
Page | 140
Tran Duy Thanh https://tranduythanh.com
In this case:
You have not yet memorized 15 vocabularies
You already memorized 8 vocabularies
For each periodic learning, Vocabulary object will be stored “vocabulary.dat”:
This file will be used for “3.Continue learning Vocabulary” Lasted status
Test case 5: Press “4.Exit program” to exit program progressing learning
Page | 141
Tran Duy Thanh https://tranduythanh.com
Page | 142
Tran Duy Thanh https://tranduythanh.com
Page | 143
Tran Duy Thanh https://tranduythanh.com
Page | 144
Tran Duy Thanh https://tranduythanh.com
28.2.5.Data
• A list of turtle shapes
28.3. Full algorithm skeleton
start
Register images of scissors, rocks, and paper as shapes that the turtle can
have. Put scissors, rock, and paper image files on the list so the computer can
choose one at random.
It is calculated by calling a function that compares whether the user won or the
computer won.
End
Page | 145
Tran Duy Thanh https://tranduythanh.com
28.4. Programming
28.4.1.Variables
• s: A list to save the file names of the scissors, rock, and paper images used by the
computer. The image file format must be gif.
• cno: a random number chosen by the computer among 0, 1,2
• myno: 0, 1, 2, selected by the user (paper:0, scissors:1, rock:2, paper:0)
• result: Variable for calculating the winner (Scissors <rock <paper <scissors)
28.4.2.Some explanations
Methods of importing modules:
import turtle
import turtle as t
from turtle import *
How to register multiple images of Turtle
here is the Link of images:
https://github.com/thanhtd32/advancedpython_part1/tree/main/data_exercise24
s=["data_exercise24/paper_machine.gif",
"data_exercise24/scissor_machine.gif",
"data_exercise24/rock_machine.gif"]
#Set the size of the screen
t.setup(300,300)
for img in s:
#Register image to be #turtle shape
t.addshape(img)
function show_result():
def show_result(myno,cno):
t.shape(s[cno])
# Calculating the Win
result=myno-cno
msg=""
if result ==2:
# I rock, look at the computer, I'm Jim
result =-1
elif result ==-2:
# I see, the computer rocks. I win
result=1
if result ==0:
print("A draw with a computer. Do it again.")
msg="A draw with a computer. Do it again."
elif result <0: #result =-1
print("You lost")
msg="You lost"
else: #result =1
#You won
Page | 146
Tran Duy Thanh https://tranduythanh.com
print("You won")
msg = "You won"
turtle.write(msg, False, align="center")
0 is paper, 1 is scissors, and 2 is rock. Actually, 0 (beam) < 1 (scissors) < 2 (rock). Since
the beam beats the rock, result = myno – cno to find the difference results in –2 or 2. If the
result value is 1, it is a win, 0 is a draw, -1 is a loss, 2 is a loss, -2 is a win case
Turtle's onkeypress() function:
#I make rocks
t.onkeypress(rock, 'r')
#I make sissor
t.onkeypress(scissor,'s')
#I make paper
t.onkeypress(paper,'p')
Confirmation of scissors, rock, and paper:
def rock():
cno=randint(0,2)
myno=2
print("Your choice is [rock]",end='')
show_result(myno,cno)
def scissor():
cno=randint(0,2)
myno=1
print("Your choice is [scissors].",end='')
show_result(myno,cno)
def paper():
cno=randint(0,2)
myno=0
print("Your choice is [paper]",end='')
show_result(myno, cno)
import turtle
import turtle as t
from turtle import *
Page | 147
Tran Duy Thanh https://tranduythanh.com
t.setup(300,300)
for img in s:
#Register image to be #turtle shape
t.addshape(img)
print("If you want to play rock paper scissors, press s for scissors, r for rock, and p for jaws.")
def show_result(myno,cno):
t.shape(s[cno])
# Calculating the Win
result=myno-cno
msg=""
if result ==2:
# I rock, look at the computer, I'm Jim
result =-1
elif result ==-2:
# I see, the computer rocks. I win
result=1
if result ==0:
print("A draw with a computer. Do it again.")
msg="A draw with a computer. Do it again."
elif result <0: #result =-1
print("You lost")
msg="You lost"
else: #result =1
#You won
print("You won")
msg = "You won"
turtle.write(msg, False, align="center")
def rock():
cno=randint(0,2)
myno=2
print("Your choice is [rock]",end='')
show_result(myno,cno)
def scissor():
cno=randint(0,2)
myno=1
print("Your choice is [scissors].",end='')
show_result(myno,cno)
def paper():
cno=randint(0,2)
myno=0
print("Your choice is [paper]",end='')
show_result(myno, cno)
#I make rocks
t.onkeypress(rock, 'r')
#I make sissor
t.onkeypress(scissor,'s')
#I make paper
t.onkeypress(paper,'p')
t.listen()
t.mainloop()
Page | 148
Tran Duy Thanh https://tranduythanh.com
Page | 149
Tran Duy Thanh https://tranduythanh.com
#Description:
#These codes I improved from Exercise24.
#Improved the rock-scissors - paper
#1.create class GameGUI
#2.Update GUI for turtle
# 2.1. All the results are drawn on the GUI
# 2.2. Load image rock, scissors, paper for Computer and human
#3. Show the result for each playing
import turtle
from random import randint
class GameUI:
#list to store image for Machine
arrImageMachine = ["data_exercise25/paper_machine.gif",
"data_exercise25/scissor_machine.gif",
"data_exercise25/rock_machine.gif"]
# list to store image for Human
arrImageHuman = ["data_exercise25/paper_human.gif",
"data_exercise25/scissor_human.gif",
Page | 150
Tran Duy Thanh https://tranduythanh.com
"data_exercise25/rock_human.gif"]
Page | 151
Tran Duy Thanh https://tranduythanh.com
Page | 152
Tran Duy Thanh https://tranduythanh.com
def rock(self):
cno=randint(0,2)
myno=2
#Your choice is [rock]
self.show_result(myno,cno)
#I make sissor
turtle.onkeypress(self.scissor,'s')
turtle.onkeypress(self.scissor,'S')
#I make paper
turtle.onkeypress(self.paper,'p')
turtle.onkeypress(self.paper,'P')
turtle.listen()
def showGameUI(self):
self.welcome()
self.eventListener()
turtle.mainloop()
#create game object
game=GameUI()
#call showGameUI method to start a game
game.showGameUI()
Player can press r, R, p, P, s, S to choose rock, paper or scissors. Program will show
image for human and computer random image on the screen.
Page | 153
Tran Duy Thanh https://tranduythanh.com
Test case 2:
Player press [r] or [R]:
Result
Player Computer
Player press [r] [R]. program will show Rock for player. And now random computer is
Paper. In this case, player is lost!
Test case 3:
Player press [s] or [S]:
Result
Computer
Player
Player press [s] [S]. program will show Scissors for player. And now random computer is
Paper. In this case, player is won!
Page | 154
Tran Duy Thanh https://tranduythanh.com
Test case 4:
Player press [p] or [P]:
Result
Computer
Player
Player press [p] [P]. program will show Paper for player. And now random computer is
Scissors. In this case, player is lost!
Test case 5:
Player press [r] or [R] again:
Result
Computer
Player
Player press [r] [R]. program will show Rock for player. And now random computer is
Paper. In this case, player is lost!
Page | 155
Tran Duy Thanh https://tranduythanh.com
Test case 6:
Player press [s] or [S] again:
Result
Computer
Player
Player press [s] [S]. program will show Scissors for player. And now random computer is
Scissors. In this case, player and computer getting drawing!
Test case 7:
Player press [p] or [P] again:
Result
Computer
Player
Player press [p] [P]. program will show Paper for player. And now random computer is
Rock. In this case, player is won!
Page | 156
Tran Duy Thanh https://tranduythanh.com
Page | 157
Tran Duy Thanh https://tranduythanh.com
start
Each random number is stored in a list object named numbers, allowing you to
check whether the answer/answer is correct.
Check the numbers while receiving the input and immediately end the
verification process if any one is wrong
Prints the result on the screen and reveals whether the answer is correct or
incorrect
End
Page | 158
Tran Duy Thanh https://tranduythanh.com
30.4. Programming
30.4.1.Variables
• numbers: A list of computer-generated random numbers.
• qno: number of random numbers
• unumber: the number entered by the user
30.4.2.Some explanations
Methods of importing modules:
from turtle import * # Turtle module
from random import randint #Random number related module
from time import sleep #Time training module
Receive input with textinput() function and set the size of the window
qno=int(textinput("","How many numbers do you want to remember?"))
if qno>1 :
setup(300,200)
• Repeat the following as many times as the number of random numbers to generate
(qno).
o Generate a random number between 1 and 99 and output it to (0, 0) of the
turtle window
o Save the generated random number to list numbers
o Stop execution for a while, delete the turtle window, and initialize the turtle's
position
for i in range(qno):
# Clear the screen and set the turtle's position to (0,0)
reset()
#hide the shape of the turtle
ht()
# Pick up the pen to stop drawing
pu()
#turtle 위치의 이동
goto(-30,0)
numbers.append(randint(1,99))
write(numbers[i],font=("",32))
# 2 second pause
sleep(2)
User guessing the numbers:
Success=True
for i in range(qno):#Compare 5 numbers
unumber=int(input(str(i+1)+' digit>>'))
if unumber != numbers[i] :
#If not, treat incorrect answer
print(numbers,"It's wrong answer")
Page | 159
Tran Duy Thanh https://tranduythanh.com
if qno>1 :
setup(300,200)
for i in range(qno):
# Clear the screen and set the turtle's position to (0,0)
reset()
#hide the shape of the turtle
ht()
# Pick up the pen to stop drawing
pu()
#turtle 위치의 이동
goto(-30,0)
numbers.append(randint(1,99))
write(numbers[i],font=("",32))
# 2 second pause
sleep(2)
#Close the turtle screen
bye()
Success=True
for i in range(qno):#Compare 5 numbers
unumber=int(input(str(i+1)+' digit>>'))
if unumber != numbers[i] :
#If not, treat incorrect answer
print(numbers,"It's wrong answer")
#The answer is not the same, so it is treated as a failure
Success = False
break
if i == qno - 1: #If everything is correct, the answer is correct
print(numbers,"That's the right answer.")
Page | 160
Tran Duy Thanh https://tranduythanh.com
Result:
Page | 161
Tran Duy Thanh https://tranduythanh.com
import string
from turtle import * # Turtle module
from random import randint # Random number related module
from time import sleep # Time training module
import functools
import turtle as turtle
Page | 162
Tran Duy Thanh https://tranduythanh.com
alphabets_memory.clear()
for i in range(qno):
position = randint(0, len(alphabets) - 1)
alphabet = alphabets[position]
alphabets_memory.append(alphabet)
drawLabel(random_turtle, alphabet, 0, 10, 'blue', style, "left")
sleep(2)
style = ('tahoma', 20, 'bold')
drawLabel(random_turtle, "Please press key to answer!",
-150, 10, 'red', style, "left")
#listening event
for k in alphabets_lowercase:
turtle.onkeypress(functools.partial(event_handler, k), key=k)
for k in alphabets_uppercase:
turtle.onkeypress(functools.partial(event_handler, k), key=k)
global needToRemoveListen,position_memory
needToRemoveListen=False
position_memory=0
turtle.listen()
#this function use to draw welcome and alphabet
def drawWelcomeAndAlphabet():
Page | 163
Tran Duy Thanh https://tranduythanh.com
#draw welcome
style = ('tahoma', 20, 'bold')
drawLabel(turtle_title, "Welcome to Memory Testing!",
-150, 250, 'blue', style, "left")
style = ('tahoma', 12, 'italic')
#draw upper case alphabets
s_uppercase=""
for s in alphabets_uppercase:
s_uppercase=s_uppercase+s+" "
s_uppercase="Uppercase alphabet:"+s_uppercase
drawLabel(alphabets_uppercase_title, s_uppercase,
-350, 200, 'blue', style, "left")
#draw lower case alphabets
s_lowercase=""
for s in alphabets_lowercase:
s_lowercase=s_lowercase+s+" "
s_lowercase="Lowercase alphabet:"+s_lowercase
style = ('tahoma', 12, 'italic')
drawLabel(alphabets_lowercase_title, s_lowercase, -350, 150, 'blue', style, "left")
#this function use to draw red Circle button
#player will click on this Button to Start the Game
def drawRedCircleButton():
button = Turtle()
button.hideturtle()
button.shape('circle')
button.fillcolor('red')
button.penup()
button.goto(0, 100)
button.write("Click red Circle to Start Game!", align='center', font=FONT)
button.sety(100 + CURSOR_SIZE + FONT_SIZE)
button.onclick(draw_onclick)
button.showturtle()
#this function use to process listening player press the Key on Keyboard
#if all Alphabets is right position->show congratulations
#if any an alphabet is wrong->show Condolatory!
def event_handler(key):
global needToRemoveListen,position_memory
if needToRemoveListen == True:
return
print(key)
style = ('tahoma', 20, 'bold')
drawLabel(random_turtle, key, -150, 10, 'blue', style, "left")
sleep(0.5)
if key != alphabets_memory[position_memory]:
needToRemoveListen=True
style = ('tahoma', 20, 'bold')
drawLabel(random_turtle, "Condolatory!\nYou are wrong, the memory list:" +
','.join(alphabets_memory), -150, 10,'red', style, "left")
position_memory = position_memory+1;
if position_memory == len(alphabets_memory) and needToRemoveListen ==False:
style = ('tahoma', 20, 'bold')
drawLabel(random_turtle, "Congratulations!\nYou answered correctly:"+
','.join(alphabets_memory),-150, 10, 'blue', style, "left")
turtle.setup(900, 600)
turtle.title("Memory Testing!")
Page | 164
Tran Duy Thanh https://tranduythanh.com
drawWelcomeAndAlphabet()
drawRedCircleButton()
turtle.mainloop()
Click here to
play Game
Test case 2:
Now, we click the Red Circle button to start the Game:
Enter 5 and
click OK to test
Program will draw step by step with sleep 2 second for each random Alphabet
Page | 165
Tran Duy Thanh https://tranduythanh.com
After draw all step-by-step random alphabet. Program will ask user to play:
Now, We press to start the game. If player press not correct the alphabet, program will
show message “…You are wrong…” with the list random of computer:
Page | 166
Tran Duy Thanh https://tranduythanh.com
Test case 3:
Now, we click the Red Circle button again to start the Game:
We enter 5 and click ok to answer. In this test case, 5 alphabets are: G,F,h,R,t
Page | 167
Tran Duy Thanh https://tranduythanh.com
Now, We press G, F, h, R, t
Page | 168
Tran Duy Thanh https://tranduythanh.com
Page | 169
Tran Duy Thanh https://tranduythanh.com
• Button click
32.2.4.Output
• Text written above the button clicked
• calculation result
32.2.5.Data
• Numbers 0 to 9, four arithmetic operators (+, -, *, /) and other Python operators (%,
//, **)
32.3. Full algorithm skeleton
start
Set the width and height of the buttons so that the buttons can be placed in 4
rows and 5 columns in the window. When an event that a specific button is
clicked occurs, a function click() to handle it is set.
The function click() receives the input of which button the user clicked, and
takes an appropriate action according to the input text. If the input character
is'=', the calculation result is calculated, and if the input character is'C',
Delete all the contents of the entry. Other characters are displayed in the
Entry widget.
End
Page | 170
Tran Duy Thanh https://tranduythanh.com
32.4. Programming
32.4.1.Variables
• window: the window object
• e: Entry widget. Show calculation results
• buttons: List of characters to be printed on the button
• row: The row where the specific button will be placed
• col: the column in which the specific button will be placed
• key: The character above the button the user clicked
• b: One Button widget
32.4.2.Some explanations
The tkinter module and defines a window object:
from tkinter import *
window =Tk()
window.title("Create a calculator")
Define an Entry widget to show the result of the calculation:
e=Entry(window,width=40,bg="black",fg="white",bd=5)
e.grid(row=0,column=0,columnspan=5)
Grid:
When placing the Entry widget in a window, it will be placed at the bottom.
Button widgets are arranged in a grid shape, 5 per row.Assuming you want to place the
columnspan to 5 setting. Since it is the first widget, the row and column values are All set
to 0.
Initialization of the button list:
buttons=[
'0', '1', '2', '+', '%',
'3', '4', '5', '-', '//',
'6', '7', '8', '*', "**",
'9', '.', '=', '/', 'C']
Button widget initialization:
row = 1
col =0
for char in buttons:
b=Button(window, text=char, width=7, height=3, command=click)
b.grid(row=row,column=col)
col +=1
if col >4:
row +=1
col=0
Page | 171
Tran Duy Thanh https://tranduythanh.com
• The Button widget is defined by dividing the window into a 4-row, 5-column grid.
• Buttons are arranged from row 1. It starts to be arranged from the 0th column, and
when the value of the column col variable becomes 5, This means that one row is
full of 5 buttons, so we set the variable row to 1 to go to the next row. increment,
and the variable col is initialized to 0.
• When an event that a button is clicked occurs, the function that handles it, click, is
assigned as the value of the command option.
When an event of clicking a specific button occurs, click(), a function that handles this
event:
for char in buttons:
def click(key = char):
if key == '=':
result=eval(e.get())
s=str(result)
e.delete(0,END)
e.insert(0,s)
elif key =='C':
e.delete(0,END)
else:
e.insert(END,key)
• Function click( ) is defined in a loop to accept which button was clicked as a parameter.
• Determine which button was clicked and what the corresponding character is with the
parameter key.
• If the key value is ‘ = ’, define the strings entered so far as parameters of the eval()
function and calculate the result value.
• If the key value is ‘C’, the contents of the Entry widget are deleted with the delete()
function.
• Other characters are stored in the Entry widget by using the method insert () of the object
variable e in turn.
32.4.3.Programming-the whole program
The whole program is shown as below.
#Coder: Tran Duy Thanh
#Email: thanhtd@uel.edu.vn
#Phone: 0987773061
#Blog for self-study: https://duythanhcse.wordpress.com
#Facebook for solving coding problem: https://www.facebook.com/groups/communityuni
from tkinter import *
window =Tk()
window.title("Create a calculator")
e=Entry(window,width=40,bg="black",fg="white",bd=5)
Page | 172
Tran Duy Thanh https://tranduythanh.com
e.grid(row=0,column=0,columnspan=5)
buttons=[
'0', '1', '2', '+', '%',
'3', '4', '5', '-', '//',
'6', '7', '8', '*', "**",
'9', '.', '=', '/', 'C']
row = 1
col =0
for char in buttons:
def click(key = char):
if key == '=':
result=eval(e.get())
s=str(result)
e.delete(0,END)
e.insert(0,s)
elif key =='C':
e.delete(0,END)
else:
e.insert(END,key)
b=Button(window, text=char, width=7, height=3, command=click)
b.grid(row=row,column=col)
col +=1
if col >4:
row +=1
col=0
window.mainloop()
Page | 173
Tran Duy Thanh https://tranduythanh.com
Test case 2: -
Test case 3: *
Page | 174
Tran Duy Thanh https://tranduythanh.com
Page | 175
Tran Duy Thanh https://tranduythanh.com
labelConfig("=", True)
labelConfig(s, True)
elif key =='C':
#reset text for Label
labelConfig("",False)
else:
#concat string for label
labelConfig(key, True)
b=Button(window, text=char, width=7, height=3, command=click)
b.grid(row=row,column=col)
col +=1
if col >4:
row +=1
col=0
#this function use to set the screen is center of the desktop
def center(window):
window.update_idletasks()
width = window.winfo_width()
frm_width = window.winfo_rootx() - window.winfo_x()
win_width = width + 2 * frm_width
height = window.winfo_height()
titlebar_height = window.winfo_rooty() - window.winfo_y()
win_height = height + titlebar_height + frm_width
x = window.winfo_screenwidth() // 2 - win_width // 2
y = window.winfo_screenheight() // 2 - win_height // 2
window.geometry('{}x{}+{}+{}'.format(width, height, x, y))
window.deiconify()
center(window)
window.mainloop()
Test case 2:
Page | 176
Tran Duy Thanh https://tranduythanh.com
Test case 3:
Click ‘C’ and test for ‘-’ and ‘+’:
Test case 4:
Click ‘C’ and test for ‘//’ and ‘/’:
Page | 177
Tran Duy Thanh https://tranduythanh.com
Test case 5:
Click ‘C’ and test for ‘*’ and ‘**’:
Test case 6:
Click ‘C’ and test for decimal number and complex expression
Page | 178
Tran Duy Thanh https://tranduythanh.com
Page | 179
Tran Duy Thanh https://tranduythanh.com
Page | 180
Tran Duy Thanh https://tranduythanh.com
start
Define a window object to provide the desired GUI, and define the result
Label widgets that push questions, images, and correct/incorrect answers.
Open the file to retrieve the problems and save them to a list
Even if the Entry widget is defined so that the correct answer can be entered, when
the user presses the [Enter] key to complete the correct answer input, the function to
handle the key event is defined. In the function, it determines whether the user's
answer is the correct answer or the incorrect answer. Print to Label widget
Define a Button widget for presenting the next problem and define a function to
handle this event when the button is clicked.
In the above button click event handling function, the process of dividing each string
stored in the list in order to bring the problems stored in the list in order and present
it on the screen, and the contents changed so that each content can be included as an
appropriate label widget
The problem presentation function is called to start presenting the problem, and when
all the problems are presented, the first problem can be presented counterfactually.
End
Page | 181
Tran Duy Thanh https://tranduythanh.com
34.4. Programming
34.4.1.Variables
• window: the window object
• qlabel: problem label widget variable
• ilabel: Image label widget variable
• rlabel: Result label widget variable indicating whether the correct answer is correct
or not
• file: file object
• p: a list containing the string containing the problem as an element
• answer: the correct answer string
• e: Entry widget variable that handles user input
34.4.2.Some explanations
Includes tkinter for the GUI and defines the Label widget variables to define the quiz
question, image, and answer fields.
from tkinter import *
window=Tk()
window.title("Take the quiz")
window.geometry("400x650+10+10")
#question label
qlabel=Label(window,width=100,text="")
qlabel.pack()
#image label
ilabel=Label(window)
ilabel.pack()
#Write the correct answer and press [Enter].
Label(window,text="Write the correct answer and press [Enter].").pack()
#Correct/Incorrect result label
rlabel=Label(window)
rlabel.pack()
Open file containing quiz questions and answers:
Data for exercise 30.
https://github.com/thanhtd32/advancedpython_part1/tree/main/data_exercise30
file=open("data_exercise30/problem.txt","r",encoding="utf8")
p=file.readlines()
file.close()
i=-1
answer=""
Page | 182
Tran Duy Thanh https://tranduythanh.com
Page | 183
Tran Duy Thanh https://tranduythanh.com
Page | 184
Tran Duy Thanh https://tranduythanh.com
def checkanswer(event):
global answer, e
if answer ==e.get() :
rlabel.config(text="Correct answer.")
else:
rlabel.config(text="Wrong answer.")
#User answer input window
e=Entry(window,width=50)
e.bind("<Return>",checkanswer)
Page | 185
Tran Duy Thanh https://tranduythanh.com
e.pack()
def getQuestion():
global i,answer, e
i +=1
# Repeat because there are 4 problems
if i >=4 : i =0
e.delete(0,len(e.get()))
rlabel.config(text="")
aQuestion =p[i].strip()
Q=aQuestion.split(":")
#Q[0]: - the problem
#Q[1]: - Answer
#Q[2]: - image file
qlabel.config(text=Q[0])
answer=Q[1]
img=PhotoImage(file=Q[2])
ilabel.config(image=img)
ilabel.image=img
Button(window,text="next problem",command=getQuestion).pack()
getQuestion()
window.mainloop()
Page | 186
Tran Duy Thanh https://tranduythanh.com
Page | 187
Tran Duy Thanh https://tranduythanh.com
#Description:
#These codes I improved from Exercise 30
#re-design GUI for quiz game
#1. Add 4 radio button to show sample question (4 question)
#2. Add more data for problem.txt
#3. Create a FileFactory class, use to read a text file and return a List string
#4. Create a Question class, it is a model class for a question
Page | 188
Tran Duy Thanh https://tranduythanh.com
Page | 189
Tran Duy Thanh https://tranduythanh.com
def getQuestion(self,index):
if self.isEmpty():
return None
if index<0 or index>=len(self.questions):
return None
return list(self.questions)[index]
#function to get sample 4 question
#and shuttle the question
def sample(self,index):
currentQuestion = self.getQuestion(index)
currentSet=set()
currentSet.add(currentQuestion)
remainList=self.questions-currentSet
samples=random.sample(remainList,3)
samples.append(currentQuestion)
random.shuffle(samples)
return samples
#this function return size of the list
def sizeOfList(self):
return len(self.questions)
#this class use to design GUI for the Quiz game
# all the UI is designed in this class
# process show question when user click next question
# show the result when user answer the question
# add center place for the screen of the desktop
class QuizeUI:
window = None
qlabel = None
ilabel = None
rlabel = None
radVars =None
questionBanks = None
currentPosition=-1
currentQuestion=None
#4 radio buttons
rad1 = None
rad2 = None
rad3 = None
rad4 = None
def __init__(self):
self.window = Tk()
# question label
self.qlabel = Label(self.window, width=100, text="",fg="blue")
self.qlabel.pack()
# image label
self.ilabel = Label(self.window)
self.ilabel.pack()
Label(self.window, text="Choose the correct answer and click [Next Question]").pack()
# Correct/Incorrect result label
self.rlabel = Label(self.window,text="")
self.rlabel.pack()
frame = Frame(self.window)
self.radVars = StringVar(frame, "<none>")
Page | 190
Tran Duy Thanh https://tranduythanh.com
self.questionBanks = ListQuestion()
if self.questionBanks.isEmpty() == False:
self.currentPosition = 0
self.showQuestion()
#this function use to show the value of radiobutton when user selection
def selection(self):
s = "You selected the option [" + str(self.radVars.get())+"]"
self.rlabel.config(text=s,fg='blue')
#This function use to show the next question and
def showQuestion(self):
self.currentQuestion=self.questionBanks.getQuestion(self.currentPosition)
self.qlabel.config(text=self.currentQuestion.problemContent)
img = PhotoImage(file=self.currentQuestion.image).subsample(2, 2)
self.ilabel.config(image=img)
self.ilabel.image = img
randomAnswers= self.questionBanks.sample(self.currentPosition)
self.rad1.config(text=randomAnswers[0].problemAnser,value=randomAnswers[0].problemAnser)
self.rad2.config(text=randomAnswers[1].problemAnser,value=randomAnswers[1].problemAnser)
self.rad3.config(text=randomAnswers[2].problemAnser,value=randomAnswers[2].problemAnser)
self.rad4.config(text=randomAnswers[3].problemAnser,value=randomAnswers[3].problemAnser)
self.currentPosition +=1
Page | 191
Tran Duy Thanh https://tranduythanh.com
x = win.winfo_screenwidth() // 2 - win_width // 2
y = win.winfo_screenheight() // 2 - win_height // 2
win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
win.deiconify()
#this function use to show the GUI of the Quiz
def showUI(self):
# Take the quiz
self.window.title("Take the quiz- Improved")
self.window.geometry("550x400")
self.center(self.window)
self.window.mainloop()
#call showUI() to start the program
QuizeUI().showUI()
Problem content
Problem image
Automatic
sampling
and shuffle
If user choose the radio, the content of radio will be shown on the GUI:
Page | 192
Tran Duy Thanh https://tranduythanh.com
Choose this
Next Question
Next question
Page | 193
Tran Duy Thanh https://tranduythanh.com
Now Clicking Next Question to see the result and next question:
We can test with many test cases. The program will repeat the list of the question.
Page | 194
Tran Duy Thanh https://tranduythanh.com
Page | 195
Tran Duy Thanh https://tranduythanh.com
Page | 196
Tran Duy Thanh https://tranduythanh.com
36.2.3.Problem decomposition
• Displaying fine dust and ultrafine dust data
• Representing fine dust as a bar graph
• Representing ultrafine dust as a bar graph
36.2.4.Thinking of users
• Consider which color to use
• Consider how to display the horizontal and vertical axes
36.2.5.Data
• Array of integers to represent ultrafine dust
• integer array to represent fine dust
• A list of strings to represent the time from 1:00 to 10:00
36.3. Full algorithm skeleton
start
End
Page | 197
Tran Duy Thanh https://tranduythanh.com
36.4. Programming
36.4.1.Variables
• hour: String list from 1 o'clock to 10 o'clock
• pm25: Integer array of ultrafine dust over time
• pm10: Integer array of fine dust over time
36.4.2.Some explanations
Import packages for drawing numpy arrays and bar graphs
Initializing list and array to store time, fine dust, and ultrafine dust data
import numpy as np
import matplotlib.pyplot as plt
hour=['1h','2h','3h','4h','5h','6h','7h','8h','9h','10h']
pm25=np.array([34,37,30,27,35,38,43,42,37,35])
pm10=np.array([46,49,41,40,81,90,53,52,55,51])
• The program below determines the size of the bar graph and the layout of the bar
graph.
• Specify the color of the bar graph according to the fine dust value
• Display legend and set bar graph title
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
hour=['1h','2h','3h','4h','5h','6h','7h','8h','9h','10h']
pm25=np.array([34,37,30,27,35,38,43,42,37,35])
pm10=np.array([46,49,41,40,81,90,53,52,55,51])
plt.figure(figsize=(10,10))
plt.subplot(2,1,1)
for i in range(10):
if pm25[i]<15:
plt.bar(hour[i],pm25[i],color='blue')
elif 15<=pm25[i]<35:
plt.bar(hour[i],pm25[i],color='green')
elif 35<=pm25[i]<75:
plt.bar(hour[i],pm25[i],color='orange')
elif pm25[i]>=75:
plt.bar(hour[i],pm25[i],color='red')
plt.title('pm2.5')
plt.show()
Page | 198
Tran Duy Thanh https://tranduythanh.com
• The following program sets the layout of the bar graph below the bar graph drawn
earlier.
• Specify the color of the bar graph according to the fine dust value
• Decide on a bar graph title and display it on the screen
plt.subplot(2,1,2)
for i in range(10):
if pm10[i]<30:
plt.bar(hour[i],pm10[i],color='blue')
elif 30<=pm10[i]<80:
plt.bar(hour[i],pm10[i],color='green')
elif 80<=pm10[i]<150:
plt.bar(hour[i],pm10[i],color='orange')
elif pm10[i]>=150:
plt.bar(hour[i],pm10[i],color='red')
plt.title('pm10')
plt.show()
hour=['1h','2h','3h','4h','5h','6h','7h','8h','9h','10h']
pm25=np.array([34,37,30,27,35,38,43,42,37,35])
pm10=np.array([46,49,41,40,81,90,53,52,55,51])
#Set the picture horizontal and vertical size
plt.figure(figsize=(10,10))
#1 of 2 rows
plt.subplot(2,1,1)
for i in range(10):
if pm25[i]<15:
plt.bar(hour[i],pm25[i],color='blue')
elif 15<=pm25[i]<35:
plt.bar(hour[i],pm25[i],color='green')
elif 35<=pm25[i]<75:
plt.bar(hour[i],pm25[i],color='orange')
elif pm25[i]>=75:
plt.bar(hour[i],pm25[i],color='red')
plt.title('pm2.5')
#2 of 2 rows
Page | 199
Tran Duy Thanh https://tranduythanh.com
plt.subplot(2,1,2)
for i in range(10):
if pm10[i]<30:
plt.bar(hour[i],pm10[i],color='blue')
elif 30<=pm10[i]<80:
plt.bar(hour[i],pm10[i],color='green')
elif 80<=pm10[i]<150:
plt.bar(hour[i],pm10[i],color='orange')
elif pm10[i]>=150:
plt.bar(hour[i],pm10[i],color='red')
plt.title('pm10')
plt.show()
Page | 200
Tran Duy Thanh https://tranduythanh.com
Page | 201
Tran Duy Thanh https://tranduythanh.com
Page | 202
Tran Duy Thanh https://tranduythanh.com
Notation
Sum Value
Page | 203
Tran Duy Thanh https://tranduythanh.com
Test case 2:
Change the array of value:
pm25=np.array([34,37,30,14,35,75,43,42,37,35])
pm10=np.array([46,29,41,40,81,90,53,52,151,51])
The result: The char show is changed with full color list mapping. And also, we have sum
and notation are changed.
Sum Value
Notation
Sum Value
Notation
Page | 204
Tran Duy Thanh https://tranduythanh.com
Test case 3:
Change the array of value, make sorting array:
pm25=np.array([14,30,34,35,35,37,37,42,43,75])
pm10=np.array([29,40,41,46,51,52,53,81,90,151])
The result: The char show is changed with full color list mapping. And also, we have sum
and notation are changed.
Sum Value
Notation
Sum Value
Notation
Page | 205
Tran Duy Thanh https://tranduythanh.com
Page | 206
Tran Duy Thanh https://tranduythanh.com
start
Calculates and displays the circumference ratio using the number of points in a circle
End
Page | 207
Tran Duy Thanh https://tranduythanh.com
38.4. Programming
38.4.1.Variables
• inCircle: the number of points in the circle
• simCount: number of simulations
• x,y: x,y coordinate values
38.4.2.Some explanations
• A simulation method to obtain probabilistic values through iterative calculations
using random numbers
• Monte Carlo simulation is widely used to probabilistically solve complex problems
in numerical analysis, statistical mechanics, and science and engineering.
• Even in programs such as AlphaGo, an artificial intelligence Go program, the
probability of winning and losing is calculated by playing countless Go games
through Monte Carlo simulation.
• Monte Carlo simulation is mathematically based on the concept of statistics and
probability fields that the characteristics of a sample randomly selected from a large
population become closer to the characteristics of the population as the number
increases.
• For example, the probability of a characteristic investigation with dice is obtained
as close to 1/6 as the number of simulations increases.
The more simulations you get, the closer you get to a more accurate value of perimeter,
but the more simulations you run, the longer it takes
import random
import matplotlib.pyplot as plt
incircle=0
The following program creates a circle with origin (0, 0) and radius length 1.
The inside of the circle is not filled, the circle is drawn in blue
Use the add_patch() method to display the circle object on the graph.
Use the set_aspect() method to set the ratio of the x-axis and y-axis equally
Page | 208
Tran Duy Thanh https://tranduythanh.com
circle_center=(0,0)
circle_radius=1
c=plt.Circle(circle_center,circle_radius,ec='b',fill=False)
a=plt.axes(xlim=(-1,1),ylim=(-1,1))
a.add_patch(c)
a.set_aspect('equal')
Display the X,y coordinates as a point of size 2 using the scatter() method.
Check whether the Y coordinate value is within a circle with a radius of 1 using a
conditional statement
Calculate the circumference ratio by dividing the number of points in the circle by the
total number of simulations
for i in range(simCount):
# Create real number x coordinates from -1 to 1
x=random.uniform(-1.0,1.0)
# Create real y coordinates from -1 to 1
y=random.uniform(-1.0,1.0)
plt.scatter(x,y,s=2)
dot_value=x*x+y*y
# Test where the (x,y) coordinates are in the circle
if dot_value<=1:
incircle =incircle+1
print("Pi=",4*incircle/simCount)
plt.show()
Page | 209
Tran Duy Thanh https://tranduythanh.com
Line 6 - import the random module to perform the Monte Carlo simulation
Lines 22 to 26 - Use random numbers to obtain x and y coordinate values and display
them as small circles using the scatter() method.
Lines 29 to 32 - Check whether the coordinates obtained using random numbers are in
the circle, and if it is in the circle, increase the incircle value by 1.
Page | 210
Tran Duy Thanh https://tranduythanh.com
incircle=0
circle_center=(0,0)
circle_radius=1
c=plt.Circle(circle_center,circle_radius,ec='b',fill=False)
a=plt.axes(xlim=(-1,1),ylim=(-1,1))
a.add_patch(c)
a.set_aspect('equal')
for i in range(simCount):
# Create real number x coordinates from -1 to 1
x=random.uniform(-1.0,1.0)
# Create real y coordinates from -1 to 1
y=random.uniform(-1.0,1.0)
plt.scatter(x,y,s=2)
dot_value=x*x+y*y
# Test where the (x,y) coordinates are in the circle
if dot_value<=1:
incircle =incircle+1
print("Pi=",4*incircle/simCount)
plt.show()
Page | 211
Tran Duy Thanh https://tranduythanh.com
Pi= 3.1328
I put my code in GitHub, here is the link:
https://github.com/thanhtd32/advancedpython_part1/blob/main/Exercise34.py
Page | 212
Tran Duy Thanh https://tranduythanh.com
We want to do is to find the area of The Monte Carlo method works in the
a circle as above. following way: Place that circle inside a square
Keep in mind that the area of a square is easy to find. Now throw a point inside the
square at random, which would result in something like this:
Page | 213
Tran Duy Thanh https://tranduythanh.com
For example, in the above diagram there are 17 points in total but only 14 of the points lie
inside the circle. So, we can say that approximately 14/17 of the area inside the square is
taken by the circle.
So, in the above example, the length of the side of the square is about 6cm, so the area of
the square is 6x6 = 36cm^2, so the area of the circle is approximately 14/17 x 36 =
29.64cm^2.
How can we check if a point is inside the We find the distance of a point to the center
circle using a computer? by using Pythagoras' theorem
All codes:
#Coder: Tran Duy Thanh
#Email: thanhtd@uel.edu.vn
#Phone: 0987773061
#Blog for self-study: https://duythanhcse.wordpress.com
#Facebook for solving coding problem: https://www.facebook.com/groups/communityuni
#Description:
#These codes I improved from Exercise 34
# It can be seen that the value of pi can be obtained as a probabilistic approximation
# using the Monte Carlo simulation. Let's write a program that calculates the ratio of
# the area size of a circle with a circle radius of 1 to a circle with a circle radius
# of 2 using Monte Carlo simulation probabilistically.
# 1.use subplot to display 2 graphic of Circle
# 2.Write isPointInCircle method to check random x,y is inside the circle
# 3.Write approximateCircleArea method to calculate CircleArea by Monte Carlo sampling
# 4.Test many case to camparing the Approximate area
import math
import random
import matplotlib.pyplot as plt
Page | 214
Tran Duy Thanh https://tranduythanh.com
paths2=ax2.add_patch(c2)
ax2.set_aspect('equal')
Page | 215
Tran Duy Thanh https://tranduythanh.com
Page | 216
Tran Duy Thanh https://tranduythanh.com
Test case 3:
SimCount =1000
Page | 217
Tran Duy Thanh https://tranduythanh.com
Test case 5:
SimCount =100000
When Simcount =100000, Area of circle with radius 1 is 3.14216
Area of circle with radius 2 is 12.54912
Test case 6:
SimCount =500000
When Simcount =500000, Area of circle with radius 1 is 3.143448
Area of circle with radius 2 is 12.562016
Page | 218
Tran Duy Thanh https://tranduythanh.com
Page | 219
Tran Duy Thanh https://tranduythanh.com
40.2.5.Data
• data array for numeric images
• recognition number
40.3. Full algorithm skeleton
start
End
Page | 221
Tran Duy Thanh https://tranduythanh.com
40.4. Programming
40.4.1.Variables
• digitImage, data: a numeric array converted from a numeric image
• n: predictive digit integer
• digits: numeric data set
40.4.2.Some explanations
Use the train_test_split() function to separate training data and test data
Use imshow() to display the first 30 number images among the number images.
import sklearn.datasets
import matplotlib.pyplot as plt
import sklearn.svm
from PIL import Image
import numpy as np
from sklearn.model_selection import train_test_split
digits=sklearn.datasets.load_digits()
# If the value is set to 0, it is always separated in the same form.
x_train, x_test, y_train,y_test=train_test_split(digits.data,
digits.target,test_size=0.25, random_state=0)
for i in range(30):
plt.subplot(3,10,i+1)
plt.axis("off")
plt.title(digits.target[i])
plt.imshow(digits.images[i],cmap="Blues")
plt.show()
Take an image in png format and convert it to a NumPy numeric array
Customize the size and color depth to the image data set you want to compare
Since the original image has values from 0 to 255, convert it to values from 0 to 16
def conv_image_to_data(filename):
blackImage=Image.open(filename).convert('L')#gray scale
blackImage=blackImage.resize((8,8))
digitImage=np.asarray(blackImage,dtype=float)
digitImage=16*np.divide(blackImage,256)
digitImage=np.floor(16-digitImage)
digitImage=digitImage.flatten()
plt.imshow(blackImage,cmap="Blues")
plt.show()
print(digitImage)
return digitImage
Page | 222
Tran Duy Thanh https://tranduythanh.com
Then, recognize what number the image of the number you have written is
learning_model=sklearn.svm.SVC(gamma=0.001)
learning_model.fit(x_train,y_train)
score = learning_model.score(x_test,y_test)
print("score=",score)
data=conv_image_to_data("data_exercise36\digit-7.png")
n=learning_model.predict([data])
print("What is the predicted number?",n)
Here is the link of images to test:
https://github.com/thanhtd32/advancedpython_part1/tree/main/data_exercise36
40.4.3.Programming-the whole program
The whole program is shown as below.
#Coder: Tran Duy Thanh
#Email: thanhtd@uel.edu.vn
#Phone: 0987773061
#Blog for self-study: https://duythanhcse.wordpress.com
#Facebook for solving coding problem: https://www.facebook.com/groups/communityuni
import sklearn.datasets
import matplotlib.pyplot as plt
import sklearn.svm
from PIL import Image
import numpy as np
from sklearn.model_selection import train_test_split
digits=sklearn.datasets.load_digits()
# If the value is set to 0, it is always separated in the same form.
x_train, x_test, y_train,y_test=train_test_split(digits.data,
digits.target,test_size=0.25, random_state=0)
for i in range(30):
plt.subplot(3,10,i+1)
plt.axis("off")
plt.title(digits.target[i])
plt.imshow(digits.images[i],cmap="Blues")
plt.show()
def conv_image_to_data(filename):
blackImage=Image.open(filename).convert('L')#gray scale
blackImage=blackImage.resize((8,8))
digitImage=np.asarray(blackImage,dtype=float)
digitImage=16*np.divide(blackImage,256)
Page | 223
Tran Duy Thanh https://tranduythanh.com
digitImage=np.floor(16-digitImage)
digitImage=digitImage.flatten()
plt.imshow(blackImage,cmap="Blues")
plt.show()
print(digitImage)
return digitImage
learning_model=sklearn.svm.SVC(gamma=0.001)
learning_model.fit(x_train,y_train)
score = learning_model.score(x_test,y_test)
print("score=",score)
data=conv_image_to_data("data_exercise36\digit-7.png")
n=learning_model.predict([data])
print("What is the predicted number?",n)
score= 0.9955555555555555
Page | 224
Tran Duy Thanh https://tranduythanh.com
Page | 225
Tran Duy Thanh https://tranduythanh.com
Page | 226
Tran Duy Thanh https://tranduythanh.com
# Add Fully Connected layer with 128 nodes and use sigmoid . function
model.add(Dense(128, activation='sigmoid'))
# Output layer with 10 nodes and use softmax function to convert to probability.
model.add(Dense(10, activation='softmax'))
img_array = (img_28x28.flatten())
img_array = img_array.reshape(-1,1).T
return img_array
#call conv_image_to_data to test image digit-5.png
data=conv_image_to_data("data_exercise37\digit-1.png")
#show image into chart
plt.imshow(data.reshape(28,28), cmap='Blues')
#call predict function
Page | 227
Tran Duy Thanh https://tranduythanh.com
y_predict = model.predict(data.reshape(1,28,28,1))
#get number recognition and show into title of Chart
plt.title('Predict number is '+str(np.argmax(y_predict)))
plt.show()
Page | 228
Tran Duy Thanh https://tranduythanh.com
Page | 229
Tran Duy Thanh https://tranduythanh.com
Test case 1:
Digit number =5
Link of this number:
https://github.com/thanhtd32/advancedpython_part1/blob/main/data_exercise37/digit-
5.png
correct
Page | 230
Tran Duy Thanh https://tranduythanh.com
Test case 2:
Digit number =7
Link of this number:
https://github.com/thanhtd32/advancedpython_part1/blob/main/data_exercise37/digit-
7.png
correct
Page | 231
Tran Duy Thanh https://tranduythanh.com
Test case 3:
Digit number =2
Link of this number:
https://github.com/thanhtd32/advancedpython_part1/blob/main/data_exercise37/digit-
2.png
correct
Page | 232
Tran Duy Thanh https://tranduythanh.com
Test case 4:
Digit number =0
Link of this number:
https://github.com/thanhtd32/advancedpython_part1/blob/main/data_exercise37/digit-
0.png
correct
Page | 233
Tran Duy Thanh https://tranduythanh.com
Test case 5:
Digit number =9
Link of this number:
https://github.com/thanhtd32/advancedpython_part1/blob/main/data_exercise37/digit-
9.png
correct
Page | 234
Tran Duy Thanh https://tranduythanh.com
Test case 6:
Digit number =1
Link of this number:
https://github.com/thanhtd32/advancedpython_part1/blob/main/data_exercise37/digit-
1.png
Correct
Page | 235
Tran Duy Thanh https://tranduythanh.com
Test case 7:
Digit number =8
Link of this number:
https://github.com/thanhtd32/advancedpython_part1/blob/main/data_exercise37/digit-
8.png
wrong
Page | 236
Tran Duy Thanh https://tranduythanh.com
Test case 8:
Digit number =3
Link of this number:
https://github.com/thanhtd32/advancedpython_part1/blob/main/data_exercise37/digit-
3.png
Correct
Page | 237
Tran Duy Thanh https://tranduythanh.com
Test case 9:
Digit number =4
Link of this number:
https://github.com/thanhtd32/advancedpython_part1/blob/main/data_exercise37/digit-
4.png
wrong
Page | 238
Tran Duy Thanh https://tranduythanh.com
Page | 239