Solving Problems With Python
Solving Problems With Python
E-mail: daniel.zahumenicky@gmail.com
All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in any
form or by any means, including photocopying, recording, or other electronic or mechanical
methods, without the prior written permission of the publisher, except in the case of brief quotations
embodied in critical reviews and certain other noncommercial uses permitted by copyright law.
For permission requests, write to the publisher at peter.kucera@gmail.com or via
www.creatingwithpython.com.
Ordering Information:
Quantity sales. Special discounts are available on quantity purchases by corporations, associations,
schools, and others. For details, contact the publisher at peter.kucera@gmail.com or via
www.creatingwithpython.com.
3
Content
Content
Introduction
About this Collection of Exercises and the Informatics Maturita Exam
Table of Tasks
Tasks
1. Baby Snake
2. Baby Snake - Game Report
3. Display on a Tram
4. Weather Station Logs
5. Ordered Meals
6. Musical Notes
7. Random Order for Oral Exams
8. Find the Cracked Plate
9. Boat Race
10. Creation of a Crossword Puzzle 1
11. Foot Race
12. Extent of Public Transport Utilization
13. Glutton
14. Long Jump
15. Easy-to-Read Parentheses
16. Names in Columns
17. The Secret Table
18. Drawing Robot 1
19. Image Reflection
20. Table of Frequency
21. Scrambled Text 1
22. Scrambled text 2
23. Ciphertext 1
24. Ciphertext 2
25. Lottery
26. Landscape
27. Virus
28. Voting 1
29. Image compression
30. NIM
31. Black and White Picture
32. File Conversion 1
33. Color Tone Spectrum
34. Image Decompression
35. Compressed Image Drawing
36. Creation of a Crossword Puzzle 2
37. Voting 2
38. Customer Satisfaction 1
39. Customer Satisfaction 2
40. Data Analysis
41. Ordering Food
42. Save the Falling Egg
43. Pyrotechnician
44. Guess the Falling Word
45. Vocabulary Learning
46. Hangman
47. Barcode
48. Multiplication
49. Seat Reservation System
4
50. Image Contour
51. Announcement Compression 1
52. Announcement Compression 2
53. Skyline
54. Boats
55. Drawing Robot 2
56. Level Editor 1
57. Level Editor 2
58. Subway Line
59. Bus Capacity Analysis
60. Calculator
61. Division
62. Survey
63. Transit Research
64. Seating Chart
Solutions
Bibliography
5
Introduction
Malcolm Gladwell says in his book Outliers that if you want to achieve success in a particular area, you have to
endure 10,000 hours of practice in that field. The author uses this rule to show that talent alone is not enough,
or even necessary, to achieve success. What is necessary, however, is a great amount of effort and systematic
training. Some psychologists dismiss this idea.
Whether this claim is true or not, we believe that practice helps us get better in a particular area. We hope that
these 64 exercises will help you improve your programming skills and gain the useful practice that will be
appreciated not only by the Maturita committee, but also by your future self in your further studies or work.
If you have ever been so engulfed in programming that you forgot about the flow of time and everything
around you, felt no hunger, thirst or exhaustion, you achieved flow. Psychologist Mihaly Csikszentmihalyi was
the first to name and define flow.
An important prerequisite for achieving flow is that the level of difficulty of a given task be adequate to one's
skills. When our skills develop at the same time as our tasks' level of difficulty rises, we start to feel passionate
and get a sense of meaningfulness - also called experiencing flow.
It is not necessary for you to solve all of these exercises or solve them in their presented order. Choose your
exercises in such a way that you enjoy solving them, ensuring that they pose a reasonable challenge for you,
and you can enjoy programming :)
We wish you an enjoyable time solving these exercises and hopefully achieving flow and also amazing results at
your Maturita exam.
You can download the text files and images you will need when solving the exercises
here: https://bit.ly/2WNk5gi
6
About this Collection of Exercises and the Informatics
Maturita Exam
How does the Maturita exam work?
The informatics Maturita exam consists of an oral exam in front of a three-member Maturita committee. The
student draws one of the approved Maturita tasks, which involves two exercises, one from programming and
the second from the principles of informatics. The student gets a total of 30 minutes to prepare for the two
exercises; the time the student spends on the individual exercises is completely up to the student. The
preparation time is followed by a 20-minute oral exam.
In this e-book you will find exercises that meet the criteria for the first half of each of the Maturita tasks (the
programming exercise).
Everything students are supposed to know for the Maturita exam is specified in the Cieľové požiadavky na
vedomosti a zručnosti maturantov z informatiky, which you can find on the web page of the National Institute
of Education (www.statpedu.sk).
At the beginning of the e-book, you can find a summary of the exercises along with the symbols for the
approaches that may be necessary to solve them.
We recommend you keep track of your progress in tabs, where you can record the date you solved the
exercise, the total time it took you as well as your own notes. From the log in your tracker, you should see that
the time you need to solve each individual exercise is gradually shortening, meaning you are getting much-
needed practice. It may also be useful to spend class time solving these exercises. You can have one shared
tracker as a class (for example, using Google Drive) where every student keeps track of their own progress (in
their own three columns). This way you can estimate the time needed to solve a particular exercise based on
the time it took your classmates to do so or you can compare your times with your classmates.
7
Structure of the exercises
The first part of the Maturita task (the programming part) is supposed to have a clear objective the student is
supposed to achieve by creating a program in a particular programming language. The means of achieving the
objective are not supposed to be given to the student. It is the responsibility of the student to choose the
means; whether the choice was the most effective and convenient is included in the assessment. This means
that it should not be revealed whether the solution requires a loop, and if so which type of a loop, and also
which type of a variable or data structure should be included in the neatest solution.
The exercises are structured in the form of bullet points representing smaller tasks (or particular attributes of
the program). Often, the smaller tasks in the bullet points get gradually harder and represent the steps in which
to solve the exercise. This structure is created to help even slightly less-skilled students at least partially solve
the exercise. For instance, the first bullet point in an exercise in which a text file needs to be read may be to
read and print the first line. By correctly executing this, the student shows that he or she can at least correctly
upload a text file as input for the program and read its first line. However, the smaller task in the next bullet
point may require reading and handling of the whole file. In some cases the first bullet point describes a smaller
segment of the task in the next bullet point. In these cases, successful execution of the more difficult (second)
task is sufficient and also shows that the student is capable of solving the basic (previous) task (which is
designed to lead students who are unable to solve the more difficult task step by step to a solution).
8
Table of All Tasks
1. Baby Snake________________________________[], Cnv, aft.
2. Baby Snake - Game Report__________________'', txt, fx()
3. Display on a Tram_________________________'', [], txt, Cnv, fx(), aft.
4. Weather Station Logs______________________'', (), [], txt
5. Ordered Meals_____________________________'', {}, txt
6. Musical Notes_____________________________'', txt, Cnv, fx(), aft.
7. Random Order for Oral Exams_______________'', []
8. Find the Cracked Plate____________________'', [], Cnv, fx()
9. Boat Race_________________________________'', [], Cnv, fx()
10. Creation of a Crossword Puzzle 1_________'', (), [], txt, Cnv, fx()
11. Foot Race________________________________(), [], txt
12. Extent of Public Transport Utilization___'', [], txt
13. Glutton__________________________________'', (), [], Cnv
14. Long Jump________________________________(), [], {}, txt
15. Easy-to-Read Parentheses_________________'', [], Cnv
16. Names in Columns_________________________'', [], txt
17. The Secret Table_________________________'', []
18. Drawing Robot 1__________________________'', [], Cnv
19. Image Reflection_________________________'', [], [[]], txt, Cnv
20. Table of Frequency_______________________'', [], txt
21. Scrambled Text 1_________________________'', [], txt
22. Scrambled text 2_________________________'', [], txt
23. Ciphertext 1_____________________________'', txt, fx()
24. Ciphertext 2_____________________________'', txt, fx()
25. Lottery__________________________________'', [], txt, fx()
26. Landscape________________________________[], Cnv, fx()
27. Virus____________________________________'', [], txt, fx()
28. Voting 1_________________________________'', (), [], txt
29. Image compression________________________'', txt, fx()
30. NIM______________________________________'', Cnv, fx()
31. Black and White Picture__________________'', txt, Cnv, fx()
32. File Conversion 1________________________'', txt, fx()
33. Color Tone Spectrum______________________'', [], txt, Cnv
34. Image Decompression______________________'', [], txt, fx()
35. Compressed Image Drawing_________________[], txt, Cnv, fx()
36. Creation of a Crossword Puzzle 2_________'', (), [], txt, Cnv, fx()
37. Voting 2_________________________________'', [], txt
38. Customer Satisfaction 1__________________'', [], txt
39. Customer Satisfaction 2__________________'', [], txt
40. Data Analysis____________________________'', [], txt
41. Ordering Food____________________________'', [], txt, Cnv
42. Save the Falling Egg_____________________'', Cnv, fx(), aft.
43. Pyrotechnician___________________________[], Cnv, fx(), aft.
44. Guess the Falling Word___________________'', Cnv, fx(), aft.
45. Vocabulary Learning______________________'', [], txt
46. Hangman__________________________________'', [], txt
47. Barcode__________________________________'', txt, Cnv, fx()
48. Multiplication___________________________'', (), [], txt, fx()
49. Seat Reservation System__________________'', [], txt, Cnv, fx()
50. Image Contour____________________________txt, Cnv
51. Announcement Compression 1_______________'', []
52. Announcement Compression 2_______________'', []
53. Skyline__________________________________[], txt, Cnv
54. Boats____________________________________[[]], txt, Cnv, fx()
55. Drawing Robot 2__________________________'', [], txt, Cnv, fx()
56. Level Editor 1___________________________[], txt, Cnv, fx()
57. Level Editor 2___________________________[], Cnv, fx()
58. Subway Line______________________________'', [], txt, Cnv
59. Bus Capacity Analysis____________________'', [], txt, Cnv, fx()
60. Calculator_______________________________'', Cnv, fx()
9
61. Division_________________________________'', (), Cnv, fx()
62. Survey___________________________________'', [], txt, Cnv, fx()
63. Transit Research_________________________(), [], txt
64. Seating Chart____________________________'', (), [], txt, Cnv, fx()
10
29. Image compression________________________'', txt, fx()
32. File Conversion 1________________________'', txt, fx()
34. Image Decompression______________________'', [], txt, fx()
37. Voting 2_________________________________'', [], txt
38. Customer Satisfaction 1__________________'', [], txt
39. Customer Satisfaction 2__________________'', [], txt
40. Data Analysis____________________________'', [], txt
45. Vocabulary Learning______________________'', [], txt
46. Hangman__________________________________'', [], txt
48. Multiplication___________________________'', (), [], txt, fx()
51. Announcement Compression 1_______________'', []
52. Announcement Compression 2_______________'', []
63. Transit Research_________________________(), [], txt
11
1 Baby Snake
Create a game called "Baby Snake".
The size of the baby snake's head is one point. The baby snake is constantly moving in a given
direction and leaves behind a trail in form of a line. At the beginning the baby snake is heading north.
We control the heading of the baby snake using our keyboard (or buttons). The game recognizes four
primary headings (up, down, right, left).
The game is over once the baby snake hits itself (i.e., the line it has left behind).
These are two examples of what a situation in which the game is over may look like:
Tasks:
1. How do we figure out whether the baby snake has hit itself?
2. What happens when the player changes the heading by 180 degrees (the baby snake turns fully
around)?
solution
UUUUDDDDDDLLLLLLLDU
UUUUUUUUUUUUUUUUUULLLLLLLLLLLLLLLLLDDDDDDDDDDDDDDDRRRRRRRR
UUUUUUUUUUULLLLLLLLLLLLLLLLLDDDDDDDDDDDDDDDRRRRRRRR
12
the copy will be a compressed version in which a method representing the repeated characters will be
used. For instance, instead of the sequence UUUUDDDDDDLLLLLLLDUU, the copy will consist of the
sequence U 4 D 6 L 7 D 1 U 2.
Tasks:
solution
3 Display on a Tram
The names of the stops of a tram line are in a text file called stops.txt. The name of each stop is on its
own line. Every morning the tram's on-board computer loads the current text file into its memory and
shows the names of the stops on a single-line twenty-character display. Create a program that will
simulate the operation of the tram's on-board computer so that:
An example of the display and what it looks like when the name of a stop is being scrolled:
Tasks:
1. Which fonts are convenient to use when we want our display to be exactly 20 characters long?
2. What changes would need to be made in the program if the tram drove the other way around (the
original last stop would instead be the first) and we continued to use the same text file?
solution
13
Create a program that will:
Tasks:
1. Some of the inputted data is in a format that is not very convenient for processing in Python. Which
data is that and how can we change its format without editing the inputted file?
solution
5 Ordered Meals
Data about the meals ordered for the next day by student diners in a school cafeteria is saved in a text file
called ordered_meals.txt. Each line consists solely of data related to a single diner's choice. The line
includes the diner's numerical code, a space and the chosen meal. Every meal is assigned a color and the
choice of the meal is recorded in the form of a symbol representing one of these assigned colors (g - green,
r - red, b - blue, o - orange). Create a program that will:
use the text file to determine the total number of meals ordered,
count the number of individual meal choices and print the findings (the number of meals ordered for
each color),
determine whether there is a meal (or meals) ordered less than twenty times and if so, print its
assigned color,
notify us when enough diners have ordered each of the meal options.
142 o
362 r
368 r
289 b
356 r
70 o
147 g
96 g
Tasks:
1. What would your program do if the inputted file totally lacks one of the meal options (nobody
ordered that particular meal)?
2. How would you need to modify your program so that it would be able to handle more meal options
(in case the menu is expanded)?
solution
6 Musical Notes
Create a program that will write whole musical notes on a musical staff, in these steps:
14
the program will read and place on the musical staff the first note from the text file notes.txt
, which consists of one line with a sequence of notes (only the notes C, D, E, F, G, A, and Bb (H) are
used),
the program gradually reads and places all of the notes from the text file onto the staff,
if all the notes do not fit on one staff, a new staff will be drawn below the previous one and the
sequence of notes will continue there.
cdefgahcdahdecdefgahhagfdec
Hint:
The symbol depicting a whole note is an empty oval without a stem (a vertical line). In a musical scale, the
tones are in the following order: C D E F G A Bb (H). The difference between two tones (an interval) is half
the distance between two lines in the staff. The tone C will be written on the second position below the
lowest line of the staff (in our exercise you can write it without the ledger line usually used to represent
lines below the staff).
Tasks:
1. What needs to be done for the program to be as flexible as possible, for example, in regard to
changes of the width of the graphical canvas?
2. What are some of the ways that allow us to determine the pitch of a note (its placement on the staff)
based on its name? Which of the possible solutions are more convenient? Justify your answer.
solution
it creates a random order in which the students have their oral exams,
15
it randomly assigns every student the number of the question they will have on their oral exam,
each question can be assigned only once (to one student),
the user can input the number of questions and the number of students in the class. The program
checks whether the number of questions is greater than the number of students and in case it is not,
it notifies the user,
due to the possible overlapping of topics in the questions, the even- and odd-numbered questions
have to alternate every time (two students having an oral exams one after the other cannot both
have an odd- or even-numbered question. Add this feature to the final program so that it can be
easily commented out (only this particular part of the program) and not used.
solution
Tasks:
1. How do we ensure that the program will not fail if a player clicks outside the range of drawn plates in
case the graphical canvas is bigger?
solution
16
9 Boat Race
Create a program simulating a boat race. You can find the function boat(x, y) in the file 09_boat.py.
This function draws a boat with randomly taut sails in the spot corresponding to the coordinates given in
the argument. You will use this function in the program; it cannot be modified.
There are 15 boats drawn on the left side of the screen. They are all placed on a vertical line (the
starting line).
There is a red finish line drawn on the right side.
With a click, the animation of the boats sailing begins. All the boats move at the same time to the
right, but every time each of the boats moves by a random number of points in the range of 1 to 10.
The function boat creates an animation of the boats' sails moving.
The game is over as soon as one of the boats reaches the finish line.
After the game has finished, the starting number of the winning boat is displayed on the screen.
Tasks:
1. How do we ensure that the pace of the race does not quicken with multiple clicks?
2. How do we ensure that the race finishes once the first boat has crossed the finish line?
3. What needs to be modified in the program so that all the boats can finish the race?
4. What happens when two boats cross the finish line at the same time? Can that even happen?
solution
17
10 Creation of a Crossword Puzzle 1
Create a program that creates a crossword puzzle based on the inputted file. You may use the text files
crossword1-1.txt and crossword1-2.txt. One line in the text file represents one row in the
crossword puzzle. Every line in the text file starts with a number representing which character of the text is
included in the solution of the crossword puzzle. For instance, '3 OPEN' means that there is a row with
the text 'OPEN' in the crossword puzzle and also that the third character of this text is part of the
crossword puzzle's solution.
An example of the text file:
1 CANVAS
2 TRUE
3 OPEN
2 RANGE
5 FUNCTION
3 WHILE
4 PRINT
6 STRING
the program loads the contents of the text file into memory,
the program includes a function that creates a crossword puzzle in a given position and with the given
size of one square,
the squares containing the crossword puzzle's solution are filled with a mute color and are lined up in
one column,
we can use a function that draws the crossword puzzle to create an empty and a completed puzzle
next to each other.
solution
11 Foot Race
Many athletes took place in a running competition. The officials had purchased a system that could
automatically identify every athlete that crossed the finish line and record his or her time in seconds. These
results have been saved in the text file foot_race.txt. Each line consists of the last name of an athlete
(one word) and their recorded time in seconds.
Peterson 272
Koloman 233
Amundsen 272
18
print the number of athletes in the following format:
Number of competitors: 32
print the list of athletes and their accomplishments in a straightforward manner:
Athlete Peterson reached the finish line in 272 seconds
Athlete Koloman reached the finish line in 232 seconds
...
print the name of the fastest competitor (you can assume that there will always be just one winner),
add to that name the time of the fastest runner in the following format: "3 min. 53 sec.".
solution
the first line consists of one number representing the capacity of the bus (max possible quantity of
passengers)
all other lines consist of the number of people getting on and off the bus at each particular stop along
with the name of the stop. All this is separated by spaces.
50
20 0 Oxford Circus Stn
35 0 Piccadilly Circus
10 20 Charles II Street
40 20 Trafalgar Sq
determine and print the number of stops on the particular bus line,
print the names of the stops - the names are one, two or three words long and will be printed in one
line and separated by commas,
print the names of the stops where the bus was far too full after passengers got on (the number of
passengers exceeded the allowed capacity),
print the highest number of passengers over the capacity in cases when the capacity of the bus was
exceeded somewhere on the route.
Tasks:
1. What possible mistakes are we able to uncover in the file using the program (assuming that the
format of the inputted file is correct)?
2. What modifications would the program need if the names of the stops in the inputted file came
before the numbers representing the quantity of passengers getting on and off the bus?
solution
19
13 Glutton
Create a game called "Glutton". There is a bug named Glutton moving across the screen. We can control
his heading with the keys w, s, a and d, and he eats apples that are placed on the screen. Glutton's size
does not change after he eats an apple.
Glutton (a blue circle) is drawn in the top left corner of the screen.
Apples (N red circles, where N is a constant inputted to the program by the player) are randomly
drawn on the screen. The apples can overlap but they have to be placed fully on the canvas and
cannot overlap with Glutton in his starting position.
At the start of the game, Glutton constantly moves to the right.
Glutton's heading (up, down, right, left) can easily be changed anytime by pressing one of the
following keys: w s a d.
When Glutton comes across an apple, he eats it (the apple disappears). When Glutton has eaten all of
the apples, the game ends and the player is awarded a congratulatory message.
solution
14 Long Jump
An international sports organization organized a worldwide amateur long jump competition. Every
competitor had five attempts. The winner was the competitor who had jumped the longest distance in one
of their five attempts.
The results of all the athletes taking part were made into one text file long_jump.txt. Each line of the
text file is in the following format:
Name country_code attempt1 attempt2 attempt3 attempt4 attempt5
A competitor's name is made up of one word only (it does not include spaces), the country code consists of
three capitalized letters of the English alphabet and the attempts are whole numbers (separated by
spaces).
An example of the inputted file:
solution
20
15 Easy-to-Read Parentheses
In both math and programming, we often come across expressions with parentheses. When there are
multiple parentheses, it often becomes quite hard to read - we do not know where a particular set of
parentheses starts and ends. Create a program that will rewrite an inputted entry so that the new version
displays each set of parentheses belonging together in the same color. Apart from the parentheses, the
entry may consist of various characters. The program does not work with brackets or braces.
Features of the program:
It loads the inputted expression with parentheses from the entry and prints it to the graphic canvas.
It informs the user whether the parentheses in the expression are placed correctly.
Two conditions must be met for the parentheses to be correctly placed:
1. every left parenthesis has exactly one corresponding right parenthesis,
2. the right parenthesis always comes after its corresponding left parenthesis,
For example, ((xx)y(xx)) has correctly placed parentheses and (aa))bb( has incorrectly placed
parentheses.
When the parentheses in the expression are correctly placed, the program displays sets of
parentheses belonging together in the same color. You can assume that you will not need more than
7 different colors.
solution
16 Names in Columns
Create a program that reorganizes the names of employees in a company database. The program rewrites
the inputted file into a two column table that is easier to read. In this new table, there are first (and middle)
names at the beginning of each line. Last names are on the same line as their respective first (and middle)
names, but they are all aligned to the left using spaces (as you can see in the example of the final file
below). The first half of the list of employees in the text file employees_names.txt consists solely of
first names (one name - it may also include a middle name, in each line) and the second half consists solely
of the corresponding last names (the order of the first and last names is kept unchanged).
Mary Ann
Andrew
Jean Michael
Phillippe
Novak
Great
Portree
de Ryannitto
21
Mary Ann Novak
Andrew Great
Jean Michael Portree
Phillippe de Ryannitto
Tasks:
1. How would we need to modify the program if we wanted to determine the individual lengths of both
the first name and the middle name of an employee (assuming he or she has both of those names)?
solution
load a sentence from the entry (we can assume that the user inputs only capitalized letters and
spaces), encode the sentence using the Secret Table's system and print the encoded sentence on the
screen,
determine and print information regarding the most frequently used cell number in any particular
encoded sentence,
in case there are multiple cell numbers used most frequently, it prints all of the numbers.
Tasks:
1. How can we deal with the inputted sentence when it also contains characters other than capitalized
letters and spaces?
2. When we compare the lengths of the plaintext and the encoded text, what relation do we find
between them?
3. Do we need the numbers in the encoded text to be separated by spaces?
solution
22
18 Drawing Robot 1
A Drawing Robot obeys commands given to it by the user and draws images in compliance with them. The
robot recognizes its position and its heading (only up / down / left / right).
The robot recognizes the following commands:
line <length> - draws a line of the according length, e.g. line 50 and moves to the end of this line,
left – turns 90 degrees to the left (without drawing anything),
right – turns 90 degrees to the right (without drawing anything).
Create a program that simulates the Drawing Robot. The robot moves on the canvas and executes the
commands it gets from the user. The robot itself is not displayed on the canvas. At the beginning of the
program, the robot is placed in the middle of the canvas and its heading is up. Commands are inputted by
the user in the widget entry and are executed on the press of the button Do.
The program also has these features:
it is possible to use the command line <length> the robot draws a line heading up,
it is possible to use the command left the next line is drawn in the given direction,
it is possible to use the command right.
line 50
right
line 30
left
line 50
left
line 100
it draws:
solution
19 Image Reflection
A black-and-white image is recorded in the file image_reflection.txt. In the first line of the file, the
proportions of the image are recorded - the first number represents the width of the image (the number of
pixels in a row) and the second number represents the height (the number of pixels in a column). Every row
of the image is recorded in an individual line of the text file. These lines come one after another
immediately after the first line with the proportions. Each consists of the numbers 0 and 1, where 0
represents white and 1 represents black in that particular pixel of the image. The numbers are separated by
spaces.
An example of the text file:
23
8 5
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1 0 1
print the total number of pixels in an image and the number of ones (1),
draw the given image on the screen; every pixel will be represented by a small square. Set the size of
the squares in your program using the variable side.
draw the original image reflected over the y-axis after a button is pressed.
Tasks:
1. What would change in the solution if zeros were to represent the color black and ones white?
2. What format would you suggest for the text file to save some storage space?
3. What would change in the program if the numbers 0 and 1 in the inputted text file were not separated
by spaces but came immediately one after another?
solution
20 Table of Frequency
When decoding ciphers, sometimes it is helpful to conduct a frequency analysis. This means that we start
by determining how often letters occur in the ciphertext, which can help us to crack the cipher. Create a
program that analyzes the text saved in the file frequency_table.txt and conducts a frequency
analysis of the characters in these steps:
the program displays the text of the text file on the screen,
the program prints the frequencies of occurrence of letters of the English alphabet in the following
format: letter - frequency; whether the letter is upper- or lower-case makes no difference, characters
other than letters are ignored by the program,
the program puts together a list of characters that have not occurred in the text at all.
THE COMMISSION
Article 1
The Commission shall act collectively in accordance with these Rules
and in compliance with the political guidelines laid down by
the President.
24
Article 2
In compliance with the political guidelines laid down by the President,
the Commission shall establish its priorities and each year adopt its
work programme.
solution
21 Scrambled Text 1
A study has discovered an interesting finding. Humans are able to read words even when the letters are not
in the correct order. This is caused by the fact that our brain considers each word as one united entity
instead of reading letter by letter. It is enough when the first and last letters are placed properly according
to the normal word we are used to. This phenomena is what we call Scrambled Text (http://www.mrc-
cbu.cam.ac.uk/~mattd/Cmabrigde/).
In the text file scrambled_text1_input.txt, you can find the file for input. Create a program that
will:
Tasks:
1. How would the solution be impacted if the text included letters that are not in the English alphabet?
2. Which words will not seem to be scrambled in the outputted text?
solution
25
22 Scrambled text 2
A study has discovered an interesting finding. Humans are able to read words even when the letters are not
in the correct order. This is caused by the fact that our brain considers each word as one united
entity instead of reading letter by letter. It is enough when the first and last letters are placed properly
according to the normal word we are used to. This phenomena is what we call Scrambled Text
(http://www.mrc-cbu.cam.ac.uk/~mattd/Cmabrigde/).
In the text file scrambled_text_input2.txt, you can find the file for input.
Program 22_scramble.py consists of a function that returns a randomly scrambled text string. You can
see the function below:
import random
def string_shuffle(string):
letters = list(string)
random.shuffle(letters)
return ''.join(letters)
Tasks:
solution
26
23 Ciphertext 1
Create a program that encodes / decodes text files in the following manner:
The program loads a cipher key from the user. The key is in the form of a word consisting of lower-
case letters of the English alphabet.
The program loads a text string from the user. The inputted text string is encoded by the program.
The program is able to encode only lower-case letters of the English alphabet. Every character is
encoded by a shift in the lower-case alphabet; the magnitude of the shift is defined by the cipher key
(by a particular letter in the cipher key). For instance, the letter c in the key means a shift of the
corresponding inputted letter by position c - by 3 characters. The next letter is encoded with the shift
corresponding to the next character in the key. In cases when the shift is longer than the number of
letters left in the alphabet, the shift continues to the first letters of the alphabet.
input: creating with python
key: abc
repeated key: abcabcabcabcabcabcab
shift: 12312312-1231-312312
output: dthbvloi xkwi szvkpp
The program goes through individual lines of the text file and encodes every one of them (getting a
cipher key from the user every time). In each line the program encodes only the lower-case letters of
the English alphabet. The encoded text is saved in a text file.
The program finds whether the text in the file needs to be encoded or decoded out from the user,
gets the cipher key and encodes / decodes the given text, saving it into the final outputted file.
You can find the original plain text for input in the file inputted_text.txt. The cifertext abc is in the
file cifertext_1.txt together with the key.
Tasks:
1. What differences and similarities are there between encoding and decoding?
2. Why is it possible that letters that are the same in the plaintext are encoded as different letters in the
ciphertext?
3. What happens when the cipher key is longer than the inputted text string?
4. Can we get different ciphertext output when working with the same cipher key? Explain why you
think so.
solution
27
24 Ciphertext 2
Create a program that encodes / decodes text files in the following manner:
You can find the original plain text for input in the file inputted_text.txt. The cifertext is in the file
cifertext_2.txt.
An example of the inputted plaintext:
Tasks:
1. What differences and similarities are there between encoding and decoding?
2. Why is it possible that letters that are the same in the plaintext are encoded as different letters in the
ciphertext?
3. What will the size of the inputted file be in comparison to the outputted file?
4. Is it possible to get different outputted files when the program is executed multiple times? Explain
why you think so.
solution
25 Lottery
Create a program that simulates a lotto. In this lotto 6 numbers are drawn from a basket containing the
numbers 1 through 49. Create a program that will:
read a bet on the six winning numbers made by the user. The user inputs the numbers into one input
line and separates them by spaces,
simulate the lotto and print the 6 winning numbers that were drawn,
compare the winning numbers with the bet the user made, print the coinciding numbers and their
quantity (how many numbers the user managed to get right),
compare the winning numbers with the bets of all the participants in the lottery. The bets are saved in
the text file lottery_2.txt (bets of fewer participants can be found in file lottery_1.txt).
Every line consists of 6 numbers separated by spaces. Each line represents one participant's single
28
bet,
print the number of participants that correctly guessed exactly one number, exactly two numbers,
exactly three numbers and so on.
32 49 38 11 13 15
40 48 36 27 43 26
8 31 2 40 48 42
19 25 4 12 3 46
20 30 42 43 35 48
21 41 25 32 6 4
40 13 33 29 1 46
Tasks:
1. Is it possible to compare the bets with the winning numbers without ordering the numbers?
2. How do we ensure that the numbers drawn do not repeat?
solution
29
26 Landscape
With this program we can generate and draw a random landscape. Create a program which:
generates data for the mountain by randomly setting the x coordinate of the vertex and y coordinate
of the mountain's initial height. For the mountain, it applies that the height before the vertex (the first
part) does not decrease, and does not increase after the vertex. Changes in the mountain's surface
can be made every 10 pixels and are random to the previous height level.
draws the mountain using the command canvas.create_polygon(). The color of the mountain
is a random tone of green.
randomly decides whether to draw a mountain or a valley (whether it's first non-decreasing and then
non-increasing or vice versa) and draws one mountain or one valley.
repeatedly draws more random mountains / valleys which create the generated landscape,
draws a new series of random mountains and valleys after pressing space.
Questions:
1. Design a text file format for saving the data of the drawn and generated landscape.
2. Is it possible to estimate how many mountains (resp. valleys) were generated by the program? Justify
your answer.
solution
27 Virus
Andrea has a virus on her computer. The virus changes the content of text files. Sometimes it changes the
order of lines in the file and sometimes it changes the order of words in a line and sometimes it also turns
words around (writes it from back to front). To simplify the solution, we will count everything between two
spaces as a word (or text in the front and in the back of a line).
Create a program which:
30
decides for every line whether to change the order of words in a line and eventually does so,
decides for every word whether to turn it around. If it decided so, it does so.
saves the transformed text to the text file virus_output.txt.
On a quiet road next to the busy Bordeaux beltway, a huddle of policemen watch
as a drone climbs into the sky to fix its glass eye on the main road.
On the ground, police captain Pascal Gensous scrutinizes the images
it sends down to the monitor.
beltway, policemen to On a txen fo road huddle the watch quiet a ysub xuaedroB
On the ,dnuorg ecilop niatpac Pascal Gensous seziniturcs eht segami
monitor sdnes it down to the
sa a enord sbmilc otni eht sky to xif its ssalg eye on the niam .daor
Questions:
solution
28 Voting 1
In the text file voting_1.txt (there is also voting_2.txt at your disposal), the progress of reality
show viewers' text message voting is saved. Every line contains exactly one phone number to which text
messages are delivered. Viewers can vote for participants whose numbers are in the range from 5220 to
5229. In the text file voting_droppedout.txt, there is a list of participants who have dropped out (their
voting numbers are each on a separate line).
Example of a section in the input text file voting_1.txt:
5225
5227
5225
5224
5225
5227
5224
5224
5227
5224
31
Questions:
solution
29 Image compression
In the file image_compression_1.txt, a black and white image is saved (there are also these files at
your disposal: image_compression_2.txt a image_compression_3.txt). The first line of the file
contains the image resolution - the first number represents the width of the image (number of pixels in a
row) and the second number represents its height (number of pixels in a column). Each row of the image is
written in a separate line in the text file. These lines follow after the first line with the image's resolution.
Each line of the image is written using the numbers 0 and 1, where 0 represents the color black and 1
white. Numbers aren't separated by anything.
Create a program which compresses the program output made of zeros and ones. This program is going to
have these properties:
Reads and prints the width and height of the image and number of all the pixels from the file.
Reads the first line of the image and sends it to the function process_line() for processing.
Contains the function process_line()which creates an output string from the order of zeros and
ones. In the output, successive zeros and successive ones are replaced by their amount. At the
beginning of the input string, there will be the amount of zeros. If the input string begins with ones,
there will be a 0, expressing zero 0s at the beginning of the input string.
Reads all the file's lines and transforms them with the help of the function process_line() and
creates a new text file named image_compression_output.txt. The size of the image will also
be saved in the first line of the output file.
20 5
11100110000000011111
00111010001111111100
11111111111111111111
00000000000000000000
00000001111100000111
20 5
0 3 2 2 8 5
2 3 1 1 3 8 2
0 20
20
7 5 5 3
Questions:
1. For what kind of line is there going to be only one number in the output file?
2. What kind of lines are going to have more than one number in the output file?
3. What's the longest line possible going to look like?
4. What image (with the same amount of dots) is going to have the shortest output file?
solution
32
30 NIM
In the game of NIM, there are two players who take turns removing one, two, or three matches. The player
who removes the last match wins. In the source code 30_task.py, you will find a function for drawing
matches.
Program for drawing matches:
In your solution use this program and modify it so that it has these properties:
There are 15 matches drawn on the screen next to each other and their number is shown,
the program prompts players in turn to input an amount of matches to be removed,
by pressing the keys 1, 2, or 3 on the keyboard, a player can select an amount of matches to be
removed,
the screen updates the number of matches shown and number of matches remaining after each turn,
the player who removes the last match wins and the program congratulates him.
Questions:
1. What happens if there are only 2 matches left in the game and a player tries to remove 3?
2. How do we ensure that we can't remove any more matches after the congratulatory message is
printed?
solution
20 5
33
ffa315070300aa0000000000000000ffffffffff
00000000000000000000afbfcfdfef0000000000
0000000000ffffffffff0000000000ffffffffff
ffffffffff0000000000ffffffffff000000ffff
00102030405060708090a0b0c0d0e0f0001f2f3f
reads the resolution of the picture from the file and based on that sets the size of the canvas,
reads the first line of the picture and draws it on the canvas by drawing a rectangle with a 1x1 pixel
size in the color of the line in the file (tones of gray),
draws the whole picture on the canvas based on the data in the file. The program shouldn't burden
the computer memory and instead read all the data right from the file and draw it,
after pressing the button Only black and white, the program will draw the picture using only
black and white pixels. The program will calculate the color based on the tone of gray - determine
whether it is in the upper or lower half of the gray scale.
Examples of the depiction of individual text files and consecutive transformation of the picture to black
and white only:
Questions:
1. How would the size of the input file change if the individual pixel colors were separated by space?
2. Evaluate whether it is more appropriate to use hexadecimal- or decimal-based numbers in text files
like these.
3. How do we figure out the number of the darkest color used?
solution
34
32 File Conversion 1
In the file bw_picture_1.txt, there is an encoded black and white picture (these files are also at your
disposal: bw_picture_2.txt a bw_picture_3.txt). The resolution of the image is in the first line -
the first number represents the picture's width (the number of pixels in a row) and the second number
represents the picture's height (the number of pixels in a column). Each row of the image is written in a
separate line in the text file. These lines follow after the first line with the image's resolution. In the picture
line, pixel colors (gray color tones) are saved. The color of one pixel is written using a two-digit number in
hexadecimal base, so numbers from 00 to ff. The color number expresses the tone of gray (let's remind
ourselves that tones of gray have the same values of red, green, and blue in the RGB model). Colors
representing pixels are not divided by anything (they follow right after one another).
Example of the text file's format:
20 5
ffa315070300aa0000000000000000ffffffffff
00000000000000000000afbfcfdfef0000000000
0000000000ffffffffff0000000000ffffffffff
ffffffffff0000000000ffffffffff000000ffff
00102030405060708090a0b0c0d0e0f0001f2f3f
reads and prints the width and height of an image and the amount of all its pixels from a file,
reads the first line of the image and sends it to the function process_line() for processing,
contains the function process_line() which produces output in the form of a string of 0s and 1s
from a text string of the sequence of gray tones. The output will contain 0s and 1s separated by
spaces. Hexadecimal-based numbers in the first half (darker colors) will transform to zeros and
numbers in the upper half will transform to ones.
reads all the lines in the file and transforms them with the help of the function process_line()
and creates a new text file named file_conversion_1_output.txt. The image resolution will
also be written in the first line of the output file.
20 5
1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0
Questions:
1. How drastically would the size of the input file change if the individual pixel colors were separated by,
for example, a space?
2. Evaluate whether it is more appropriate to use hexadecimal- or decimal-based numbers in text files
like these.
3. How do we figure out the number of the darkest color used?
4. What is the relationship between the sizes of the input and output files?
solution
35
33 Color Tone Spectrum
In the file bw_picture_1.txt, there is an encoded black and white picture (these files are also at
your disposal: bw_picture_2.txt a bw_picture_3.txt). The resolution of the image is in the
first line - the first number represents the picture's width (the number of pixels in a row) and the
second number represents the picture's height (the number of pixels in a column). Each row of the
image is written in a separate line in the text file. These lines follow after the first line with the image's
resolution. In the picture line, pixel colors (gray color tones) are saved. The color of one pixel is written
using a two-digit number in hexadecimal base, so numbers from 00 to ff. The color number expresses
the tone of gray (let's remind ourselves that tones of gray have the same values of red, green, and blue
in the RGB model). Colors representing pixels are not divided by anything (they follow right after one
another).
Example of the text file's format:
20 5
ffa315070300aa0000000000000000ffffffffff
00000000000000000000afbfcfdfef0000000000
0000000000ffffffffff0000000000ffffffffff
ffffffffff0000000000ffffffffff000000ffff
00102030405060708090a0b0c0d0e0f0001f2f3f
From the text file and the colors used (tones of gray), we can see how often specific tones of gray are used
in the picture. Create a program which:
reads the file and prints the width and height of the picture and the total amount of pixels,
finds out and prints the number of the most frequent tone of gray,
draws a frequency histogram of individual gray tone usage (based on the example). The frequency of
one value's appearance will be drawn as a column with a width of 2 pixels, individual columns will
appear one after the other and the column's maximum height will be 500 px,
draws a histogram with a computed scale (none of the columns drawn will exceed a height of 500
px).
Hint: We can use the function int() to convert numbers to the decimal base, the second parameter sets
the number base. For example: int('ff', 16) returns 255.
An example of histograms drawn for the range of files from bw_picture_1.txt to
bw_picture_3.txt:
Questions:
1. How do we do a quick check to make sure that the number of appearances returned is not
completely wrong?
2. What can we find out from the final histogram and consequently say about the properties of the
picture contained in the input file?
solution
36
34 Image Decompression
In the file image_decompression_1.txt, there is an encoded black and white image (these files are
also at your disposal: image_decompression_2.txt and image_decompression_3.txt). The
resolution of the image is in the first line - the first number represents the picture's width (the number of
pixels in a row) and the second number represents the picture's height (the number of pixels in a column).
Each row of the image is written in a separate line in the text file. These lines follow after the first line with
the image's resolution. The first number in each line represents the number of black pixels that follow after
each other in that row in the image. The next number represents the amount of white pixels that follow
after each other in that row in the image. There are alternating numbers representing the amount of black
and white pixels in each line. Numbers are separated by a single space.
Create a program which decompresses an image written in this way and makes a sequence of zeros and
ones out of it (zero is a black pixel and one is a white pixel). The program is going to have these properties:
reads and prints the width and height of the image and the number of all the pixels in the file,
reads the first line of the image and sends it to the function process_line() for processing,
contains the function process_line(), which makes an output string from the number sequence.
There are only going to be zeros and ones in the output string.
reads all the lines of the file, transforms them with the help of the function process_line(), and
creates a text file named image_decompression_output.txt. The size of the picture will also
be saved in the first line of the output file.
20 5
0 3 2 2 8 5
2 3 1 1 3 8 2
0 20
20
7 5 5 3
20 5
11100110000000011111
00111010001111111100
11111111111111111111
00000000000000000000
00000001111100000111
Questions:
1. What kind of line is going to be represented by only one number in the input file?
2. What kind of lines are going to have more than one number in the input file?
3. What is the longest input line possible going look like?
4. When comparing images with the same overall number of pixels, which image will have the shortest
input file?
5. What is the relationship between the sizes of the input and output files?
solution
37
35 Compressed Image Drawing
In the file image_decompression_1.txt there is an encoded black and white image (these files are
also at your disposal: image_decompression_2.txt and image_decompression_3.txt). The
resolution of the image is in the first line - the first number represents the picture's width (the number of
pixels in a row) and the second number represents the picture's height (the number of pixels in a column).
Each row of the image is written in a separate line in the text file. These lines follow after the first line with
the image's resolution. The first number in each line represents the number of black pixels that follow after
each other in that row in the image. The next number represents the amount of white pixels that follow
after each other in that row in the image. There are alternating numbers representing the amount of black
and white pixels in each line. Numbers are separated by a single space.
Create a program which decompresses an image written in this way. The program is going to have these
properties:
reads the image size for the file, based on which it sets the canvas size,
reads the first line of the image and draws it on the canvas, one pixel is drawn using a rectangle with a
size of 1x1 pixel,
draws the whole image on the canvas based on the data in the file while not burdening the memory.
It reads all the data and draws directly from the file,
draws the image using reversed pixels after pressing a button labeled negative. Everything that is
black according to the file will be drawn in white and, conversely, everything that is white according
to the file will be drawn black.
20 5
0 3 2 2 8 5
2 3 1 1 3 8 2
0 20
20
1 1 1 1 16
WWWBBWWBBBBBBBBWWWWW
BBWWWBWBBBWWWWWWWWBB
WWWWWWWWWWWWWWWWWWWW
BBBBBBBBBBBBBBBBBBBB
BWBWBBBBBBBBBBBBBBBB
Questions:
1. What kind of line is going to be represented by only one number in the input file?
2. What kind of lines are going to have more than one number in the input file?
3. What is the longest input line possible going look like?
38
4. When comparing images with the same overall number of pixels, which image will have the shortest
input file?
5. What is the relationship between the sizes of the input and output files?
solution
CREATING
CANVAS
TRUE
OPEN
RANGE
FUNCTION
WHILE
PRINT
STRING
Program properties:
solution
39
37 Voting 2
In the text file voting_1.txt (the file voting_2.txt is also at your disposal), the progress of reality
show viewers' text message voting is saved. Every line contains exactly one phone number to which text
messages are delivered. Viewers can vote for participants whose numbers are in the range from 5220 to
5229. The organizer of the competition wants to provide the participants with information about what
time (in what order) they received text message votes. Thanks to this the participants can see whether
more people voted at the beginning of the competition or at the end.
Example of part of the inputted text file voting_1.txt:
5225
5227
5225
5224
5225
5227
finds out and prints the number of all text messages sent,
creates a text file named 5220.txt where the numbers of lines representing only those messages
received for participant 5220 are printed on separate lines,
creates text files 5221.txt to 5229.txt containing similar reports for the other participants.
Example of part of the outputted text file 5225.txt based on the previous input text file example:
1
3
5
Questions:
solution
38 Customer Satisfaction 1
A local grocery store has decided that it wants to find out its customers' rate of satisfaction with the
services it has provided. They have installed a box near the exit where customers can express their
satisfaction / dissatisfaction on a touchscreen. All responses are written to a text file. Responses are
contained in the text file satisfaction_1.txt (the files satisfaction_2.txt and
satisfaction_3.txt are also at your disposal). Each line contains one customer response. The
response contains the time of entry in the form of hour:minute, followed by one space and the text yes
or no depending on whether the customer was satisfied or dissatisfied. The file contains responses from
multiple days.
Example of part of the input text file satisfaction_1.txt:
08:39 yes
06:47 yes
10:52 yes
14:55 no
15:30 no
10:53 yes
40
the total number of responses,
at what time (during which hour) customers are most satisfied and the total number of satisfied
customers,
at what time (during which hour) customers are most dissatisfied and the total number of dissatisfied
customers,
the satisfaction percentage for each hour of the day, but only for those hours for which responses
exist.
solution
39 Customer Satisfaction 2
A local grocery store has decided that it wants to find out its customers' rate of satisfaction with the
services it has provided. They have installed a box near the exit where customers can express their
satisfaction / dissatisfaction on a touchscreen. All responses are written to a text file. Responses are
contained in the text file satisfaction_1.txt (the files satisfaction_2.txt and
satisfaction_3.txt are also at your disposal). Each line contains one customer response. The
response contains the time of entry in the form of hour:minute, followed by one space and the text yes
or no depending on whether the customer was satisfied or dissatisfied. The file contains responses from
multiple days.
Example of part of the input text file satisfaction_1.txt:
08:39 yes
06:47 yes
10:52 yes
14:55 no
15:30 no
10:53 yes
solution
41
40 Data Analysis
A local grocery store has decided that it wants to find out its customers' rate of satisfaction with the
services it has provided. They have installed a box near the exit where customers can express their
satisfaction / dissatisfaction on a touchscreen. All responses are written to a text file. Responses are
contained in the text file satisfaction_1.txt (the files satisfaction_2.txt and
satisfaction_3.txt are also at your disposal). Each line contains one customer response. The
response contains the time of entry in the form of hour:minute, followed by one space and the text yes
or no depending on whether the customer was satisfied or dissatisfied. The file contains responses from
multimple days.
Example of the input text file:
15:38 yes
15:39 yes
14:33 yes
08:38 yes
07:42 yes
15:20 yes
Example of output:
solution
41 Ordering Food
There is an electronic food system in the school cafeteria. Students can order food from the menu for the
next day. There are always 4 food choices marked with the following colors: green, red, blue, and orange.
Create a program for choosing food with these properties:
Four squares are going to be drawn on the screen filled with the colors green, red, blue, and orange
and the title of the program (see the example).
We order food using the mouse to click on a colored square.
We enter a student identification number into the program (A label is also shown near the entry field
- see the example).
After clicking one of the squares, a new line is written in the text file food_choice.txt which
contains a student identification number, a space and the food selected (g – green, r – red, b – blue, o
42
– orange).
The program does not react to clicking outside the squares, orders aren't written to the file if no
student code has been entered, and the original content of the file food_choice.txt is deleted
each time the program is started.
154 o
208 g
206 b
101 g
85 r
Questions:
1. What do we have to think about when making the program if we know that the menu might later be
extended?
2. How do we create the program so that we can be flexible changing the sizes and positions of the
squares shown next to each other?
solution
An egg (an ellipse) displayed on the screen falls from the top edge of a random x coordinate.
There is a random letter of the English alphabet hidden inside the egg which we have to press; the
hidden letter appears in the last third of the egg's path downward.
By pressing the hidden letter (on the keyboard), we save the egg from falling and breaking. If we don't
press the hidden letter in time, the egg breaks and the game is over.
After we save an egg, a new one with a random letter starts falling.
solution
43
43 Pyrotechnician
A pyrotechnician's job is to cut the right cable to disarm an explosive (detonator). Create a program -
simulator for a pyrotechnician which has these properties:
The following are defined in the program: a list of colors used, the initial coordinates of cable
placement and their length (all cables are placed horizontally on top of each other, their width is fixed
at a size of 10 px).
Based on the data, the program draws cables, writes the title (see the example), randomly chooses
the right cable and starts a countdown which is shown on the screen.
The player controls the game by clicking on a cable. If he clicks on the right cable, the timer stops and
a message announcing the win is printed (see the example).
If they don't click on a cable in the time limit, everything is deleted from the canvas and the program
doesn't do anything else.
Questions:
1. How do we ensure that the program is going to work for inconsistent amounts of cables of multiple
colors?
2. Will the program work if two of the cables have the same color?
solution
A random word falls from the top edge of a random x coordinate. The letters of the word have been
replaced by stars. A list of words from which the word has randomly been chosen is defined at the
beginning of the program.
The player has to correctly guess the word by pressing keys. If the player presses a key with a letter
that has multiple appearances in the word, all appearances of this letter are revealed and the half-
solved word continues to fall.
If the player doesn't guess the word correctly before it hits the bottom edge, the game ends with the
printed text You lose!.
If the player guesses the whole word correctly, the game pauses at its current position and we see
the whole (guessed) word.
44
solution
45 Vocabulary Learning
Word pairs are saved in the text file vocabulary_learning.txt - a Spanish word and an English word -
in two lines one after the other.
Example of the text file:
esposa
wife
hermana
sister
hermano
brother
padre
father
Create a program to learn vocabulary (in text form) with these properties:
The program loads all the words to memory. Players choose whether the program shows Spanish or
English words.
The program consecutively shows all the words based on the language chosen and reads the answer.
If we enter a word incorrectly, the program tests that word again after all other words which were
meant to be tested.
The program continues testing us on the words until we have entered all the words correctly; at the
end it prints how many wrong answers we gave.
Questions:
solution
45
46 Hangman
The text file hangman.txt contains one word per line. In the game of Hangman, a player's task is to guess
the letters which are in the mystery word.
Example of the mystery words in the text file:
book
music
movie
cinema
theater
concert
Create a program - the game of Hangman (in text form) - with these properties:
The program loads all the words from the file into memory and randomly chooses one word for the
player to guess.
Instead of the word, a corresponding number of dots is displayed and the player begins guessing
letters.
Whenever a player guesses a letter correctly, it is revealed in the corresponding location in the word
(unguessed letters remain dots).
A player can incorrectly guess a maximum of 10 letters, then the game ends and the program prints
that the player has failed.
If the player guesses the whole word (letter by letter), the game ends with a congratulatory message.
Question:
solution
47 Barcode
Our barcode contains eight-digit numbers that don't start with a zero. Each digit is represented by a line
and the width of each line is equal to the number's value (e.g. the number 4 will be represented by a line
with a width of 4). Lines are 80 pixels long and are equidistant from each other (the distance between each
line is 10 pixels). The code is displayed between the first and last line; therefore, lines two to seven do not
extend all the way down. You can use the already prepared text files bar_code_1.txt,
bar_code_2.txt and bar_code_3.txt.
Example of our barcode graphical display:
generates a random code and prints its numerical value to the shell,
graphically displays the barcode (following the example),
reads the barcode from the text file and draws it on the screen,
reads all the barcodes one by one and displays them on the screen in fours (see the example),
another pair of four shows after pressing space.
46
Example of the input text file:
13419824
21603459
38546595
14290739
32649199
Example of the pairs of four barcodes displayed from the text file:
solution
48 Multiplication
Create a program to test your younger sibling's multiplication abilities. The program is going to have these
properties:
The program generates 10 math problems to practice multiplication up to 100 (non-negative integers)
and loads them into memory together with their solutions.
It gives us the problems one by one in text form and reads our answer. We earn 1 point for each
correct answer. If we answer incorrectly, the program places that problem at the end of the list of all
the problems we are going to be tested with.
We don't earn any points for problems that we solve incorrectly, even if we solve them right the next
time.
After it's done testing us, the program prints out how many points we have earned.
The program writes all 10 problems to the file multiplication_output.txt.
Questions:
solution
47
49 Seat Reservation System
In the file 49_task.py, a program which draws a blueprint of a bus has been prepared. If you click on a
seat with your mouse, the program reacts by printing the number of that seat. For example, the program
draws a blueprint like this one (with 10 rows of seats):
import tkinter
canvas = tkinter.Canvas(width=600, height=300, bg='white')
canvas.pack()
rowcount = 10
size = 40
busx, busy = 50, 50
def click(event):
if (busx < event.x < busx + size * rowcount and
busy < event.y < busy + size * 4):
ix = (event.x - busx) // size
iy = (event.y - busy) // size
seat = ix * 4 + iy + 1
colorize(seat, 'red')
print(seat)
In the beginning all the seats are free and they are colored green.
By clicking on a seat, we either occupy it or we make it free. Occupied seats are red.
Seat status is continuously displayed - the program prints the amount of free seats, the amount of
occupied seats, and the amount of free aisle seats (the two inner rows).
There is a save button in the program. Using the button we can save a blueprint to a text file in such a
way that the content of the file is visually similar to the blueprint on the canvas (see the example).
Free seats are saved as a number (the seat number) and occupied seats are saved with the letter X.
48
Example of a text file for the blueprint in the previous picture:
X 5 9 X X 21 25 X 33 37
2 X X 14 X X X 30 X X
3 X X 15 X X X 31 X X
X 8 12 X X 24 28 X 36 40
Questions:
solution
50 Image Contour
In the file image_contour_1.txt there is an encoded black and white image (the files
image_contour_2.txt and image_contour_3.txt are also at your disposal). The resolution of the
image is in the first line - the first number represents the picture's width (the number of pixels in a row) and
the second number represents the picture's height (the number of pixels in a column). Each row of the
image is written in a separate line in the text file. These lines follow after the first line with the image's
resolution. The first number in each line represents the number of black pixels that follow after each other
in that row in the image. The next number represents the amount of white pixels that follow after each
other in that row in the image. There are alternating numbers representing the amount of black and white
pixels in each line. Numbers are separated by a single space.
Create a program which draws a picture encoded this way. The program will have these properties:
Reads the size of the image from the file and sets the canvas size based on it.
Reads the first line of the image and draws it on the canvas, always drawing only one 1x1 px rectangle
for the first black pixel, even if more black pixels should follow after each other in the picture's
definition.
Draws the whole image on the canvas based on the data in the file while not burdening the memory -
all the data is read and drawn directly from the file.
Draws a black 1x1 px rectangle where a white pixel (or the first white pixel in a group of white pixels)
should be after the user clicks the Differently button. The image drawn at the start of the
program should not be erased when the button is pushed.
20 5
0 3 2 2 8 5
2 3 1 1 3 8 2
0 20
20
7 5 5 3
Example of the colored pixels (W - white, B - black) after decoding the input file (we draw only the first
49
black and first white pixels - with black color):
WWWBBWWBBBBBBBBWWWWW
BBWWWBWBBBWWWWWWWWBB
WWWWWWWWWWWWWWWWWWWW
BBBBBBBBBBBBBBBBBBBB
BBBBBBBWWWWWBBBBBWWW
Questions:
1. What kind of line is going to be represented by only one number in the input file?
2. What kind of lines are going to have more than one number in the input file?
3. What is the longest input line possible going look like?
4. When comparing images with the same overall number of pixels, which image will have the shortest
input file?
5. What is the relationship between the sizes of the input and output files?
solution
51 Announcement Compression 1
Passenger announcements displayed on the information screens in train stations which are transferred
directly from a computer to the screens are the most efficient. The system is older but has a longer life
expectancy, which is the reason that the system supports English letters only. The service program first
compresses and then sends the dispatcher's text input, which is then converted to only capital letters for
the display screen.
The text is compressed in such a way that the program removes spaces from the announcement. In order
for the announcements to remain legible, words in the compressed announcement are written so that one
word is made up of only upper-case letters and the next word lower-case.
For example, the sentence:
The north of the line will be shut down for the weekend
will be compressed in this way:
THEnorthOFtheLINEwillBEshutDOWNforTHEweekend
Your program will load one line of passenger information from the user. Information can contain upper-
and lower-case letters and spaces only. Create a program which:
solution
50
52 Announcement Compression 2
Passenger announcements displayed on the information screens in train stations which are transferred
directly from a computer to the screens are the most efficient. The system is older but has a longer life
expectancy, which is the reason that the system supports English letters only. The service program first
compresses and then sends the dispatcher's text input, which is then converted to only capital letters for
the display screen.
The text is compressed in such a way that the program removes spaces from the announcement. In order
for the announcements to remain legible, words in the compressed announcement are written so that
every word begins with a capital letter; all other letters are lower case.
For example the sentence:
The north of the line will be shut down for the weekend
can be written this way:
TheNorthOfTheLineWillBeShutDownForTheWeekend
Your program will load one line of passenger information from the user. Information can contain upper-
and lower-case letters and spaces only. Create a program which:
solution
51
53 Skyline
The Urban Architecture Institute needs a simple urban street simulator to regulate the height of future new
buildings.
Create a program which loads information about heights and widths (in meters) of buildings on a street
from the file street_build_up.txt. Each line of the input file contains only two numbers - the height
and width of a building separated by a space. The program is going to have these properties:
displays the building as rectangles next to each other (see the example),
in case of free space on the street (a "building" with a height of zero), it's going to be marked with a
thicker green horizontal line. That's a potential spot for a new building.
highlights large walls on the boundary of buildings, meaning places where the height difference
between two existing neighboring buildings is too large - this critical boundary is entered in meters
using the Entry field. This feature will help urban architects eliminate jagged street skylines with
over-exposed side walls.
40 50
20 70
30 30
40 0
50 100
Note: The wall of the fourth building in the picture is not highlighted in red because there is no building next
to it.
solution
54 Boats
Program a simulation for boats anchored in a bay. In the text file boats.txt, a description of the bay has
been saved - it's a two-dimensional map consisting of 1s and 0s separated by spaces. The character 1
represents land and 0 represents water. The resolution (height and width) of this map is in the first line –
two integers separated by a space. The bay can therefore be drawn as a two-dimensional map of land and
water squares. After clicking a button, the program generates a boat somewhere on the water in the bay.
With another click on the button, the program generates other boats until the bay is full.
The rules for generating (placing) boats:
52
draws a bay made of squares based on the map in the file,
draws one boat after the button is clicked. A boat can be generated in a random position or there can
be a strategy (e.g. beginning at the top of the map).
prints an announcement on the screen saying that the bay is full when there isn't any more space for
another boat.
10 7
0 0 0 1 1 1 1 0 0 0
0 0 1 1 1 1 1 1 0 0
1 0 0 0 0 0 0 0 0 1
0 0 0 0 1 0 0 0 0 0
1 0 0 0 0 0 0 0 0 1
1 1 0 0 0 0 0 0 1 1
1 1 1 0 0 0 0 1 1 1
Example of the program – a dock with five yellow boats and an example of a full bay (for the input file in
the previous example):
solution
55 Drawing Robot 2
A Drawing Robot obeys commands given to it by the user and draws images in compliance with them. The
robot recognizes its position and its heading (only up / down / left / right).
repeat 4
line
right
...
repeatend
Create a program which simulates the drawing robot's activity. At the beginning of the program, the robot
is located at the center of the canvas facing upwards. The program doesn't show the robot. After clicking
the button Draw, the robot executes the commands which are saved in the file drawing_robot_2.txt;
the robot draws the image based on the commands in the file. The program has these features:
The robot is able to execute the command line from a text file, drawing an upward line.
The robot is also able to execute the commands right and left from the text file. Other lines are
53
drawn in the direction the robot is facing.
The robot is also able to execute the loop repeat ... repeatend.
line
repeat 4
line
left
repeatend
right
right
line
left
line
Example of the program's output after execution of the commands in the input file:
solution
56 Level Editor 1
Game developers sometimes add level editors to their games so that players can design their own level
maps. Create an editor program which has these properties:
solution
54
57 Level Editor 2
Game developers sometimes add level editors to their games so that players can design their own level
maps. Create a level editor program for the game Maze. The program will allow straight walls to be added
to the maze by clicking. Create a program which has these properties:
solution
58 Subway Line
There's always a route plan of the subway line above the door in a subway car. This horizontal line is the
same color as the subway line's color and shows the line's stops (see the example). The public transport
company has information about all the individual subway lines saved in files. The program can always
generate a new plan from this data when there are changes, such as the opening of a new subway station.
Create a program which has these properties:
Loads the color of a line from the file subway_line_route.txt (in the first line of the file) and a
list of stations (each subsequent line contains one name only) and displays the subway line as a
horizontal line with the names of the stations spaced in regular distances. Station names will be
displayed at an angle above the line.
Displays the end stations with a square at the beginning and end of the line.
Station marks - small circles - will be displayed on the line. The circles representing stations where
express trains also stop will not be filled. Express train stations have the character * written in front
of their name in the input file.
#FF0000
Grand Central Station
Marcy Avenue
Franklin Street
*National Museum
Union Square
Kingston Avenue
55
Sutton Street
*Court Street
Botanical Garden
...
solution
The number in the first line represents bus capacity (max. amount of people possible).
Every additional line contains a number representing the number of travelers getting on and off the
bus at a bus stop and the name of the particular bus stop. This information is separated by a space.
50
20 0 Oxford Circus Stn
35 0 Piccadilly Circus
10 20 Charles II Street
40 20 Trafalgar Sq
10 40 Whitehall
5 10 Horse Guards Parade
35 10 Westminster Stn
0 55 St Thomas' Hospital
Create a program which creates a visualization of how full the bus is:
Prints the names of the bus stops loaded from the file in a column on the canvas (the names of the
bus stops consists of one to two words).
After pressing any key, a capacity indicator is displayed next to the first bus stop - a rectangle partly
filled with a green stripe. The empty rectangle represents the bus' full capacity and a green stripe
represents the percentage of how full the bus was after leaving the bus stop.
After pressing any additional key, the capacity indicator is displayed next to the following bus stop.
If it happens that the bus is overfull after leaving a bus stop (the amount of people on board is higher
than the allowed capacity), the indicator exceeds the rectangle and fills it with red.
56
Questions:
1. What would you have to change in your program (considering possible stops with names consisting of
more words) if all the data in every line was separated by a semi-colon?
solution
60 Calculator
Create a simple calculator that's able to do addition and subtraction operations. The calculator's buttons
will be displayed as squares with text drawn on the canvas.
Create a program which has these properties:
Displays square buttons with numbers next to each other. There should be a display above the
buttons showing the input number. At the beginning of the program, the number zero should be
displayed.
After clicking on a button with a number, that number will be added to the number displayed, or just
replacing the zero if that is what's displayed.
Displays the square buttons +, -, =, C in the second row.
After clicking the buttons + or –, a zero will be displayed again so that we can input the second
number in order to perform the addition / subtraction. After clicking the button =, the solution will be
displayed.
After clicking the button C (Clear), a zero will again be displayed and the user can input a new
problem.
solution
61 Division
Create an educational program to practice simple Mathematics problems with integer division and division
remainders. The program should have these properties:
Generates a problem and displays it on the canvas. The dividend will be in the range of 11 to 20 and
the divider in the range of 2 to 9.
Enables the user to input a solution to the integer division problem (we don't input the remainder)
with the Entry component. After clicking the button Check, the program prints out whether the
solution is correct or not.
Displays the division principle visually - after declaring the answer correct or not, it displays the
dividend as circles and colors in n-tuples of circles in an amount equal to the divisor with different
colors (you can choose the colors with a prepared list). Circles representing the remainder will be
separated from the others (see the example).
57
solution
62 Survey
The company Surveys Ltd. processes polls in which they ask for people's opinions on current public topics.
In the text file survey.txt, the first line contains a question and three numbers in the second line
represent the amount of "Yes," "No," or "I don't know" votes that have been recorded so far separated by
a space.
Example of the text file:
Do you agree with the idea of paying a deposit for PET bottles?
30 22 7
Prints the question and the opinions with the amount of people who voted for each underneath each
other.
Displays stripes that graphically represent votes for individual answers in percentages and also shows
how many people voted for that opinion.
Displays the stripe representing the most votes in a different color.
Enables the user to vote: by clicking the number of the answer (1, 2, or 3), a vote is added, the canvas
updates, and the program also updates the file survey.txt.
solution
63 Transit Research
After changes to its tram line routes, the city's public transport company conducted a month-long study on
how heavily its individual tram lines were being utilized. In the file transit_research.txt, there is a list
of all the tram stops and the average number of people getting on and off during the observed time. Three
pieces of information are stored on every line of the file - the average number of people getting on, the
average number of people getting off, and the name of the tram stop. The information is separated by a
semicolon. The numbers are integers; the names of the tram stops can consist of multiple words.
The company wants to use the gathered data to improve its services - placing ticket machines at busy
stops, choosing the right vehicle for each route, and making the least-used tram stops request stops.
Example of the text file:
10;0;Main Square
5;0;Green Park
50;1;High Street
2;0;Hospital
10;3;Theater
58
1;1;Town Hall
Prints a list of the tram stations with the number of passengers in the tram after it has left the stop.
Shows recommendations for the correct type of tram for a concrete route. The correct tram type is
chosen based on the greatest number of passengers during the vehicle's journey. The tram types are:
long, standard, short. Rules for what number of passengers is best for which type of tram are up
to you.
Makes a list of tram stops suitable for the placement of a ticket machine. It is advisable for there to
be a ticket machine at tram stops where at least 10 passengers get on.
Makes a list of tram stops where there are fewer than three people (or fewer than three people get
off) - these will be changed to request stops, where a passenger needs to signal the driver to stop. If
there is no signal, the tram won't stop at that particular tram stop.
solution
64 Seating Chart
In the text file seating_chart.csv, there is a list of students in a class in alphabetical order. Each line
contains the name of a single student in the order of surname;first name. Example of the text file:
Murray;Maria
Anderson;Michael
Wilson;Bob
Stewart;Thomas
Hamilton;Lucy
Martin;John
Create a program which creates a random seating chart using the list of students. This program will have
these properties:
The user inputs the number of rows and the amount of desks in one row via two Entry areas. There
is also a description of the Entry areas above the areas. We confirm entry by clicking the button
Confirm input.
The program reads from the text file and remembers all the students. If a user provides an insufficient
number of desks for all the students, the program alerts us by printing text on the canvas.
If the number of desks is enough for all the students to be seated, the program draws the input
number of desks and randomly places students in them. Names are written in the desks in the order:
surname (colored red), then first name (beneath that in blue).
If the amount of students is less than the amount of desks, the remainder of the desks stay empty.
The program places students in order from the front. Empty desks will wind up in the back (see the
example).
We can draw the seating chart again or edit the layout using the button Confirm input .
59
solution
60
1 Baby Snake
import tkinter
canvas = tkinter.Canvas(width=400, height=400)
canvas.pack()
def run():
global xhead, yhead, collision
xhead += dx
yhead += dy
c = canvas.coords('snake')
cx = c[::2]
cy = c[1::2]
i = 0
while i < len(cx) and not collision:
if cx[i] == xhead and cy[i] == yhead:
collision = True
i += 1
if not collision:
c.append(xhead)
c.append(yhead)
canvas.coords('snake', c)
canvas.after(10, run)
def key(event):
global dx, dy
if event.keysym == 'Left':
dx, dy = -1, 0
if event.keysym == 'Right':
dx, dy = 1, 0
if event.keysym == 'Up':
dx, dy = 0, -1
if event.keysym == 'Down':
dx, dy = 0, 1
collision = False
xhead, yhead = 200, 200
dx, dy = 0, -1 #movement direction on x and y axes
canvas.create_line(xhead, yhead-dy, xhead, yhead, tags = 'snake')
run()
canvas.bind_all('<Key>', key)
List c holds the coordinates of all the points that the baby snake has moved through. We use the data held
in this list later on when determining whether the baby snake has hit its own trajectory.
Tasks:
1. What happens when the baby snake leaves the screen?
2. How can we ensure that the baby snake will not go outside of the screen?
3. Why do we add the new position of the baby snake (of its head) to the list at the end of the
function run(), instead of, for example, adding it to the list at the beginning of the function
without using the if-command that it is placed in?
4. How would we have to modify the program if we wanted to give the baby snake the ability to move
diagonally to the right and up?
task
[] Cnv aft.
61
2 Baby Snake - Game Report
We'll show you two different solutions for this exercise.
Solution 1:
def compresion(s):
if s == '':
return ''
s = s + '.' # {line A}
letter = s[0]
count = 0
outp = ''
for char in s:
if char == letter:
count += 1
else:
outp = outp + '{} {} '.format(letter, count)
letter = char
count = 1
# outp = outp + char + ' ' + str(count) # {line B}
return outp
Tasks:
1. How would the final text file change if we were to leave out the line labeled {line A}?
2. What is the connection between the lines labeled {line A} and {line B}?
3. What characters can / cannot be added to string s (in the line labeled {line A}) for the output of
the program to change / to stay the same as before?
Solution 2:
def compresion(s):
if s == '':
return ''
letter = s[0]
62
count = 0
outp = ''
for char in s:
if char == letter:
count += 1
else:
outp = outp + '{} {} '.format(letter, count)
letter = char
count = 1
outp = outp + '{} {} '.format(letter, count)
return outp
Tasks:
4. What are the differences between solutions 1 and 2?
5. What is the connection between the lines labeled {line C} and {line D}?
6. What characters can / cannot be added to string s (in the line labeled {line A}) for the output of
the program to change / to stay the same as before?
7. Which solution is more effective in regard to the amount of memory needed? Explain why you
believe so.
task
'' txt fx()
3 Display on a Tram
Since the display has only one line and consists of exactly twenty characters, we will use a non-
proportional font (for example, Courier New). It is more convenient to edit the text string displayed on the
screen than move the text itself using, for example, canvas.move(). When moving the text itself, it is
harder to ensure that the beginning of the text is displayed on the right side of the screen while the end of
the text is displayed on the left side at certain phases of the movement.
import tkinter
canvas = tkinter.Canvas(width=600, height=100, bg='black')
canvas.pack()
def animation():
global label
label = label[1:] + label[0] # {line A}
canvas.delete('all')
canvas.create_text(300, 50, text=label,
fill='red', font=('Courier New', 35, 'bold'))
canvas.after(100, animation)
63
def draw(index, stops, terminal):
global label
label = stops[index] + ' '
if terminal:
label += ' - end of the line '
label = label + ' '*(20 - len(label)) # {line B}
def next_stop(event):
global current, terminal
if not terminal:
current += 1
if current == len(stops)-1:
terminal = True
draw(current, stops, terminal)
current = 0
terminal = False
label = ''
draw(current, stops, terminal)
animation()
print(stops)
canvas.bind_all('<Key>', next_stop)
canvas.mainloop()
Tasks:
1. What could we replace the line labeled {line A} with if we were unable to use slices?
2. What role does the line labeled {line B} have in the solution of the exercise? What would
happen if string name was longer than 20 characters?
3. What changes would need to be made to this program if the tram was to drive the other way
around and we used the same text file?
4. What changes would need to be made to this program if we wanted to control the display using the
right and left arrow key (the previous and the next stop)?
5. Which part of the program ensures that the display does not change the names of the stops on the
screen once the tram has reached its terminus station? What would happen if the program was able
to change the name of the stop to the next one even after the tram has reached its terminus
station?
task
'' [] txt Cnv fx() aft.
64
4 Weather Stations Logs
We can use different methods to read the text file. Instead of using a for loop to read the file line by line
(as you can see in the solution below), we can use function file.readlines() and load the contents of
the whole file directly into a list. This has no impact on the level of difficulty of the solution since we still
need to deal with the individual lines. It does not matter whether we deal with the individual lines
immediately after each line is read or just after we have loaded all the lines into a list.
Tasks:
1. What would happen if we commented out the line labeled {line A}? And what would happen if
the program did not calculate the average temperature and we commented out the line labeled
{line A}? Explain why you think so.
2. What does the command in the line labeled {line B} do and why?
3. What other ways are there to count the number of measurings? Which way is easier and why?
4. What other ways are there to calculate the average temperature? Which way is easier and why?
5. What would happen if the inputted file was empty?
task
'' [] () txt
65
5 Ordered Meals
We use a data structure called dictionary in the solution. Solving this exercise using a list of tuples is
also possible, but the solution is less orderly.
file.close()
Tasks:
1. What would happen if we replaced the line labeled {line A} with d = {}?
2. Why is the notation d[meal] = d[meal] + 1 not enough in {line B}?
3. How would the output of the program change if we removed the line labeled {line D}?
4. How would we have to modify the program so that the output of the program stays the same when
we remove the line labeled {line D}?
5. Why is it not possible to place the command print where {line C} is to directly print the
information?
task
'' {} txt
66
6 Musical Notes
This exercise has multiple solutions. The exercise is fairly simple; when solving it the student should mainly
demonstrate the ability to use functions and generalize the solution.
import tkinter
canvas = tkinter.Canvas(width=420, height=420)
canvas.pack()
WIDTH = 400
scale = 'cdefgah'
def load_notes(filename):
file = open(filename, 'r')
return file.readline().strip()
#return 'cdefgahhagfedcceggeccdfaafdcegegfafafggfedc'
def pitch(note):
return scale.find(note) * 5
def draw(notes):
notex = 20
stavey = 10
stave(0, stavey, WIDTH)
count = 0
for note in notes:
draw_note(notex, stavey + 5 * 10 - pitch(note))
notex += 20
count += 1
if count+1 == WIDTH // 20 :
stavey += 100
notex = 20
count = 0
stave(0, stavey, WIDTH)
notes = load_notes('files/notes.txt')
draw(notes)
canvas.mainloop()
Tasks:
1. What would happen if we commented out line A instead of line B?
2. What has to be modified in the program so that the notes are displayed gradually (not all at the
same time)?
task
'' txt Cnv fx() aft.
67
7 Random Order for Oral Exams
If we use the function random.shuffle() in the solution, this exercise's level of difficulty significantly
drops. For this reason, the exercise includes the fifth bullet point where questions with even and odd
numbers need to be shuffled separately. When we comment out this section of the program and
uncomment the line labeled {line A}, the program will work according to the first four bullet points.
import random
student_cnt = int(input('Input the number of students:'))
quest_cnt = int(input('Input the number of questions:'))
students = []
questions = []
for i in range(student_cnt):
students.append(i+1)
for i in range(quest_cnt):
questions.append(i+1)
even_questions = questions[1::2]
odd_questions = questions[::2]
random.shuffle(odd_questions)
random.shuffle(even_questions)
questions = []
for i in range(len(even_questions)):
questions = questions + [even_questions[i], odd_questions[i]]
if len(odd_questions) > len(even_questions):
questions.append(odd_questions[-1])
random.shuffle(students)
#random.shuffle(questions) # {line A}
Tasks:
1. How would we solve the exercise without using the function random.shuffle()?
2. What changes would have to be made to the solution if we were given a list with the names of the
students instead of the numbers that had been assigned to the students?
3. How would you check that the list of shuffled numbers does not include any duplicated numbers
using Python?
task
'' []
68
8 Find the Cracked Plate
cracked = random.randrange(10)
plates = [0]*10
ending = False
def letter(order):
return chr(ord('A') + order)
def win():
canvas.delete('all')
canvas.create_text(350, 50, font='Arial 20', fill='blue',
text='Congratulations, you found the cracked plate!')
def multiple():
selected = ''
for i in range(len(plates)):
if plates[i] > 1:
selected += letter(i)
canvas.create_text(350, 80, text='Plates chosen more than once: ' +
selected, font='Arial 20', fill='red')
def click(xy):
global ending # {line A}
if xy.x < 10*70 and not ending: # {line B}
plate = xy.x // 70
plates[plate] += 1
if plate == cracked:
ending = True
win()
multiple()
for i in range(10):
draw_plate(i*70+35, 50, letter(i))
canvas.bind('<Button-1>', click)
canvas.mainloop()
Tasks:
1. What would happen if the number given to function letter in its argument was negative?
2. What impact would the removal of the line labeled {line A} have on the program?
3. What impact would the replacement of and with or in the line labeled{line B} have on the
program?
task
'' [] Cnv fx()
69
9 Boat Race
It appears that we could use the function canvas.move() to move the boats and the function
canvas.coords() to find out the coordinates of the boats. It this case we would not need to create a
list to hold the positions of the boats. However, it is stated in the exercise that we cannot modify the
function boat and therefore we are not able to assign tags to the drawn images. Tags are necessary when
we want to use the command move. Another reason why the command canvas.move is not the right
choice for this exercise is the fact that the sails of the boats are supposed to be flapping in the wind as the
boats are moving. Creating this animation would not be possible with the move command since this
command only moves an already drawn image without the possibility of altering it. All this means that the
exercise is designed in a way that leads the students to avoid using this function, even though it is not
explicitly stated.
def draw_boats():
for i in range(15):
boat(pos[i], i*40+40)
canvas.create_line(650, 0, 650, 650, fill='red', width=3)
def win(number):
global start
start = False
canvas.create_text(350, 350, font='Arial 20', fill='red',
text='The winner is boat number: '+str(number+1))
def race():
if start:
canvas.delete('all')
for i in range(len(pos)):
pos[i] += random.randint(1, 10)
if pos[i] > 650:
win(i)
draw_boats()
canvas.after(100, race)
def click(event):
global start
if not start:
start = True
race()
pos = [20] * 15
start = False
draw_boats()
canvas.bind('<Button-1>', click)
canvas.mainloop()
task
'' [] Cnv fx()
70
10 Creation of a Crossword Puzzle 1
For the column with the solution of the crossword puzzle to be displayed correctly, we first of all need to
calculate in which column the solution will be placed in regard to the whole crossword puzzle. So we need
to determine the highest number of the numbers representing the position of the letter that is part of the
solution in each of the words. Now when we are drawing the individual rows of the crossword, we are able
to calculate how much we need to move them to the right by so that the boxes with the letters that are
part of the solution are aligned in one column. If the argument of the function that draws the crossword
includes information about the position where the crossword is supposed to be placed on the canvas and
whether the crossword should be empty or completed, we can simply draw empty and completed
crosswords next to each other.
crossword = []
file = open('files/crossword1-1.txt', 'r')
for r in file:
desc = r.split()
row = (int(desc[0]), desc[1]) # {line B}
crossword.append(row)
maximal = max(crossword)
col_secret = maximal[0]
draw_all(10, 10, col_secret, crossword, False, 30)
draw_all(300, 10, col_secret, crossword, True, 30)
canvas.mainloop()
Tasks:
1. Explain what the role of the line labeled {line A} is in the program.
2. What would happen if we replaced the line labeled {line A} with the notation: x = x + size?
3. Explain what the role of the line labeled {line B} is and why is it not possible to write it as:
row=(desc[1], int(desc[0])) or as: row=(desc[0], desc[1]).
4. How would the functionality of the program be impacted by a change in the inputted text file - for
example, if the line saying 1 TRUE was changed to -1 TRUE?
task
'' [] () txt Cnv fx()
71
11 Foot Race
For this exercise we will show you two fairly similar solutions.
Solution 1:
file = open('files/foot_race.txt')
competitors = []
Solution 2:
file = open('files/foot_race.txt')
competitors = []
Tasks:
1. What are the differences between the two solutions you can see above?
2. What would the solution look like if we didn't use either a list or tuple (the data would not be
stored into memory)?
task
[] () txt
72
12 Extent of Public Transport Utilization
file = open('files/bus_utilization_extent.txt')
capacity = int(file.readline())
mylist = []
overcrowd = []
count = 0
highest = 0
for line in file:
data = line.split()
if len(data) == 3:
name = data[2]
else:
name = data[2] + ' ' + data[3]
count += int(data[0])
count -= int(data[1])
if count > capacity:
overcrowd.append(name)
if count - capacity > highest:
highest = count - capacity
mylist.append(name)
print('Vehicle capacity:', capacity)
print('Number of stops:', len(mylist))
print('List of stops: ', end='') # {line A}
for stop in mylist:
print(stop, end=', ')
print()
print('Bus was overcrowded after these stops:')
for stop in overcrowd:
print(stop)
print('Highest overcrowding:', highest, 'passengers over capacity')
Tasks:
1. What does the notation in the line labeled {line A} mean?
2. How could we solve this exercise if we were not familiar with the command print with the
parameter end?
3. How do we modify the program so that there is no comma at the end of the printed list of stops (the
comma after the last stop is removed)?
task
'' [] txt
73
13 Glutton
N = 4
r = 20
def push(event):
global dx, dy
if event.char == 'w':
dx, dy = 0, -2
elif event.char == 's':
dx, dy = 0, 2
elif event.char == 'a':
dx, dy = -2, 0
elif event.char == 'd':
dx, dy = 2, 0
def run():
global gx, gy
gx += dx
gy += dy
canvas.move(glutton, dx, dy)
for i in range(len(circles)):
if sqrt((circles[i][0] - gx)**2 + (circles[i][1]-gy)**2) <= 2*r:
# 'hypot' function (math module) is useful too
# if hypot(circles[i][0] - gx, circles[i][1] - gy) < 2 * r:
canvas.delete(circles[i][2])
circles.pop(i) # {line A}
break # {line B}
if len(circles) > 0:
canvas.after(50, run)
else:
canvas.create_text(250, 250, text='No more apples',
font='Arial 30')
gx, gy = r, r
glutton = canvas.create_oval(gx-r, gy-r, gx+r, gy+r, width=0, fill='blue')
dx, dy = 2, 0 # initial direction
circles = []
for i in range(N):
x, y = randint(r * 3, 500 - r), randint(r * 3, 500 - r)
circles.append((x, y, canvas.create_oval(x - r, y - r, x + r, y + r,
width=0, fill='red'))) # {line C}
canvas.focus_set()
canvas.bind('<Key>', push)
canvas.after(10, run)
canvas.mainloop()
Tasks:
1. What impact on the functionality of the program would the removal of the line labeled {line A}
have?
74
2. What impact on the functionality of the program would the removal of the line labeled {line B}
have?
3. What would the program look like if we did not use the command break?
4. Explain the role of the command in the line labeled {line C}. Which data structure does this
command create?
5. How could we enhance the program? Which functions could we create in the program?
task
'' [] () Cnv
14 Long Jump
file = open('files/long_jump.txt')
countries = {}
maxlength = 0
winners = []
for line in file:
data = line.split()
countries[data[1]] = countries.get(data[1], 0) + 1 # {line A}
length = 0
for i in range(5):
length = max(length, int(data[i + 2])) # {line B}
if length > maxlength:
maxlength = length
winners = [data[0]]
elif length == maxlength:
winners.append(data[0])
print('List of countries:')
for country in countries:
print(country, end=', ')
print()
print('Numbers of competitors:')
for double in countries.items():
print(double[0], ':', double[1])
print('Longest jump:', maxlength, 'was made by:')
for winner in winners:
print(winner)
Tasks:
1. With which command(s) can we replace the line labeled {line A} if we do not wish to use the
method get()?
2. Explain what is going on in the line labeled {line B}?
task
[] () {} txt
75
15 Easy-to-Read Parentheses
import tkinter
if ok:
msg = 'Correct parenthesis pairing'
else:
msg = 'Wrong parenthesis pairing'
canvas.create_text(500, 90, text=msg, font='Courier 30')
if ok:
y = 3
who = -1
for char in exp:
if char == '(':
who += 1
if char == '(' or char == ')':
canvas.create_text(y, 3, anchor='nw', text=char,
font='Courier 30', fill=colors[who])
else:
canvas.create_text(y, 3, anchor='nw', text=char,
font='Courier 30', fill='black')
if char == ')':
who -= 1
y += 30
canvas.mainloop()
task
'' [] Cnv
76
16 Names in Columns
file = open('files/employees_names.txt')
names = file.readlines()
file.close()
for i in range(len(names)):
names[i] = names[i].strip()
count = len(names) // 2
print('Name count:', count)
firstnames = names[:count] # {line A}
lastnames = names[count:] # {line B}
length = 0
for s in lastnames:
length = max(length, len(s))
print('Longest last name length is ', length)
length = 0
for s in firstnames:
length = max(length, len(s))
print('Longest first name length is ', length)
outp=open('outp.txt','w')
for i in range(count):
outp.write(firstnames[i] + (' ' * (length - len(firstnames[i]) + 1))
+ lastnames[i]+'\n')
outp.close()
Tasks:
1. What happens in the lines labeled {line A} and {line B}?
2. What other way is there to determine the length of the longest last name?
3. How do we find and print the longest last name?
4. How do we figure out the highest number of first names (all the names except for the last name) an
employee has?
task
'' [] txt
77
17 The Secret Table
m = max(table)
print('The most frequent groups:')
for i in range(10):
if table[i] == m:
print(i, end=' ')
Tasks:
1. Which segment of the program converts a character to a number in accordance with the Secret
Table?
2. What other way is there to convert a character to a number in accordance with the Secret Table?
3. What will the program print if the input is incorrect (for instance, it is text in lower-case letters)?
task
'' []
78
18 Drawing Robot 1
import tkinter
def do(cmd):
global robotx, roboty, angle
parts = cmd.split()
if parts[0] == 'line':
length = int(parts[1])
if angle == 0:
x, y = robotx, roboty - length
elif angle == 90:
x, y = robotx + length, roboty
elif angle == 180:
x, y = robotx, roboty + length
elif angle == 270:
x, y = robotx - length, roboty
else:
x, y = robotx, roboty
canvas.create_line(robotx, roboty, x, y, fill='black', width=3)
robotx, roboty = x, y
elif parts[0] == 'left':
angle -= 90
if angle < 0: # {line A}
angle += 360 # {line B}
elif parts[0] == 'right':
angle = (angle + 90) % 360 # {line C}
def do1():
do(entry1.get())
Tasks:
1. What are the roles of the lines labeled {line A}, {line B} and {line C} in the program?
2. If we removed the lines labeled {line A}, {line B} and {line C} from the program, what
would we need to modify for the program to keep the same level of functionality?
3. We want to add the command line without any specified movement. This new command will
automatically move the robot by 10 steps. What is the easiest way to modify the program to meet
this requirement?
task
'' [] Cnv
79
19 Image Reflection
import tkinter
def mirror():
global width, height, side
canvas.delete('all')
for i in range(height):
for j in range(width):
if int(picture[i][j]) == 0:
color = 'white'
else:
color = 'black'
canvas.create_rectangle((width-j-1)*side, i*side,
(width-j)*side, (i+1)*side,
width=0, fill=color)
picture = []
side = 2
file = open('files/image_reflection.txt')
line = file.readline()
numbers = line.split()
width = int(numbers[0])
height = int(numbers[1])
one_cnt = 0
for r in range(height):
line = file.readline()
numbers = line.split()
picture.append(numbers)
for s in range(width):
if numbers[s] == '0':
color = 'white'
else:
one_cnt += 1
color = 'black'
canvas.create_rectangle(s*side, r*side,
(s+1)*side, (r+1)*side,width=0,
fill=color)
file.close()
print('Picure has {} pixels.'.format(height * width))
print('There are {} ones in picture.'.format(one_cnt))
canvas.mainloop()
Tasks:
1. What would need to be modified in the program if we wanted a reflection of the image to be drawn
after every press of the button Mirror.
2. How do we modify the program so that the squares of the image that are the same color as the
background are not drawn (since it is unnecessary)?
3. We wish to draw as few squares as possible for different images . How do we figure out which
background color would be more convenient and use that color for the background?
80
4. What is the current size of an individual square and how can we change it?
task
'' [] [[]] txt Cnv
20 Table of Frequency
file = open('files/frequency_table.txt')
count = [0] * 26
for line in file:
print(line, end='')
for char in line:
uppercase = char.upper()
if 'A' <= uppercase <= 'Z':
count[ord(uppercase) - 65] += 1
print()
print('Frequency of the individual letters in the text:')
for i in range(26):
if count[i] != 0:
print(chr(65 + i), '-', count[i])
print('Missing letters:')
for i in range(26):
if count[i] == 0:
print(chr(65 + i), end=' ')
Tasks:
1. How can we sort the table by the frequencies of occurrence of the individual characters?
2. What other method of storing the frequencies of occurrence of the characters is there?
3. What would have to be modified in the program if we wished to find out the frequencies of
occurrence of punctuation marks as well?
task
'' [] txt
81
21 Scrambled Text 1
import random
file1.close()
file2.close()
Tasks:
1. What is executed in the line labeled {line A} and why do we have to use the function list?
2. If we were not familiar with the function shuffle, how could we solve this exercise?
3. What is executed in the line labeled {line B}? What could we replace this line with?
task
'' [] txt
22 Scrambled Text 2
import random
def string_shuffle(string):
letters = list(string)
random.shuffle(letters)
return ''.join(letters)
def strip_word(word):
stripped_word = ''
wrong_begin = ''
wrong_end = ''
i = 0
while word[i] in skip:
wrong_begin += word[i]
i += 1
while i < len(word) and not (word[i] in skip): # {line A}
82
stripped_word += word[i]
i += 1
wrong_end = word[i:]
return wrong_begin, stripped_word, wrong_end
skip = '.,!?():#@~[]0123456789<>{}^%*-+/\\'
file1 = open('files/scrambled_text_input2.txt', 'r')
file2 = open('files/scrambled_text.txt', 'w')
file1.close()
file2.close()
Tasks:
1. What would happen if we changed the order of conditions in the line labeled {line A} and why?
2. What would happen if we left out the condition in the line labeled {line B}?
3. What can we replace the method join with?
task
'' [] txt
23 Ciphertext 1
want_decrypt = input('If you want decrypt type Y and press Enter: ')
decrypt = False
input_file = 'files/inputted_text.txt'
output_file = 'files/cifertext_1.txt'
83
if want_decrypt == 'Y':
decrypt = True
input_file, output_file = output_file, input_file # {line C}
file1 = open(input_file, 'r')
file2 = open(output_file, 'w')
for line in file1:
new_line = encrypt(line, key, decrypt)
file2.write(new_line)
print(line)
print(new_line)
file1.close()
file2.close()
Tasks:
1. What will always be true about the length of the string stored in the variable rep_key in the line
labeled {line A}?
2. What does the notation in the line labeled {line B} do? Why is there % 26?
3. What is going on in the line labeled {line C}?
4. Which line(s) of the program ensure that only letters of the English alphabet are processed?
5. Which segment of the program changes the transformation of a character from encoding to
decoding?
task
'' txt fx()
24 Ciphertext 2
import random
def encrypt(inp, decrypt):
outp = ''
if decrypt:
shift = -1 * (ord(inp[0]) - 96)
inp = inp[1:] # {line A}
else:
shift = random.randint(1, 25)
outp += chr(shift + 96)
for char in inp:
if 'a' <= char <= 'z':
outp += chr( (ord(char)-97 + shift) % 26 + 97) # {line B}
else:
outp += char
return outp
want_decrypt = input('If you want decrypt type Y and press Enter: ')
decrypt = False
input_file = 'files/inputted_text.txt'
output_file = 'files/cifertext_2.txt'
if want_decrypt == 'Y':
decrypt = True
input_file, output_file = output_file, input_file # {line C}
file1 = open(input_file, 'r')
file2 = open(output_file, 'w')
for line in file1:
84
new_line = encrypt(line, decrypt)
file2.write(new_line)
print(line)
print(new_line)
file1.close()
file2.close()
Tasks:
1. What would happen if we left out the line labeled {line A}?
2. What does the notation in the line labeled {line B} do? Why is there % 26?
3. What is going on in the line labeled {line C}?
4. Which line(s) of the program ensure that only letters of the English alphabet are processed?
5. Which segment of the program changes the transformation of a character from encoding to
decoding?
6. How is an empty line in an inputted file encoded?
task
'' txt fx()
25 Lottery
import random
def shuffling():
numbers = []
for i in range(1, 50):
numbers.append(i)
random.shuffle(numbers)
return numbers[:6]
def to_list(string):
newlist = string.strip().split()
for i in range(len(newlist)):
newlist[i] = int(newlist[i])
return newlist
outp = shuffling()
print('Tossed numbers:', outp)
guess = to_list(inp)
guessed, count = same(outp, guess)
print('Guessed count:', count, 'guessed:', guessed)
85
for line in file:
guess_numbers = to_list(line)
guessed, count = same(guess_numbers, outp)
correct[count] += 1
file.close()
for i in range(len(correct)):
print('{} numbers was correctly guessed by {} players'.format(i,
correct[i]))
Tasks:
1. Why do we create a seven-item list in the line labeled {line A} when there are only 6 numbers
drawn in the lottery?
2. Is the order in which the parameters of the function same() are given important (can we give the
function the drawn numbers first and then the numbers that the player has guessed)?
3. What other way is there for drawing 6 numbers in a lottery?
4. How can we determine the number of participants in the lottery just by adding some lines to the end
of the program without reading the file again?
task
'' [] txt fx()
86
26 Landscape
def draw_hill():
hill = []
direction = random.choice((1,-1)) # {line A}
hill.append(0)
hill.append(random.randint(200, 500))
summit = random.randint(100, 600)
for i in range(summit // 10):
new_value = hill[-1] + direction * random.randint(0, 5)
hill.append(i*10+1)
hill.append(new_value)
direction = -1 * direction
for i in range((700-summit) // 10 + 10):
new_value = hill[-1] + direction * random.randint(0, 5)
hill.append(i*10+summit)
hill.append(new_value)
def draw(event):
canvas.delete('all')
for i in range(10):
draw_hill()
#draw_hill()
canvas.bind_all('<space>', draw)
canvas.mainloop()
Questions:
1. What causes the notation in the line {line A}? How else could we write it?
2. Explain the notation in the line {line B}.
3. How is the change in elevation solved between the first part of the mountain and the second part?
4. How much information about the mountains is saved in memory while this program is running? Is it
possible to optimize memory usage? If yes, how?
task
[] Cnv fx()
87
27 Virus
import random
file = open('files/virus.txt', 'r')
lines = file.readlines()
file.close()
def printout():
for line in lines:
print(line, end='')
def decision():
return random.choice((True, False))
def process_line(line):
words = []
words = line.split()
if decision():
random.shuffle(words)
new_line = ''
for word in words:
if decision():
word = word[::-1]
new_line += word + ' '
return new_line[:-1] + '\n'
def save_to_file(name):
file = open(name, 'w')
file.writelines(lines)
file.close()
printout()
print('='*60)
if decision():
random.shuffle(lines)
for i in range(len(lines)): # {line A}
line = lines[i]
lines[i] = process_line(line[:-1]) # {line B}
printout()
save_to_file('files/virus_output.txt')
Questions:
1. What happens if we replace the loop starting on the line marked {line A} with this:
2. What happens when we write line instead of line[:-1] in the line {line B}?
3. Why is it not possible to create an input text file out of an output text file (with the inverse process)?
4. How should we edit the input text file so that we can reconstruct the original file out of it? Let's
suppose that we don't leave out any of the original program's transformations.
task
'' [] txt fx()
88
28 Voting 1
import random
count = [0] * 10
eliminated = []
results = []
for i in range(10):
print('Player: {} got {} votes'.format(i+5220, count[i]))
if not i+5220 in eliminated:
results.append((count[i], i+5220)) # {line B}
Questions:
1. What happens if any numbers appear multiple times in the file voting_droppedout.txt?
2. What happens if the file voting_droppedout.txt is empty?
3. How do we find out and print the ranking of a competitor's success?
4. Why do we subtract the number 5220 in the line {line A}?
5. What does the variable results contain after the line {line B} has ended?
6. What does the variable dropout contain in the line {line C}?
task
'' [] () txt
89
29 Image compression
def process_line(inp):
inp = inp.strip()
length = len(inp)
outp = ''
if inp[0] == '1':
outp += '0 '
count, i = 0, 0
processing = inp[0]
for char in inp:
if char == processing:
count += 1
else:
outp += str(count) + ' '
processing = char
count = 1
outp += str(count) + ' ' # {line A}
return outp[:-1] + '\n' # {line B}
Questions:
1. Why is it necessary to bind space to the output in the line {line A}?
2. What do we do in the line {line B} and why?
3. How many times is the line {line C} executed in this program?
task
'' txt fx()
90
30 NIM
def draw(count):
canvas.delete('match')
for i in range(count):
match(i * 20 + 20, 50)
def congratulation(player):
canvas.delete('msg')
canvas.create_text(225, 100, text='Congratulations, the winner is:'
+ str(player), fill='red', font='Arial 20')
def inp(event):
if '1' <= event.char <= '3': # {line A}
move = int(event.char)
global match_cnt, turn # {line B}
if match_cnt - move >= 0:
match_cnt -= move
draw(match_cnt)
if match_cnt == 0:
congratulation(turn)
else:
turn = 3 - turn
show_msg(turn, match_cnt)
turn = 1
match_cnt = 15
draw(match_cnt)
show_msg(turn, match_cnt)
canvas.bind_all('<Key>', inp)
canvas.mainloop()
Questions:
1. Which part of the program ensures that we can't pick more matches than are available and how?
2. Explain what happens if we leave out the line {line A} in the program. Justify your answer in
detail.
3. Explain what happens if we leave out the line {line B} in the program. Justify your answer in
detail.
task
'' Cnv fx()
91
31 Black and White picture
import tkinter
def draw(all_shades):
canvas.delete('all')
file = open(filename, 'r')
line = file.readline() # {line A}
y = 0
for line in file:
line = line.strip()
x = 0
for i in range(width):
shade = line[i*2:i*2+2] # {line B}
if not all_shades:
color = 'black'
if shade > '7f': # {line C}
color = 'white'
else:
color = '#' + 3 * shade # {line D}
point(i, y, color)
canvas.update() # {line E}
y += 1
file.close()
def bw():
draw(False)
filename = 'files/bw_picture_1.txt'
file = open(filename, 'r')
line = file.readline()
file.close()
size = line.split()
width = int(size[0])
height = int(size[1])
canvas = tkinter.Canvas(width=width, height=height, bg='white')
canvas.pack()
button1 = tkinter.Button(text='Only black and white', command=bw)
button1.pack()
draw(True)
Questions:
1. What happens when we leave out the line {line A} in the program?
2. What happens when we leave out the line {line E} in the program?
3. What happens when we move the line {line E} to the inner circle?
4. Explain why we multiply by 2 in the line {line B}.
5. There is a comparison in the line {line C}. What data is compared and how does this comparison
work? Will it work correctly based on what we need?
6. Explain the notation in the line {line D}.
task
'' txt Cnv fx()
92
32 File Conversion 1
def process_line(inp):
count = len(inp) // 2 # {line A}
outp = ''
for i in range(count):
shade = inp[i*2:i*2+2] # {line B}
color = '0'
if shade > '7f': # {line C}
color = '1'
outp += color + ' '
outp = outp[:-1] + '\n' # {line D}
return outp
Questions:
1. Why do we divide by 2 in the line {line A}?
2. What happens when there is / isn't the character '\n' in the input?
3. Explain why we multiply by 2 in the line {line B}.
4. There is a comparison in the line {line C}. What data is compared and how does this comparison
work? Will it work correctly based on what we need?
5. Explain the notation in the line {line D} and explain the purpose of its usage.
6. How many times will the body of the loop in the line {line E} be executed in the program for an
input text file containing six lines (for example, the one in the example in the assignment)?
task
'' txt fx()
93
33 Color Tone Spektrum
import tkinter
canvas = tkinter.Canvas(width=450, height=520, bg='white')
canvas.pack()
Questions:
1. How do we count the scale in the program? How else could we count it?
2. If we couldn't / weren't able to convert a number from hexadecimal base, how else could we figure
out the frequency of the appearance of individual tones? How would we remember it in the
program?
3. What happens when we leave out adding 1 in the line {line A}?
task
'' [] txt Cnv
94
34 Image Decompression
def process_line(inp):
inp = inp.strip()
sequence = inp.split()
color = 0
outp = ''
for element in sequence:
count = int(element)
outp = outp + count * str(color)
color = 1 - color # {line A}
return outp + '\n' # {line B}
Questions:
1. What do we do in the line {line A} and why?
2. Why do we add the character \n to the output in the line {line B} ?
3. How many times will the line {line C} be executed in this program?
4. What will the function process_line() return from an empty string?
5. Why is the variable color in the function process_line(), not the string?
task
'' [] txt fx()
95
35 Compressed Image Drawing
import tkinter
def draw(first):
canvas.delete('all')
file = open(name, 'r')
line = file.readline() # {line A}
y = 0
for line in file:
sequence = line.split()
x = 0
color = first # {line B}
for item in sequence:
count = int(item)
if color:
points(x, y, count)
color = not color # {line C}
x += count
canvas.update() # {line D}
y += 1
file.close()
def negative():
draw(False)
name = 'files/image_decompression_3.txt'
file = open(name, 'r')
line = file.readline()
file.close()
size = line.split()
width = int(size[0])
height = int(size[1])
canvas = tkinter.Canvas(width=width, height=height, bg='white')
canvas.pack()
button1 = tkinter.Button(text='Negative', command=negative)
button1.pack()
draw(True)
canvas.mainloop()
Questions:
1. What is going to happen and what outcome is it going to have visually on the screen if we move the
line {line B} right after {line A}?
2. What are we doing in the line {line C} and why? What is going to happen if we move {line C}
over and it becomes a part of the if construction?
3. Which points of the image are we drawing and which points do we have to draw?
4. If we have two images in a file of the same size, which one is going to be drawn faster?
5. What happens if we leave out the line {line D} in the program?
task
[] txt Cnv fx()
96
36 Creation of a Crossword Puzzle 2
crossword = []
file = open('files/crossword2-1.txt', 'r')
secret = file.readline().strip()
i = 0
for r in file:
r = r.strip()
shift = -1 * r.index(secret[i]) # {line A}
row = (shift, r)
crossword.append(row)
i += 1
Questions:
1. Explain what the line {line A} does?
2. Why do we read the first line of the file before the loop which reads all the other lines in the file?
What would happen if we did not read it before the loop? How would we need to edit the program?
3. What do we need to change in the program to be able to input the left upper point of the whole
crossword and not the column with the puzzle?
4. What happens if a letter from the puzzle appears more than once in a row of the crossword?
5. What happens if a letter from the puzzle does not appear in a row of the crossword?
task
'' [] () txt Cnv fx()
97
37 Voting 2
import random
files = []
for i in range(5220, 5230): # {line A}
s = open('files/'+str(i)+'.txt', 'w')
files.append(s)
for s in files:
s.close()
Questions:
1. What does the for loop that starts in the line {line A} do?
2. In what relationship will the input file and the output files be?
3. What is the minimum amount of lines that an output file can have?
4. How can we recreate an input file using the output files?
5. How do we ensure that output files won't be created for participants who dropped out (a list of
them is in the file voting_droppedout.txt)?
task
'' [] txt
98
38 Costumer Satisfaction 1
satisfied = [0] * 24
unsatisfied = [0] * 24
Questions:
1. What is going to change if we change the counting of unsatisfied customers to negative numbers in
the line {line A}?
2. What's going to happen if the input file is empty?
3. What is the loop doing in the line {line B} and why do we need to have it?
4. Why do we look for index in the list unsatisfied, and not unsatified2 in the line {line C}?
5. Suggest a format for the file in which data is going to be written so that it has the smallest file size.
task
'' [] txt
99
39 Costumer Satisfaction 2
import tkinter
canvas = tkinter.Canvas(width=480, height=520, bg='white')
canvas.pack()
unsatisfied = [0] * 24
unsatisfied_cnt = sum(unsatisfied)
bad_cnt = max(unsatisfied)
hour = unsatisfied.index(bad_cnt)
print('The highest number of unsatisfied customers: {}. Hour:{}'.format(
bad_cnt, hour))
for i in range(24):
if unsatisfied[i] > 0:
print('Hour:{} Unsatisfied customers: {}'.format(i, unsatisfied[i]))
canvas.create_rectangle(i*20, 500, i*20+18, 500-unsatisfied[i],
fill='red')
canvas.create_text(i*20+9, 510, text='{:02}'.format(i), fill='red')
Questions:
1. What is the only thing you have to change for the program to draw a histogram of satisfied
customers?
2. What is going to happen if the input file is empty?
task
'' [] txt
100
40 Data Analysis
opinions = [0] * 24
Questions:
1. Based on what do we know that the recording is from the next day?
2. How does time comparison work?
task
'' [] txt
101
41 Ordering Food
import tkinter
canvas = tkinter.Canvas(width=420, height=150, bg='white')
canvas.pack()
def draw():
for i in range(len(colors)):
canvas.create_rectangle(x+i*size, y, x+i*size+size-2, y+size-2,
fill=colors[i], outline='')
def click(xy):
if y < xy.y < y + size:
order = (xy.x - x) // size
if 0 <= order < len(colors):
print(order)
student = entry1.get()
if student != '':
file = open('files/food_choice.txt', 'a')
file.write(student+' '+abbr[order]+'\n')
file.close()
Questions:
1. At first glance, we might think that opening and closing the file in the line {line A} is needless.
Why do we need to do it?
2. What do we do in the line {line B} and why?
3. What has to be done if the food choices grow by another available food, represented by the color
yellow and the letter y?
4. What do you suggest doing so that the program won't allow us write the same student's code to the
file twice?
task
'' [] txt Cnv
102
42 Save the Falling Egg
def new_game():
global letter, ex, ey
ex, ey = random.randint(20, 400), 0
letter = chr(random.randrange(26) + 97)
letter = ''
ex, ey = 0, 0
def draw(show):
canvas.delete('egg')
canvas.create_oval(ex-10, ey-20, ex+10, ey+20, tags='egg')
if show:
canvas.create_text(ex, ey, text=letter, font='Arial 20',
tags='egg')
def falling():
global ey
ey += 5
show = ey > 400 - 400 // 3 # {line A}
draw(show)
if ey < 400:
canvas.after(100, falling)
def key(event):
if event.char == letter:
new_game()
new_game()
falling()
canvas.bind_all('<Key>', key)
canvas.mainloop()
Questions:
1. What does the notation in the line {line A} mean and what consequences does it have on the
program's performance?
2. What has to be done so that the letters in the program are not random but rather the letters of the
input word shown step by step?
task
'' Cnv fx() aft.
103
43 Pyrotechnician
def draw():
for i in range(len(colors)):
canvas.create_rectangle(x, y+i*10, x+width, y+i*10+9, fill=colors[i])
def click(xy):
global done
if x < xy.x < x + width and time > 0:
order = (xy.y - y) // 10
if 0 <= order < len(colors):
print(order)
if order == correct:
done = True
canvas.create_text(200, 130, text='You won!', font='Arial 30')
def animation():
global time
time -= 1
canvas.delete('time')
canvas.create_text(300, 75, text=time, font='Arial 30', fill='red',
tags='time')
if time > 0 and not done:
canvas.after(100, animation)
elif not done:
canvas.delete('all')
draw()
canvas.bind('<Button-1>', click)
animation()
canvas.mainloop()
Questions:
1. What time are we going to see on the screen last?
2. Why are we finding out in the function if time > 0 ?
3. Why is in the function animation() elif with a condition and else without a condition not
sufficient?
4. What is going to happen if the color list is empty?
task
[] Cnv fx() aft.
104
44 Guess the Falling Word
def new_game():
global letter, wx, wy, word, guessed
wx, wy = random.randint(20, 400), 0
word = words[random.randrange(len(words))]
guessed = '*' * len(word)
def draw():
canvas.delete('word')
canvas.create_text(wx, wy, text=guessed, font='Arial 20',
anchor='nw', tags='word')
def falling():
global wy
wy += 5
draw()
if wy < 400 and guessed != word:
canvas.after(500, falling)
elif guessed != word:
canvas.create_text(200, 200, text='You lose!')
def key(event):
global guessed
if event.char in word and not event.char in guessed:
new_guess = ''
for char in word:
if char in guessed or char == event.char:
new_guess += char
else:
new_guess += '*'
guessed = new_guess
new_game()
falling()
canvas.bind_all('<Key>', key)
canvas.mainloop()
Questions:
1. What do we have to change in the program and how so that after pressing a key, only the first
unsolved appearance of the letter is shown and not all the appearances?
2. Why do we have the variable new_guess in the function key() instead of just modifying the string
guessed?
task
'' Cnv fx() aft.
105
45 Vocabulary Learning
The file can be read in multiple ways. Since Spanish and English words are on individual lines and the lines
take turns, we have to solve the problem of reading these lines. We show this method of solving in the first
demonstration of the solution. In the second demonstration, we have read the whole list from the file to a
list and have used slices to split the languages.
Solution 1:
sp = []
en = []
file = open('files/vocabulary_learning.txt', 'r')
i = 0
for line in file:
if i % 2 == 0:
sp.append(line.strip())
else:
en.append(line.strip())
i += 1
file.close()
lang = input('From Spanish to English? (Y/N): ')
Solution 2:
106
else:
print('Correct!')
print('Number of wrong answers:' + str(wrong))
Questions:
1. What format would you suggest for the input file with words?
2. What happens if there is an odd number of lines in the input file? In this case, is there going to be
any difference between the first and second solutions?
3. What happens if we substitute the notation: a, b = en[:], sp[:] with the notation:
a, b = en, sp in the program?
task
'' [] txt
46 Hangman
import random
file = open('files/hangman.txt', 'r')
words = file.readlines()
file.close()
random.shuffle(words)
word = words[0].strip()
guess = '.' * len(word)
print('Guess letters in word!')
print(guess)
wrong = 0
while guess != word and wrong < 10: # {line A}
char = input('Enter the letter:')[0]
if char in word: # {line B}
new_word = ''
for i in range(len(word)):
if char == word[i]:
new_word += char # {line C}
else:
new_word += guess[i]
print('letter ', char, ' is in word')
guess = new_word
else:
wrong += 1
print('wrong guess...')
print(guess)
if guess == word:
print('Congratulations, you guessed the whole word!')
else:
print('You lose, 10x wrong guess!')
Questions:
1. What happens if the input file is empty?
2. What happens if there is a phrase in the file instead of an individual word?
3. What happens if the user enters more letters or presses enter?
4. Explain under which circumstances the condition in the line {line A} is true.
5. Is the condition in the line {line B} necessary? What has to be done so that we can leave it out?
107
6. Why are we creating a new word in a new variable in the line {line C}?
task
'' [] txt
47 Barcode
def generate_code():
code = chr (random.randrange(9) + ord('1'))
for i in range(7):
code += chr (random.randrange(10) + ord('0'))
return code
def draw(event):
global read
if not read:
canvas.delete('all')
for ix in range(2):
for iy in range(2):
code = file.readline().strip()
if code != '':
draw_code(ix * 100 + 10, iy * 100 + 10, code)
else:
read = True
if read:
file.close() # {line B }
code = generate_code()
print(code)
draw_code(20, 10, code)
file = open('files/barcode_1.txt', 'r')
read = False
canvas.bind_all('<space>', draw)
canvas.mainloop()
Questions:
1. Why did we prefer to remember the code in a text string in the solution? What would have changed
if we had remembered it as a number?
2. There is an if in the line {line A}. What happens if we remove it?
3. The file is closed in the line {line B}. Why can't we close it immediately in the else branch when
we set read = True?
4. How does the program performance change when we discard the variable read?
108
5. What is the program going to do if the input text file is empty?
task
'' txt Cnv fx()
48 Multiplication
import random
def generate_task():
a, b = random.randrange(11), random.randrange(11)
task = '{} * {} = '.format(a, b)
return task, a * b # {line A}
count, points = 0, 0
while len(tasks) > 0:
count += 1
task = tasks.pop(0)
print(task[0], end='') # {line B}
inp = input('')
answer = int(inp)
if answer != task[1]:
tasks.append(task)
elif count <= 10:
points +=1
print('Points awarded:', points)
Questions:
1. When and where can a situation occur that causes the list problems to be empty?
2. What is the variable amount for? Which property of the program does it ensure?
3. What data type does the function in the line {line A} return?
4. What is ensured with the notation in the line {line B}?
5. If we enter characters other than numbers into the input, the program fails. What is the easiest way
to prevent that error?
task
'' [] () txt fx()
109
49 Seat Reservation System
import tkinter
canvas = tkinter.Canvas(width=600, height=300, bg='white')
canvas.pack()
rowcount = 10
size = 40
busx, busy = 50, 50
def take(seat):
global occupied, empty
index = empty.index(seat)
empty.pop(index)
occupied.append(seat)
colorize(seat, 'red')
def free(seat):
global occupied, empty
index = occupied.index(seat)
occupied.pop(index)
empty.append(seat)
colorize(seat, 'lightgreen')
def info():
canvas.delete('info')
canvas.create_text(busx, 220, text='Available seats: '+str(len(empty)),
tags='info', anchor='nw')
canvas.create_text(busx, 240, text='Occupied: '+str(len(occupied)),
tags='info', anchor='nw')
free_middle = 0
for seat in empty:
if 2 <=seat % 4 <= 3:
free_middle += 1
canvas.create_text(busx, 260, text='Available middle-seats: '+
str(free_middle), tags='info', anchor='nw')
def click(event):
if (busx < event.x < busx + size * rowcount and
busy < event.y < busy + size * 4):
ix = (event.x - busx) // size
iy = (event.y - busy) // size
seat = ix * 4 + iy + 1
colorize(seat, 'red')
if seat in empty:
take(seat)
110
else:
free(seat)
info()
def save():
file = open('files/seat_reservation_output.txt', 'w')
for j in range(1, 5):
line = ''
for i in range(j, rowcount*4+1, 4):
if i in empty:
line += '{:2} '.format(i)
else:
line += ' X' + ' '
line = line[:-1] + '\n'
file.write(line)
file.close()
occupied = []
empty = []
for i in range(rowcount*4):
empty.append(i+1)
colorize(i+1, 'lightgreen')
info()
canvas.mainloop()
Questions:
1. Think of a different way of remembering free and occupied seats.
2. How could the task be solved without remembering free and occupied seats?
3. Why is there a for loop immersed when saving? Would it be possible to write the solution with a
loop that goes for the number of seats and is not immersed?
task
'' [] txt Cnv fx()
111
50 Image Contour
import tkinter
def draw(first):
#canvas.delete('all')
file = open(filename, 'r')
line = file.readline() # {line A}
y = 0
for line in file:
sequence = line.split()
x = 0
color = first # {line B}
for element in sequence:
count = int(element)
if color:
points(x, y, count)
color = not color # {line C}
x += count
canvas.update() # {line D}
y += 1
file.close()
def another_way():
draw(False)
filename = 'files/image_contour_1.txt'
file = open(filename, 'r')
line = file.readline()
file.close()
size = line.split()
width = int(size[0])
height = int(size[1])
canvas = tkinter.Canvas(width=width, height=height, bg='white')
canvas.pack()
button1 = tkinter.Button(text='Another way', command=another_way)
button1.pack()
draw(True)
canvas.mainloop()
Questions:
1. What is going to happen and what visual outcome is it going to have on the screen if we move the
line {line B} right after {line A}?
2. What are we doing in the line {line C} and why? What is going to happen if we move {line C}
over and it becomes a part of the if construction?
3. If we have two images in the file of the same size, which one will be drawn faster?
4. What happens if we leave out the line {line D} from the program?
task
txt Cnv
112
51 Announcement Compression 1
Questions:
1. How is the program going to be influenced when we begin the input sentence with a capital letter vs.
a lower-case letter? Justify your answer.
2. What does the notation in the line {line A} mean?
3. How else do we change a lower-case letter of the English alphabet to a capital letter without using
the method upper?
4. What does the last line of the code do?
task
'' []
113
52 Announcement Compression 2
Questions:
1. How is the program going to be influenced when we begin the input sentence with a capital letter vs.
a lower-case letter? Justify your answer.
2. What does the notation in the line {line A} mean?
3. What happens if we leave out the line {line B} in the program?
4. What has to be changed if we want to create a return function out of compressing and creating the
original string?
task
'' []
114
53 Skyline
import tkinter
def draw():
file = open('files/street_build_up.txt')
limit = int(entry1.get())
y = 150
x = 10
height2 = 0
for line in file:
numbers = line.split()
width = int(numbers[0])
height = int(numbers[1])
if height > 0:
canvas.create_rectangle(x, y - height, x + width, y, fill='grey')
else:
canvas.create_line(x, y, x + width, y, width=3, fill='green')
if height != 0 and height2 != 0 and abs(height - height2) > limit:
canvas.create_line(x, y - height, x, y - height2,
width=3, fill='red')
x += width
height2 = height
file.close()
Questions:
1. What will the program draw if there is a line with the values 0 0 in the file?
2. The program highlights wall differences which are too big between two buildings with red. What
would we have to change so that the program would also highlight changes that are too big
between a building and an open space?
3. What is the program going to do if there is a negative number as the first number in any of the lines?
task
[] txt Cnv
115
54 Boats
The following solution places the boats step by step from the top.
import tkinter
def another():
global row, col # possible position (row/column) of a new ship
found = False
while row < height and not found:
if (harbour[row][col]=='0' and harbour[row][col+1]=='0'
and harbour[row][col+2]=='0'):
canvas.create_rectangle(col * square + 2, row * square + 2,
(col+3)*square-2, (row+1)*square-2,
width=0, fill='yellow')
found = True
col += 4
if col > width - 3:
row += 1
col = 0
else:
col += 1
if col > width - 3:
row += 1
col = 0
if not found:
canvas.create_text(width * square / 2, height * square / 2,
text='Full capacity', font='Arial 30')
square = 50
file = open('files/boats.txt')
numbers = file.readline().split()
width = int(numbers[0])
height = int(numbers[1])
harbour = []
for r in range(height):
harbour.append(file.readline().split())
file.close()
canvas = tkinter.Canvas(width=square * width, height=square * height)
canvas.pack()
Questions:
1. Which part of the program ensures that the third square we are placing is placed on an empty area
and not outside the created structure so that the program doesn't crash?
116
2. Which part of the program ensures that two boats in one line don't touch each other?
3. Which attribute must the map have so that it is not possible to place even one boat (with the
assumption that the map has the least mainland)?
4. What other structure can we use in the program if we want to evade a list of lists or a list of N-
tuples?
task
[[]] txt Cnv fx()
55 Drawing robot 2
import tkinter
def do(cmd):
global robotx, roboty, length, angle
if cmd == 'line':
if angle == 0:
x, y = robotx, roboty - length
elif angle == 90:
x, y = robotx + length, roboty
elif angle == 180:
x, y = robotx, roboty + length
elif angle == 270:
x, y = robotx - length, roboty
canvas.create_line(robotx, roboty, x, y, width=3)
robotx, roboty = x, y
elif cmd == 'left':
angle -= 90
if angle < 0:
angle += 360
elif cmd == 'right':
angle = (angle + 90) % 360
def fromfile():
file = open('files/drawing_robot_2.txt')
repeatcnt = 0
cmdlist = [] # command list in loop
for line in file:
cmd = line.strip()
parts = cmd.split()
if parts[0] == 'repeat':
repeatcnt = int(parts[1])
elif parts[0] == 'repeatend':
# loop execution
for i in range(repeatcnt):
for cmd in cmdlist:
do(cmd)
cmdlist = [] # {line A}
repeatcnt = 0
else:
if repeatcnt > 0: # {line B}
cmdlist.append(cmd)
else:
do(cmd) # command execution
117
file.close()
Questions:
1. What exactly are the contents of the variable list before its assignment in the line {line A}?
2. Why is there a condition in the line {line B} for the number of repetitions when, should the for
loop repeat zero times, it wouldn't even execute once?
3. Is the program also going to work for the immersed loops? Why?
task
'' [] txt Cnv fx()
56 Level Editor 1
In the demonstration of possible solutions to the level editor task, we have chosen to draw squares. We
remember their ID numbers in a list. After using the mouse to click, we can change their color with the
method itemconfig. As an alternative, it is possible to just draw a net consisting of squares made out of
lines and only after clicking it would it draw colored squares. In the level editor task, we need to again
remember at least the list of square colors to save the data to the file.
import tkinter
def click(event):
canvas.itemconfig(board[event.y // side][event.x // side],
fill=entry1.get())
def save():
file = open('files/level_editor1_output.txt', 'w')
for r in range(height):
for c in range(width):
file.write(canvas.itemcget(board[r][c], 'fill'))
file.write('\n')
file.close()
side = 40
width = 10
height = 10
canvas = tkinter.Canvas(width=width * side, height=height * side)
board = []
for r in range(height):
line = []
for c in range(width):
line.append(canvas.create_rectangle(c*side, r*side,
(c+1)*side, (r+1)*side,
fill='#FFFFFF'))
board.append(line)
canvas.pack()
entry1 = tkinter.Entry()
entry1.insert(0, '#FF0000')
entry1.pack()
button1 = tkinter.Button(text='Save', command=save)
button1.pack()
118
canvas.bind('<Button-1>', click)
Questions:
1. What is remembered in the variable net? In what form?
2. What happens if we enter a color by its name into entry rather than by its code (e.g. red)? How
does it affect the output text file, its structure and the consequential loading of the level from the
text file?
3. What happens if we click multiple times on any of the squares in the net with the same color / with
a different color? What effect is it going to have on memory and the displayed shapes?
task
[] txt Cnv fx()
57 Level Editor 2
In the demonstration of the possible solutions to the level editor task, we have chosen to draw squares.
We remember their ID numbers in a list. After using the mouse to click, we can change their color with the
method itemconfig. As an alternative, it is possible to just draw a net consisting of squares made out of
lines and only after clicking it would it draw colored squares. Thereafter, we can remember the colors of
squares in a list.
import tkinter
def click(event):
global start_r, start_c
r = event.y // side
c = event.x // side
if start_r == -1: # Starting point
start_r, start_c = r, c
canvas.itemconfig(board[r][c], fill='#0000FF')
else: # Ending point
if start_r == r: # horizontal wall
for i in range(min(c, start_c), max(c, start_c) + 1):
canvas.itemconfig(board[r][i], fill='#0000FF')
elif start_c == c: # vertical wall
for i in range(min(r, start_r), max(r, start_r) + 1):
canvas.itemconfig(board[i][c], fill='#0000FF')
else: # when second click is diagonal
canvas.itemconfig(board[start_r][start_c], fill='#FFFFFF')
start_r, start_c = -1, -1
side = 40
width = 10
height = 10
canvas = tkinter.Canvas(width=width * side, height=height * side)
board = []
for r in range(height):
line = []
for c in range(width):
line.append(canvas.create_rectangle(c*side, r*side,
(c+1)*side, (r+1)*side,
fill='#FFFFFF'))
board.append(line)
canvas.pack()
start_r, start_c = -1, -1
canvas.bind('<Button-1>', click)
119
Questions:
1. What is remembered in the variable board? In what form?
2. What happens if we click on squares that are connected by a diagonal segment?
3. What happens if we click on any of the squares in the net multiple times?
task
[] Cnv fx()
58 Subway Line
import tkinter
file = open('files/subway_line_route.txt')
subway = file.readlines()
file.close()
color = subway.pop(0).strip() # {line A}
x = 20
canvas.create_line(x, 205, x + 40 * (len(subway) - 1), 205,
width=3, fill=color)
for i in range(len(subway)):
name = subway[i].strip()
if name[0] == '*':
name = name[1:]
express = True
else:
express = False
canvas.create_text(x, 200, text=name,
angle=45, anchor='sw', font='Arial')
if i == 0 or i == len(subway) - 1: # Terminals # {line B}
canvas.create_rectangle(x - 20, 200, x, 220, fill=color, width=0)
elif express:
canvas.create_oval(x - 10, 200, x, 210,
width=2, fill='white', outline=color)
else:
canvas.create_oval(x - 10, 200, x, 210, fill=color, width=0)
x += 40
canvas.pack()
Questions:
1. What happens if there is an empty line in the input file?
2. What does the notation in the line {line A} do?
3. Why is -1 under a condition in the line {line B}?
4. We want only express stations to be shown on the map. What would be the easiest way to edit the
program in order to accomplish our intentions?
task
'' [] txt Cnv
120
59 Bus Capacity Analysis
import tkinter
def push(event):
global y
if len(stops) > 0:
canvas.create_rectangle(150, y + 2, 250, y + 18)
curcount = stops.pop(0)
if curcount > capacity:
color = 'red'
else:
color = 'green'
canvas.create_rectangle(150, y + 2, 150 + 100 * curcount / capacity,
y + 18, fill=color)
y += 20
file = open('files/bus_utilization_extent.txt')
capacity = 0
stops = []
count = 0
y = 20
for line in file:
if capacity == 0: # First line
capacity = int(line)
else:
parts = line.split()
count += int(parts[0]) # Get on
count -= int(parts[1]) # Get off
stops.append(count)
canvas.create_text(5, y, text=' '.join(parts[2:]), anchor='nw')
#using 'join' method due to stop names containing more than one word
y += 20
file.close()
y = 20
canvas.bind('<Key>', push)
canvas.mainloop()
Questions:
1. What can we replace the method join with? With what sequence of commands?
2. What happens if we change the capacity shown in the first line of the text file to a negative number?
3. What happens if we leave out the first if in the function push?
4. If we first had the name of the stop and then the numbers of people getting on and off in the lines
of the input file, what effect would it have on the solution to this task?
task
'' [] txt Cnv fx()
121
60 Calculator
import tkinter
def push(event):
global result, display, operation, operand
if event.y >= 70: # buttons +/-/=/C
button = event.x // 30
if button < 4: # Clear
if button == 0:
result = 0
elif button == 1:
operation = '+'
operand = result
result = 0
elif button == 2:
operation = '-'
operand = result
result = 0
elif button == 3: # equals
if operation == '+':
result += operand
elif operation == '-':
result = operand - result
canvas.itemconfig(display, text=result)
for i in range(10):
canvas.create_rectangle(i * 30, 40, (i + 1) * 30, 70)
canvas.create_text(i * 30 + 15, 55, text=i)
for i in range(4):
canvas.create_rectangle(i * 30, 70, (i + 1) * 30, 100)
canvas.create_text(15, 85, text='C')
canvas.create_text(45, 85, text='+')
canvas.create_text(75, 85, text='-')
canvas.create_text(105, 85, text='=')
operand = 0
result = 0
display = canvas.create_text(3, 3, anchor='nw', font='Courier 30', text=0)
canvas.bind('<Button-1>', push)
Questions:
1. Can the solution to a calculation be negative? What does this mean for our calculator?
2. What has to be edited in the program so that the calculator can also multiply numbers?
3. How do we modify the program so that we can record the calculations done on the calculator into a
text file?
task
'' Cnv fx()
122
61 Division
def check():
global a, b
colors = ('red', 'green', 'blue')
result = a // b
if int(entry1.get()) == result:
txt = 'CORRECT'
else:
txt = 'INCORRECT'
canvas.create_text(10, 50, anchor='nw', text=txt, font='Courier 30')
x = 10
f = 0
for i in range(a):
if i >= result * b:
color = 'yellow'
if i == result * b: # Remainder separation
x += 30
else:
if i % b == 0:
f = (f + 1) % len(colors) # Changing colors
color = colors[f]
canvas.create_oval(x, 100, x + 20, 120, width=0, fill=color)
x += 30
Questions:
1. What happens if we don't enter an answer and click the button Over? What can we do about that?
2. How do we edit the program so that it draws the remainder as a square?
3. How do we edit the program so that the individual colors are drawn below each other rather than
next to each other?
task
'' () Cnv fx()
123
62 Survey
import tkinter
def draw():
canvas.delete('all')
canvas.create_text(10, 10, anchor='nw', text=question)
mysum = 0
maximal = 0
for p in count:
mysum += p
maximal = max(maximal, p)
for i in range(3):
canvas.create_text(10, (i + 1) * 30 + 8, anchor='nw',
text=str(i + 1) + ') ' +
reply[i] + ' - ' + str(count[i]))
if count[i] == maximal:
color = 'green'
else:
color = 'red'
canvas.create_rectangle(120, (i + 1) * 30 + 5,
120 + count[i]/mysum*200, (i + 1) * 30 + 25,
width=0, fill=color)
def push(event):
if event.char == '1':
count[0] += 1
elif event.char == '2':
count[1] += 1
elif event.char == '3':
count[2] += 1
draw()
file = open('files/survey.txt', 'w')
file.write(question+'\n')
file.write(str(count[0])+' '+str(count[1])+' '+str(count[2]))
file.close()
file = open('files/survey.txt')
question = file.readline().strip()
line = file.readline()
file.close()
reply = ('Yes', 'No', "I don't know")
count = []
numbers = line.split()
for i in range(3):
count.append(int(numbers[i]))
canvas = tkinter.Canvas(width=600, height=200, background='white')
canvas.pack()
canvas.focus_set()
draw()
canvas.bind('<Key>', push)
Questions:
1. How can we avoid branching of the program (if and elif) in the function push?
2. We work with a text file in multiple places in the program. If we had to work with a different poll,
we would have to change the name of the file everywhere. How could we make it easier in this
program?
124
task
'' [] txt Cnv fx()
63 Transit Research
file = open('files/transit_research.txt')
stops = []
count = 0
maxcount = 0
for line in file:
parts = line.split(';')
geton = int(parts[0])
getoff = int(parts[1])
count += geton
count -= getoff
maxcount = max(maxcount, count)
stops.append((parts[2].strip(), count, geton >= 10,
geton < 3 and getoff < 3)) # {line A}
file.close()
Questions:
1. What is saved in the list stops and in what form?
2. What does the notation in the line {line A} mean?
task
[] () txt
125
64 Seating Chart
def msg(info):
canvas.delete('all')
canvas.create_text(250, 200, text=info, fill='red', font='Arial 20')
def process():
rows = int(entry1.get())
cols = int(entry2.get())
if count > rows * cols:
msg('Not enough desks for students')
else:
random.shuffle(students)
draw(20, 20, students[:], rows, cols) # {line B}
Questions:
1. What happens if the input text file is empty?
2. How do we ensure that the empty desks are mainly in the back?
3. Why is students[:] written in the line {line B}?
126
4. What happens if we remove if and its condition in the line {line A}?
5. What data is saved in the list students and what structure does the list have?
task
'' [] () txt Cnv fx()
127
Bibliography
[1] Kučera, P.: Programujeme v Pythone (učebnica informatiky pre stredné školy). Bratislava: Peter Kučera,
2016, ISBN 978 - 80 - 972320 - 4 - 7
[2] Kučera, P., Výbošťok, J.: Programujeme v Pythone 2 (učebnica informatiky pre stredné školy). Bratislava:
Peter Kučera, 2016, ISBN 978 - 80 - 972779 - 1 - 8
[3] Hanulová, E., Kučera, P.: Maturita z informatiky. Tvorba zadaní. Bratislava: MPC, 2007, ISBN 978 - 80 -7164 -
440 - 8
128
129