automated terminal push
All checks were successful
learn org at code.softwareshinobi.com/python.softwareshinobi.com/pipeline/head This commit was not built

This commit is contained in:
2025-06-05 20:40:34 -04:00
parent 1cb989b04d
commit 0e4be2e42c
40 changed files with 147 additions and 114 deletions

View File

@@ -0,0 +1,486 @@
# Chapter 2.2. Simple Calculations Exam Problems
In the previous chapter, we explained how to work with the system console how to **read numbers** from it and how to **print the output**. We went through the main arithmetical operations and briefly mentioned data types. Now, we are going to practice what we have learned by solving a few **more complex exam problems**.
## Reading Numbers from The Console
Before going to the tasks, we are going to revise the most important aspects of what we have studied in the previous chapter. We will start by reading numbers from the console.
### Reading an Integer
We need to create a variable to store the integer (for example, **`num`**) and use a standard command for reading input from the console (the function **`input(…)`**), combined with the function **`int(…)`** which converts a string to an integer:
```python
num = int(input())
```
### Reading a Floating-Point Number
We read a floating-point number, the same way we read an integer one, but this time we use the function **`float(…)`**:
```python
num = float(input())
```
## Printing Text Using Placeholders
A **placeholder** is an expression that is replaced with a particular value while printing an output. The function **`print(…)`** supports printing a string based on a placeholder, there are a few ways to do that, as we reviewed in the previous chapter:
- The first argument that we pass to the function is the formatted string, followed by the symbol **`%`** and the number of arguments, equal to the number of placeholders, placed in brackets:
```python
print("You are %s %s, a %d-years old person from %s." % ("Ivan", "Ivanov", "16", "Burgas"))
```
- The second way is the so-called "f-strings", where before the formatted string we put the symbol **`f`** and the arguments are in the string between curled brackets **`{}`**:
```python
first_name = "Ivan"
last_name = "Ivanov"
age = 21
town = "Burgas"
print(f"You are {first_name} {last_name}, a {age}-years old person from {town}.")
```
There are other ways to format a string and the more curious of you can check them in the following article, as well as find the difference between them:[https://cito.github.io/blog/f-strings/](https://cito.github.io/blog/f-strings/)
## Arithmetic Operators
Let's revise the main arithmetic operators for simple calculations.
### Operator +
```python
result = 3 + 5 # the result is 8
```
### Operator -
```python
result = 3 - 5 # the result is -2
```
### Operator \*
```python
result = 3 * 5 # the result is 15
```
### Operator / and //
```python
result = 5 / 2 # the result is 2.5 (fractional division)
result2 = 7 // 3 # the result is 2 (integer division)
```
## Concatenation
By using the operator **`+`** between string variables (or between a string and a number), concatenation is being performed (combining strings):
```python
firstName = "Ivan";
lastName = "Ivanov";
age = 19;
str = firstName + " " + lastName + " is " + age + " years old";
# Ivan Ivanov is 19 years old
```
## Exam Problems
Now, after having revised how to make simple calculations and how to read and print numbers from the console, let's go to the tasks. We will solve a few **problems from a SoftUni practical exam**.
## Problem: Training Lab
**A training lab** has a rectangular size **l** x **w** meters, without columns on the inside. The hall is divided into two parts- left and right, with a hallway approximately in the middle. In both parts, there are **rows with desks**. In the back of the hall, there is a big **entrance door**. In the front, there is a **podium** for the lecturer. A single **working place** takes up **70 x 120 cm** (a table with size 70 x 40 cm + space for a chair and passing through with size 70 x 80 cm). **The hallway** width is at least **100 cm**. It is calculated that due to the **entrance door** (which has 160 cm opening) **exactly one working space is lost**, and due to the **podium** (which has a size of 160 x 120 cm) exactly **two working spaces** are lost. Write a program that reads the size of the training lab as input parameters and calculates the **number of working places in it** (look at the figure).
### Input Data
**Two numbers** are read from the console, one per line: **l** (length in meters) and **w** (width in meters).
Constraints: **3 ≤ w ≤ l ≤ 100**.
### Output Data
Print an integer in the console: **the number of working places** in the training lab.
### Sample Input and Output
| Input | Output | Figure |
| ---------- | ------ | ------------------------------------------------------ |
| 15<br>8.9 | 129 | ![](/assets/chapter-2-2-images/01.Training-lab-01.png) |
| 8.4<br>5.2 | 39 | ![](/assets/chapter-2-2-images/01.Training-lab-02.png) |
#### Clarification of The Examples
In the first example, the hall length is 1500 cm. **12 rows** can be situated in it (12 _ 120 cm = 1440 + 60 cm difference). The hall width is 890 cm. 100 cm of them are for the hallway in the middle. The rest 790 cm can be situated by **11 desks per row** (11 \* 70 cm = 770 cm + 20 cm difference). \*\*Number of places = 12 _ 11 - 3** = 132 - 3 = **129\*\* (we have 12 rows with 11 working places = 132 minus 3 places for podium and entrance door).
In the second example, the hall length is 840 cm. **7 rows** can be situated in it (7 \* 120 cm = 840, no difference). The hall width is 520 cm. 100 cm from them is for the hallway in the middle. The rest 420 cm can be situated by **6 desks per row** (6 \* 70 cm = 420 cm, no difference). **Number of places = 7 \* 6 - 3** = 42 - 3 = **39** (we have 7 rows with 6 working places = 42 minus 3 places for podium and entrance door).
### Hints and Guidelines
Try to solve the problem on your own first. If you do not succeed, go through the hints.
#### Idea for Solution
As with any programming task, **it is important to build an idea for its solution**, before having started to write code. Let's carefully go through the problem requirements. We have to write a program that calculates the number of working places in a training lab, where the number depends on the hall length and height. We notice that the provided input data will be **in meters** and the information about how much space the working places and hallway take, will be **in centimeters**. To do the calculations, we will use the same measuring units, no matter whether we choose to convert length and height into centimeters or the other data in meters. The first option is used for the presented solution.
Next, we have to calculate **how many columns and how many rows** with desks will fit. We can calculate the columns by **subtracting the width by the necessary space for the hallway (100 cm)** and **dividing the difference by 70 cm** (the length of a workplace). We find the rows by dividing **the length by 120 cm**. Both operations can result in **a real number** with a whole and a fractional part, but we have to **store only the whole part in a variable**. In the end, we multiply the number of rows by the number of columns and divide it by 3 (the lost places for entrance door and podium). This is how we calculate the needed value.
#### Choosing Data Types
From the example, we see that a real number with whole and fractional parts can be given as an input, therefore, it is not appropriate to choose data type **`int`**. This is why we use **`float`**. Choosing a data type for the next variables depends on the method we choose to solve the problem. As with any programming task, this one has **more than one way to be solved**.
#### Solution
It is time to go to the solution. We can divide it into three smaller tasks:
- **Reading input from the console**.
- **Doing the calculations**.
- **Printing the output on the console**.
The first thing we have to do is read the input from the console. With **`input(…)`** we read the values from the console and with the function **`float(…)`** string is converted into **`float`**.
![](/assets/chapter-2-2-images/01.Training-lab-03.png)
Let's move to the calculations. The special part here is that after having divided the numbers, we have to store only the whole part of the result in a variable.
<table><tr><td><img src="/assets/alert-icon.png" style="max-width:50px" /></td>
<td><b>Search in Google!</b> Whenever we have an idea how to solve a particular problem, but we do not know how to write it in Python or we are dealing with one that many other people have had before us, the easiest way to solve it is by looking for information on the Internet.</td>
</tr></table>
In this case, we can try with the following search: "[**_Python gets whole number part of float_**](https://www.google.com/?q=python+get+whole+number+part+of+float)". One possible way is to use the method **`math.trunc(…)`** and don't forget to refer to the **`math`** library. The code down below is blurred on purpose and it should be completed by the reader:
![](/assets/chapter-2-2-images/01.Training-lab-04.png)
With **`print(…)`** we print the result in the console:
![](/assets/chapter-2-2-images/01.Training-lab-05.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1048#0](https://judge.softuni.org/Contests/Practice/Index/1048#0).
## Problem: Vegetable Market
A gardener is selling his harvest on the vegetable market. He is selling **vegetables for N BGN per kilogram** and **fruits for M BGN per kilogram**. Write a program that **calculates the earnings of the harvest in Euro**. (Assume that **1 EUR** is equal to **1.94 BGN**).
### Input Data
**Four numbers** are read from the console, one per line:
- First line: Vegetable price per kilogram a floating-point number.
- Second line: Fruit price per kilogram a floating-point number.
- Third line: Total kilograms of vegetables an integer.
- Fourth line: Total kilograms of fruits an integer.
**Constraints: all numbers will be within the range from 0.00 to 1000.00.**
### Output Data
Print on the console **one floating-point number: the earnings of all fruits and vegetables in EUR**.
### Sample Input and Output
| Input | Output |
| ------------------------- | ------ |
| 0.194<br>19.4<br>10<br>10 | 101 |
**Clarification for the first example:**
- Vegetables cost: 0.194 BGN. \* 10 kg. = **1.94 BGN.**
- Fruits cost: 19.4 BGN. \* 10 kg. = **194 BGN.**
- Total: **195.94 BGN. = 101 EUR**.
| Input | Output |
| ---------------------- | ---------------- |
| 1.5<br>2.5<br>10<br>10 | 20.6185567010309 |
### Hints and Guidelines
First, we will give a few ideas, followed by particular hints for solving the problem and the essential part of the code.
#### Idea for Solution
Let's first go through the problem requirements. In this case, we have to calculate **the total income** from the harvest. It equals **the sum of the earnings from the fruits and vegetables** which we can calculate by multiplying **the price per kilogram by the quantity**. The input is given in BGN and the output should be in euros. It is assumed that 1 EUR equals 1.94 BGN, therefore, to get the wanted **output value, we have to divide the sum by 1.94**.
#### Choosing Data Types
After we have a clear idea of how to solve the task, we can continue with choosing appropriate data types. Let's go through the **input**: we have **two integers** for total kilograms of vegetables and fruits, therefore, the variables we declare to store their values will be of **`int`** type. The prices of the fruits and vegetables are said to be **two floating-point numbers** and therefore, the variables will be of **`float`** type.
We can also declare two variables to store the income from the fruits and vegetables separately. The **output** should be a **floating-point number**, so the result should be **`float`** type.
#### Solution
It is time to get to the solution. We can divide it into three smaller tasks:
- **Reading input from the console**.
- **Doing the calculations**.
- **Printing the output** on the console.
To read the input, we declare variables, which we have to name carefully so that they can give us a hint about the values they store. With **`input(…)`**, we read values from the console and with the functions **`int(…)`** and **`float(…)`**, we convert the particular string value into int and double:
![](/assets/chapter-2-2-images/02.Vegetable-market-01.png)
We do the necessary calculations:
![](/assets/chapter-2-2-images/02.Vegetable-market-02.png)
The task does not specify a special output format, therefore, we just have to calculate the requested value and print it on the console. As in mathematics and so in programming, the division has a priority over addition. However, in this task, first, we have to **calculate the sum** of the two input values and then **divide by 1.94**. To give priority to addition, we can use brackets. With **`print(…)`** we print the output on the console:
![](/assets/chapter-2-2-images/02.Vegetable-market-03.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1048#1](https://judge.softuni.org/Contests/Practice/Index/1048#1).
## Problem: Change Tiles
On the ground in front of an apartment building **tiles need to be placed**. The ground has a **square shape with a side of N meters**. The tiles are **"W" meters wide** and **"L" meters long**. There is one bench on the ground with a **width of "M" meters and a length of "O" meters**. There is no need to place tiles under it. Each tile is replaced for **0.2 minutes**.
Write a program that **reads from the console the size** of **the ground, the tiles and the bench**, and calculates **how many tiles are needed** to cover the ground and what is the total **time for placing all of the tiles**.
**Example: ground with size 20 m** has an **area of 400 $$m^2$$**. **A bench** that is **1 m** wide and **2 m** long, has an area of **2 $$m^2$$**. One **tile** is **5 m wide** and **4 m long** and has an **area of 20 $$m^2$$**. **The space** that needs to be covered is **400 - 2 = 398 $$m^2$$**. **398 / 20 = 19.90 tiles** are necessary. The **time** needed is **19.90 \* 0.2 = 3.98 minutes.**
### Input Data
The input data comes as **5 numbers**, which are read from the console:
- **N length** of **a side** of **the ground** within the range of [**1 … 100**].
- **W width** per **tile** within the range of [**0.1 … 10.00**].
- **L length** per **tile** within the range of [**0.1 … 10.00**].
- **M width** of **the bench** within the range of [**0 … 10**].
- **O length** of **the bench** within the range of [**0 … 10**].
### Output Data
Print on the console **two numbers**:
- **number of tiles** needed for the repair
- **total time for placing them**
Each number should be on a new line and rounded to the second decimal place.
### Sample Input and Output
| Input | Output |
| ---------------------- | ------------ |
| 20<br>5<br>4<br>1<br>2 | 19.9<br>3.98 |
**Explanation of the example:**
- **Total area** = 20 \* 20 = 400.
- **Area of the bench** = 1 \* 2 = 2.
- **Area for covering** = 400 2 = 398.
- **Area of tiles** = 5 \* 4 = 20.
- **Needed tiles** = 398 \/ 20 = 19.9.
- **Needed time** = 19.9 \* 0.2 = 3.98.
| Input | Output |
| -------------------------- | ------------------------------------ |
| 40<br>0.8<br>0.6<br>3<br>5 | 3302.08333333333<br>660.416666666667 |
### Hints and Guidelines
Let's make a draft to clarify the task requirements. It can look the following way:
![](/assets/chapter-2-2-images/03.Change-tiles-01.png)
#### Idea for Solution
It is required to calculate the **number of tiles** that have to be placed, as well as the **time for placing them**. To **find that number**, we have to calculate **the area that needs to be covered** and **divide it by the area per tile**. By the requirements of the problem, the ground is square, therefore, we find the total area by multiplying its side by its value **`N * N`**. After that, we calculate **the area that the bench takes up** by multiplying its two sides as well **`M * O`**. After subtracting the area of the bench from the area of the whole ground, we obtain the area that needs to be repaired.
We calculate the area of a single tile by **multiplying its two sides with one another** **`W * L`**. As we already stated, now we have to **divide the area for covering by the area of a single tile**. This way, we find the number of necessary tiles. We multiply it by **0.2** (the time needed for changing a tile). Now, we have the wanted output.
#### Choosing Data Types
The length of the side of the ground, the width and the length of the bench will be given as **integers**, therefore, to store their values, we can use the system function **`int(…)`**. We will be given floating-point numbers for the width and the length of the tiles and this is why we will use **`float(…)`**.
#### Solution
As in the previous tasks, we can divide the solution into three smaller tasks:
- **Reading the input**.
- **Doing the calculations**.
- **Printing the output** on the console.
The first thing we have to do is go through **the input** of the task. It is important to pay attention to the sequence they are given in. With **`input(…)`** we read values from the console and with **`int(…)`** and **`float(…)`**, we convert the particular string value into **`int`** or **`float`**:
![](/assets/chapter-2-2-images/03.Change-tiles-02.png)
After we have initialized the variables and have stored the corresponding values in them, we move to the **calculations**. The code below is blurred on purpose, so the reader can think by himself over it:
![](/assets/chapter-2-2-images/03.Change-tiles-03.png)
**We calculate the values** that we have to print on the console. **The number** of necessary **tiles** is obtained by **dividing the area** that needs to be covered **by the area of a tile**:
![](/assets/chapter-2-2-images/03.Change-tiles-04.png)
In the task is specified that the number of the output should be rounded **to the second decimal place**. That is why we cannot just print the value with **`print(…)`**. We will use the method **`round(…)`**, which is rounding to the closest integer number with exactly n-numbers after the decimal place. For example, the number 1.35 will be rounded to 1, and 1.65 - to 2:
![](/assets/chapter-2-2-images/03.Change-tiles-05.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1048#2](https://judge.softuni.org/Contests/Practice/Index/1048#2).
## Problem: Money
Some time ago, **Pesho bought Bitcoins**. Now, he is going on vacation in Europe **and he needs euros**. Apart from Bitcoins, he has **Chinese yuans** as well. Pesho wants to **exchange his money for euros** for the tour. Write a program that **calculates how much euro he can buy, depending on the following exchange rates**:
- **1 Bitcoin = 1168 BGN.**
- **1 Chinese yuan (CNY) = 0.15 USD.**
- **1 USD = 1.76 BGN.**
- **1 EUR = 1.95 BGN.**
The exchange office has a **commission fee of 0% to 5% from the final sum in euro**.
### Input Data
Three numbers are read from the console:
- On the first line **number of Bitcoins**. Integer within the range of [**0 … 20**].
- On the second line **number of Chinese yuans**. Floating point number within the range of [**0.00 … 50 000.00**].
- On the third line **commission fee**. Floating point number within the range of [**0.00 … 5.00**].
### Output Data
Print one number on the console **the result of the exchange of currencies**. The output should be rounded **to the second decimal place**.
### Sample Input and Output
| Input | Output |
| ----------- | ------ |
| 1<br>5<br>5 | 569.67 |
**Explanation**:
- 1 Bitcoin = 1168 BGN
- 5 Chinese yuan (CNY) = 0.75 USD
- 0.75 USD = 1.32 BGN
- **1168 + 1.32 = 1169.32 BGN = 599.651282051282 EUR**
- **Commission fee:** 5% of 599.651282051282 = **29.9825641025641**
- **Result**: 599.651282051282 - 29.9825641025641 = 569.668717948718 = **569.67 EUR**
| Input | Output | Input | Output |
| ----------------- | -------- | ------------------ | -------- |
| 20<br>5678<br>2.4 | 12442.24 | 7<br>50200.12<br>3 | 10659.47 |
### Hints and Guidelines
Let's first think of the way we can solve the task, before having started to write code.
#### Idea for Solution
We see that the **number of bitcoins** and **the number of Chinese yuans** will be given in the input. The **output** should be in euros. The exchange rates that we have to work with are specified in the task. We notice that we can only exchange the sum in BGN to EUR, therefore, we **first have to calculate the whole sum** that Pesho has in BGN, and then **calculate the output**.
As we have information for the exchange rate of Bitcoins to BGN, we can directly exchange them. On the other hand, to get the value of **Chinese yuans in BGN**, first, we have to **exchange them in USD**, and then the **USD to BGN**. Finally, we will **sum the two values** and calculate how much euro that is.
Only the final step is left: **calculating the commission fee** and subtracting the new sum from the total one. We will obtain a **floating-point number** for the commission fee, which will be a particular **percent of the total sum**. Let's divide it by 100, to calculate its **percentage value**. Then we will multiply it by the sum in euro and divide the result from the same sum. Print the final sum on the console.
#### Choosing Data Types
**Bitcoins** are given as **an integer**, therefore, we can declare a variable using the **`int(…)`** function. For **Chinese yuan and commission fee**, we obtain **a floating-point number**, therefore, we are going to use **`float(…)`**.
#### Solution
After we have built an idea on how to solve the task and we have chosen the data structures that we are going to use, it is time to get to **writing the code**. As in the previous tasks, we can divide the solution into three smaller tasks:
- **Reading input from the console**.
- **Doing the calculations**.
- **Printing the output** on the console.
**We declare the variables** that we are going to use and again we have to choose **meaningful names**, which are going to give us hints about the values they store. We initialize their values: we create variables, where we will store the string arguments passed to the function and convert them to int or double:
![](/assets/chapter-2-2-images/04.Money-01.png)
Then we do the necessary calculations:
![](/assets/chapter-2-2-images/04.Money-02.png)
Finally, we **calculate the commission fee** and **subtract it from the sum in euro**. Let's pay attention to the way we could write this: **`euro -= commission * euro`** is the short way to write **`euro = euro - (commission * euro)`**. In this case, we use a **combined assignment operator** (**`-=`**) that **subtracts the value of the operand to the right from the one to the left**. The operator for multiplication (**`*`**) has a **higher priority** than the combined operator, this is why the expression **`commission * euro`** is performed first and then its value is divided.
Finally, we have to print the result in the console. We should notice that we have to format the output **to the second decimal place**. The difference between this and the previous task is that here, even if the number is an integer, **we have to print it to the second decimal place** (for example **`5.00`**). One way to do so is to use the function **`print(…)`** and to format a string using a placeholder(**`%.2f`**). By using it, we can covert a number into a string, saving the specified numbers after the decimal point:
![](/assets/chapter-2-2-images/04.Money-03.png)
Let's pay attention to something that applies to all other problems of this type: written like that, the solution of the task is pretty detailed. As the task itself is not too complex, in theory, we could write one big expression, where right after having taken the input, we calculate the output. For example, such an expression would look like this:
![](assets/chapter-2-2-images/04.Money-04.png)
This code would print a correct result, **but it is hard to read**. It won't be easy to find out how it works and whether it contains any mistakes, as well as finding such and correcting them. **Instead of one complex expression**, it is **better to write a few simpler ones** and store their values in variables with appropriate names. This way, the code is cleaner and easily maintainable.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1048#3](https://judge.softuni.org/Contests/Practice/Index/1048#3).
## Problem: Daily Earnings
Ivan is a programmer in an American company, and he **works** at home **approximately N days per month** by earning **approximately M USD per day**. At the end of the year, Ivan **gets a bonus**, which **equals 2.5 of his monthly salary**. In addition, **25% of his annual salary goes for taxes**. Write a program that **calculates what is the amount of Ivan's net average earnings** in BGN per day, as he spends them in Bulgaria. It is accepted that one year has exactly 365 days. The exchange rate of US USD to BGN will **be passed to a function**.
### Input Data
**Three numbers** are read from the console.
- On the first line **workdays per month**. An integer within the range of [**5 … 30**].
- On the second line **daily earnings**. A floating-point number within the range of [**10.00 … 2000.00**].
- On the third line **exchange rate of USD to BGN** /1 dollar = X BGN/. A floating-point number within the range of [**0.99 … 1.99**].
### Output Data
Print one number on the console **the average daily earnings in BGN**. The result will be **rounded up to the second digit after the decimal point**.
### Sample Input and Output
| Input | Output |
| ------------------- | ------ |
| 21<br>75.00<br>1.59 | 74.61 |
**Explanation**:
- **One monthly salary** = 21 \* 75 = 1575 USD.
- **Annual income** = 1575 \* 12 + 1575 \* 2.5 = 22837.5 USD.
- **Taxes** = 25% of 22837.5 = 5709.375 USD.
- **Net annual income in USD** = 17128.125 USD = 27233.71875 BGN.
- **Average earnings per day** = 27233.71875 / 365 = 74.61 BGN.
| Input | Output | Input | Output |
| ----------------- | ------ | -------------------- | ------ |
| 15<br>105<br>1.71 | 80.24 | 22<br>199.99<br>1.50 | 196.63 |
### Hints and Guidelines
Firstly, we have to analyze the task and think of a way to solve it. Then, we will choose data types and, finally, we will write the code.
#### Idea for Solution
Let's first calculate **how much the monthly salary** of Ivan is. We do that by **multiplying the working days per month by his daily earnings**. We **multiply the result** by 12, to calculate his salary for 12 months, and then, we multiply it **by 2.5**, so that we can calculate the bonus. After having summed up the two values, we calculate **his annual income**. Then, we will reduce **the annual income by 25% taxes**. We can do that by multiplying the total income by **0.25** and subtracting the result out of it. Depending on the exchange rate, **we exchange the USD to BGN** and after that, we divide the result by 365.
#### Choosing Data Types
**The working days** per month are given as **an integer**, therefore, we can convert the string into an int with the function **`int(…)`**. For both **the earned money** and **the exchange rate of USD to EUR**, we will obtain **a floating-point number**, therefore, we will use the function **`float(…)`**.
#### Solution
Again: after we have an idea of how to solve the problem and we have considered the data types that we are going to use, we can start **writing the program**. As in the previous tasks, we can divide the solution into three smaller tasks:
- **Reading the input**.
- **Doing the calculations**.
- **Printing the output** on the console.
Then we **declare the variables** that we are going to use by trying to choose **meaningful names**. We create a variable to store the arguments passed to the function, by converting the string to integer or floating number by using **`int(…)/float(…)`**:
![](/assets/chapter-2-2-images/05.Daily-earnings-01.png)
After that we do the calculations:
![](/assets/chapter-2-2-images/05.Daily-earnings-02.png)
We could write an expression that calculates the annual income without brackets as well. As multiplication is an operation that has a higher priority over addition, it will be performed first. Despite that, **writing brackets is recommended when using more operators**, as this way the code is **easily readable** and chances of making a mistake are smaller.
Finally, we have to print the result on the console. We notice **that the number has to be rounded up to the second digit after the decimal point**. To do that, we can use the same placeholder, just like the previous task:
![](/assets/chapter-2-2-images/05.Daily-earnings-03.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1048#4](https://judge.softuni.org/Contests/Practice/Index/1048#4).

View File

@@ -0,0 +1,355 @@
# Chapter 3.2. Simple Conditions Exam Problems
In the previous chapter, we went through **the simple conditional statements** in Python, which we can use to execute different actions depending on a given condition. We mentioned what is the **`scope`** of a variable and how to track the execution of our program step by step (the so-called **debugging**). In this chapter, we'll be working with **simple conditions** by going through some Exam Problems. To do this, let's first revise their construction:
```python
if bool expression:
# condition body
else:
# else-construction body
```
**`if` conditions** consist of:
* **`if` clause**
* bool expression - a variable of bool type (**`bool`**) or bool logical expression (an expression that results in **`true/false`**)
* condition body - contains a random block of source code
* **`else` clause** and its block of source code (**optional**)
## Exam Problems
After having revised how to write simple conditions, let's solve a few Exam Problems to practice the **`if-else`** construction.
## Problem: Transport Price
A student has to travel **n kilometers**. He can choose between **three types of transportation**:
* **Taxi**. Starting fee: **0.70** BGN. Day rate: **0.79** BGN/km. Night rate: **0.90** BGN/km.
* **Bus**. Day / Night rate: **0.09** BGN/km. Can be used for distances of a minimum of **20** km.
* **Train**. Day / Night rate: **0.06** BGN/km. Can be used for distances of a minimum of **100** km.
Write a program that reads the number of **kilometers n** and **period of the day** (day or night) and calculates **the price for the cheapest transport**.
### Input Data
**Two lines** are read from the console:
* The first line (arguments) contains a number **n** number of kilometers an integer in the range of [**1 … 5000**].
* The second line contains the word "**day**" or "**night**" traveling during the day or the night.
### Output Data
Print to the console **the lowest price** for the given number of kilometers.
### Sample Input and Output
| Input | Output | Input | Output |
|----------|----------|----------|----------|
|5<br>day |4.65 |7<br>night|7 |
| Input | Output | Input | Output |
|----------|----------|----------|----------|
|25<br>day |2.25 |180<br>night|10.8 |
### Hints and Guidelines
We will read the input data and, depending on the distance, we will choose the cheapest transport. To do that, we will write a few conditional statements.
#### Processing The Input Data
In the task, we are given **information about the input and output data**. Therefore, in the first **two lines** of the solution, we will declare and initialize the two **variables** that are going to store **the values of the input data**. **The first line** contains **an integer** and that is why the declared variable will be converted with the function **`int(…)`**. **The second line** contains **a word**, therefore, the variable will be of **`string`** type:
![](/assets/chapter-3-2-images/01.Transport-price-01.png)
Before starting with the conditional statements, we need to **declare** one more **variable** that stores the value of **the transport price**:
![](/assets/chapter-3-2-images/01.Transport-price-02.png)
#### Checking The Conditions and Calculating
After having **declared and initialized** the input data and the variable that stores the value of the price, we have to decide which **conditions** of the task have to be **checked first**.
The task specifies that the rates of two of the vehicles **do not depend** on whether it is **day** or **night**, but the rate of one of the transports (taxi) **depends**. This is why the **first condition** will be whether it is **day or night** so that it is clear which rate the taxi will be **using**. To do that, we **declare one more variable** that stores **the value of the taxi rate**:
![](/assets/chapter-3-2-images/01.Transport-price-03.png)
To calculate **the taxi rate**, we will use a conditional statement of type **`if-else`**:
![](/assets/chapter-3-2-images/01.Transport-price-04.png)
After having done that, now we can start calculating **the transport price** itself. The constraints in the task refer to **the distance** that the student wants to travel. This is why we will use an **`if-elif-else`** statement that will help us find **the price** of the transport, depending on the given kilometers:
![](/assets/chapter-3-2-images/01.Transport-price-05.png)
First, we check whether the kilometers are **less than 20**, as the task specifies that the student can only use **a taxi** for **less than 20 kilometers**. If the condition is **true** (returns **`true`**), the variable that is created to store the value of the transport (**`price`**), will store the corresponding value. This value equals **the starting fee** that we will **sum** with its **rate**, **multiplied** by **the distance** that the student has to travel.
If the condition of the variable **is not true** (returns **`false`**), the next step of our program is to check whether the kilometers are **less than 100**. We do that because the task specifies that in this range, **a bus** can be used as well. **The price** per kilometer of a bus **is cheaper** than a taxi one. Therefore, if the result of the condition is **true**, we store **a value**, equal to the result of the **multiplication** of **the rate** of the bus by **the distance** to the variable for the transportation **`price`** in the **`elif`** statement body.
If this condition **does not return `true`** as a result, we have to store **a value**, equal to **the result** of **the multiplication** of **the distance** by the train **rate** to the price variable in the **`else`** body. This is done because the train is **the cheapest** transport for the given distance.
#### Printing The Output Data
After we have checked the distance **conditions** and we have **calculated the price of the cheapest transport**, we have to **print it**. The task **does not** specify how to format the result, therefore, we just print **the variable**:
![](/assets/chapter-3-2-images/01.Transport-price-06.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1050#0](https://judge.softuni.org/Contests/Practice/Index/1050#0).
## Problem: Pipes in Pool
A pool with **volume V** fills up via **two pipes**. **Each pipe has a certain flow rate** (the liters of water, flowing through a pipe for an hour). A worker starts the pipes simultaneously and goes out for **N hours**. Write a program that finds the state of the pool **the moment the worker comes back**.
### Input Data
**Four lines** are read from the console:
* The first line contains a number **V the volume of the pool in liters** an integer in the range of [**1 … 10000**].
* The second line contains a number **P1 the flow rate of the first pipe per hour** an integer in the range of [**1 … 5000**].
* The third line contains a number **P2 the flow rate of the second pipe per hour** an integer in the range of [**1 … 5000**].
* The fourth line contains a number **H the hours that the worker is absent** a floating-point number in the range of [**1.0 … 24.00**].
### Output Data
Print to the console **one of the two possible states**:
* To what extent the pool has filled up and how many percents each pipe has contributed with. All percent values must be formatted to an integer (without rounding).
* "The pool is **[x]**% full. Pipe 1: **[y]**%. Pipe 2: **[z]**%."
* If the pool has overflown with how many liters it has overflown for the given time a floating-point number.
* "For **[x]** hours the pool overflows with **[y]** liters."
**Have in mind** that due to **the rounding to an integer**, there is **data loss** and it is normal for **the sum of the percents to be 99%, not 100%**.
### Sample Input and Output
|Input|Output|Input|Output|
| ---- | ----- | ---- | ---- |
|1000<br>100<br>120<br>3 |The pool is 66% full. Pipe 1: 45%. Pipe 2: 54%. |100<br>100<br>100<br>2.5|For 2.5 hours the pool overflows with 400 liters.|
### Hints and Guidelines
To solve the task, we read the input data, write a few conditional statements, do some calculations and print the result.
#### Processing The Input Data
From the task requirements, we note that our program must have **four lines** from which we read **the input data**. The first **three** consist of **integers** and that is why the **variables** that will store their values will be of **`int`** type. We know that the **fourth** line will be a **floating-point number**, therefore, the variable we use will be of **`float`** type:
![](/assets/chapter-3-2-images/02.Pipes-in-pool-01.png)
Our next step is to **declare and initialize** a variable in which we are going to calculate how many **liters** the pool has **filled up** for the **time** the worker was **absent**. We do the calculations by **summing** the values of the flow rates of the **two pipes** and **multiplying** them by the **hours** that are given as input data:
![](/assets/chapter-3-2-images/02.Pipes-in-pool-02.png)
#### Checking The Conditions and Processing Output Data
After we have **the value of the quantity** of water that has flown through the **pipes**, the next step is to **compare** that quantity with the volume of the pool itself.
We do that with a simple **`if-else`** statement, where the condition will be whether **the quantity of water is less than the volume of the pool**. If the statement returns **`true`**, we have to print one **line** that contains **the ratio** between the quantity of **water that has flown through the pipes** and **the volume of the pool**, as well as the **ratio of the quantity of the water** from **each pipe** to the **volume of the pool**.
The ratio has to be in **percentage**, that is why all the calculations so far will be **multiplied by 100**. The values will be printed using **placeholders**, and as there is a condition for **the result in percentage** to be formatted to **two digits** after **the decimal** point **without rounding**, we will use the method **`math.trunc(…)`**:
![](/assets/chapter-3-2-images/02.Pipes-in-pool-03.png)
However, if **the condition** returns **`false`**, that means that **the quantity of water** is **more** than the **volume** of the pool, therefore, it has **overflown**. Again, the output data has to be on **one line**, but this time it should contain only two values one of the **hours** when the worker was absent, and the **quantity of water**, which is the difference between the incoming water and the volume of the pool.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1050#1](https://judge.softuni.org/Contests/Practice/Index/1050#1).
## Problem: Sleepy Tom Cat
**Tom Cat** likes to sleep all day but, unfortunately, his owner is always playing with him whenever he has free time. To sleep well, **the norm of games** that Tom has is **30 000 minutes per year**. The time for games he has **depends on the holidays that his owner has**:
* During **workdays**, his owner plays with him **63 minutes per day**.
* During **holidays**, his owner plays with him **127 minutes per day**.
Write a program that reads **the number of holidays** and prints whether **Tom can sleep well** and how much **the difference from the norm** for the current year is. It is assumed that **there are 365 days in one year**.
**Example**: 20 holidays -> the working days are 345 (365 - 20 = 345). The time for games is 24 275 minutes (345 \* 63 + 20 \* 127). The difference from the norm is 5 725 minutes (30 000 24 275 = 5 725) or 95 hours and 25 minutes.
### Input Data
The input is read from the console and consists of an integer **the number of holidays** in the range of [**0 … 365**].
### Output Data
**Two lines** have to be printed to the console:
* If Tom's time for games **is above the norm** for the current year:
* **On the first line** print: **"Tom will run away"**.
* **On the second line** print the difference from the norm in the format: **"{H} hours and {M} minutes more for play"**.
* If the time for games of Tom **is below the norm** for the current year:
* **On the first line** print: **"Tom sleeps well"**.
* **On the second line** print the difference from the norm in the format: **"{H} hours and {M} minutes less for play"**.
### Sample Input and Output
|Input|Output|Input|Output|
|----|-----|----|-----|
|20|Tom sleeps well<br>95 hours and 25 minutes less for play|113|Tom will run away<br>3 hours and 47 minutes more for play|
### Hints and Guidelines
To solve the problem, we will read the input data. Then, we will write a few conditional statements and do some calculations. Finally, we will print the result.
#### Processing The Input Data and calculating
From the task we see that **the input data** will be read only on **the first line** and will be **an integer** in the range of [**0 … 365**]. This is why we will use a variable of **`int`** type:
![](/assets/chapter-3-2-images/03.Sleepy-tom-cat-01.png)
To solve the problem, **first**, we have to calculate **the total minutes** the owner of Tom is playing with him. We see that not only does the sleepy cat has to play with his owner during **the holidays**, but also during **the working days**. **The number** that we read from the console refers to **the holidays**.
Out next step is to **calculate**, with the help of that number, how many **the working days** of the owner are, as without them we cannot calculate **the total minutes for play**. As the total number of days per year is ***365*** and the number of holidays is **X**, that means that the number of working days is **365 - X***. We store **the difference** in a new variable that only stores this value:
![](/assets/chapter-3-2-images/03.Sleepy-tom-cat-02.png)
Once we have **the number of days for playing**, we can calculate **the time for games** of Tom in minutes. Its **value is equal** to the **result of the multiplication of the working days by 63** minutes (the task specifies that during working days, the time for play is 63 minutes per day), **summed with the result of the multiplication of the holidays by 127** minutes (the task specifies that during holidays, the time for play is 127 minutes per day):
![](/assets/chapter-3-2-images/03.Sleepy-tom-cat-03.png)
In the task condition, we see that we have to **print the difference** between the two values in **hours** and **minutes** as output data. That is why we **subtract** the **total** time for play from the norm of **30 000** minutes and **store** the result in a **new** variable. After that, we **divide** that variable by 60 to get the **hours**, and then, to find out how many the **minutes** are, we use **modular division with the operator `%`**, as again we divide the variable of the difference by 60.
Here we have to note that if the total **time for the playing** of Tom is **less** than **30,000** when **subtracting** the norm from it, we will obtain **a negative number**. To **neutralize** the number in the division, we use **the function `math.fabs(…)`** when finding the difference:
![](/assets/chapter-3-2-images/03.Sleepy-tom-cat-04.png)
#### Checking The Conditions
The time for games is already calculated, which leads us to the **next** step **comparing** the **time for play** of Tom with the **norm** on which the good sleep of the cat depends. To do so, we will use an **`if-else`** conditional statement. In the **`if` clause** we will check whether **the time for play is more than 30 000** (the norm).
#### Processing The Output Data
Whatever the result of the conditional statement is, we have to print how much **the difference in hours and minutes** is. We will do that with a **placeholder** and the variables that store the values of the hours and the minutes, as the formatting will be according to the task requirements for output:
![](/assets/chapter-3-2-images/03.Sleepy-tom-cat-05.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1050#2](https://judge.softuni.org/Contests/Practice/Index/1050#2).
## Problem: Harvest
In a vineyard with an area of X square meters, **40% of the harvest goes for wine production**. **Y kilograms of grapes** are extracted from a **1 square meter vineyard**. **2,5 kg of grapes** is needed for **1 liter of wine**. The wanted quantity of wine for sale is **Z liters**.
Write a program that **calculates how much wine can be produced** and whether that quantity is enough. **If it is enough, the rest is divided between the vineyard workers equally**.
### Input Data
The input data is read from the console and consists of **exactly 4 lines**:
* First line: **X $$m^2$$ the vineyard size** an integer in the range of [**10 … 5000**].
* Second line: **Y grapes for one $$m^2$$** an integer in the range of [**0.00 … 10.00**].
* Third line: **Z needed liters of wine** an integer in the range of [**10 … 600**].
* Fourth line: **number of workers** an integer in the range of [**1 … 20**].
### Output Data
The following has to be printed to the console:
* If the **produced** wine is **less than the needed quantity**:
* **"It will be a tough winter! More {insufficient wine}} liters wine needed."**
</br> \* **The result** has to be **rounded down to the nearest integer**.
* If **the produced** wine is **more than the needed quantity**:
* **"Good harvest this year! Total wine: {total wine} liters."**
\* **The result** has to be **rounded down to the nearest integer**.
* **"{Wine left} liters left -> {wine for one worker} liters per person."**
\* **Both of the results** have to be **rounded up to the higher integer**.
### Sample Input and Output
|Input|Output|Input|Output|
|----|-----|----|-----|
|650<br>2<br>175<br>3|Good harvest this year! Total wine: 208 liters.<br>33 liters left -> 11 liters per person.|1020<br>1.5<br>425<br>4|It will be a tough winter! More 180 liters wine needed.|
### Hints and Guidelines
To solve the problem, we will read the input data. Then, we will write a few conditional statements and do some calculations. Finally, we will print the result.
#### Processing The Input Data and performing the calculations
First, we have to **check** what **the input data** will be so that we can choose what **variables** we will use. The code below is blurred on purpose and it should be written by the reader:
![](/assets/chapter-3-2-images/04.Harvest-01.png)
To solve the task, based on the input data, we have to **calculate** how many **liters of wine** will be produced. From the task requirements, we see that to **calculate** the quantity of **wine in liters**, we first, have to find **the number of grapes in kilograms**, which we will get from the harvest. For that, we will declare a variable that keeps a **value**, equal to **40%** of the result from the **multiplication** of the vineyard area by the number of grapes, which is extracted from 1 $$m^2$$.
After having done these calculations, we are ready to **calculate the quantity of wine in liters** that will be produced from the harvest as well. For that, we declare one more variable that stores that **quantity**. To calculate, we have to **divide the number of grapes in kg by 2.5**:
![](/assets/chapter-3-2-images/04.Harvest-02.png)
#### Checking The Conditions and Processing Output Data
After having done the necessary calculations, the next step is to **check** whether the liters of wine that have been produced **are enough**. For that, we will use **a simple conditional statement** of the **`if-else`** type and we will check whether the liters of wine from the harvest are **more than** or **equal to** the **needed liters**.
If the condition returns **`true`**, from the task requirement we see that **on the first line** we have to print **the wine that has been produced from the harvest**. That value has to be **rounded down to the nearest integer**, which we will do by using both the method **`math.floor(…)`** and a **placeholder** when printing it.
On the second line, we have to print the results by **rounding them up to the higher integer**, which we will do by using the method **`math.ceil(…)`**. The values that we have to print are **the quantity of wine left** and **the quantity that each worker gets**. The wine left is equal to **the difference** between the produced liters of wine and the needed liters of wine.
We calculate the value of that quantity in a new variable, which we declare and initialize in the **`if` condition body**, before printing the first line. We calculate the quantity of wine that **each worker gets** by dividing the wine left by the number of workers:
![](/assets/chapter-3-2-images/04.Harvest-03.png)
If the condition returns **`false`**, we have to **print the difference** between **the needed liters** and the **liters of wine produced from the harvest**. There is a specification that the result has to be **rounded down to the nearest integer**, which we will do by using the method **`math.floor(…)`**:
![](/assets/chapter-3-2-images/04.Harvest-04.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1050#3](https://judge.softuni.org/Contests/Practice/Index/1050#3).
## Problem: Firm
A firm gets a request for creating a project for which a certain number of hours are needed. The firm has **a certain number of days**. During 10% of the days, the workers are **being trained** and cannot work on the project. A normal **working day is 8 hours long**. The project is important for the firm and every worker must work on it with **overtime of 2 hours per day**.
**The hours** must be **rounded down to the nearest integer** (for example, **6.98 hours** are rounded to **6 hours**).
Write a program that calculates whether **the firm can finish the project on time** and **how many hours more are needed or left**.
### Input Data
The input data is read from **the console** and contains **exactly three lines**:
* On **the first** line are **the needed hours** **an integer in the range of** [**0 … 200 000**].
* On **the second** line are **the days that the firm has** **an integer in the range of** [**0 … 20 000**].
* On **the third** line are **the number of all workers** **an integer in the range of** [**0 … 200**].
### Output Data
**Print one line** to the console:
* If **the time is enough**:
* **"Yes!{the hours left} hours left."**
* If **the time is NOT enough**:
* **"Not enough time!{additional hours} hours needed."**
### Sample Input and Output
|Input|Output|Input|Output|
|----|-----|----|-----|
|90<br>7<br>3<br>|Yes!99 hours left.|99<br>3<br>1|Not enough time!72 hours needed.|
### Hints and Guidelines
To solve the problem, we will read the input data. Then, we will write a few conditional statements and do some calculations. Finally, we will print the result.
#### Processing The Input Data
**First**, we have to read the input data to solve the problem. The code below is blurred on purpose and it should be written by the reader:
![](/assets/chapter-3-2-images/05.Firm-01.png)
#### Auxiliary Calculations
The next step is to calculate **the number of total working hours** by multiplying the working days by 8 (every working day is 8 hours long) with the number of workers and then sum them with the overtime. **The working days** equal **90% of the days** that the firm has. **The overtime** equals the result of the multiplication of the number of workers by 2 (the possible hours of overtime) and then it is multiplied by the number of days that the firm has. From the task requirements, we see that **the hours** should be **rounded down to the nearest integer**, which we will do with the method **`math.floor(…)`**:
![](/assets/chapter-3-2-images/05.Firm-02.png)
#### Checking The Conditions
After having done the calculations that are needed to find the value of **the working hours**, now we have to check whether these hours are **enough**, **or some hours are left**.
If **the time is enough**, we print the result that is specified in the task requirements, which in this case is the difference between **the working hours and the hours needed** for finishing the project.
If **the time is not enough**, we print the additional hours that are needed for finishing the project. They equal the difference between **the hours for the project** and **the total working hours**:
![](/assets/chapter-3-2-images/05.Firm-03.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1050#4](https://judge.softuni.org/Contests/Practice/Index/1050#4).

View File

@@ -0,0 +1,512 @@
# Chapter 4.2. More Complex Conditions Exam Problems
The previous chapter introduced you to **nested conditions** in **Python**. Via nested conditions, the program logic in a particular application can be represented using **`if` conditional statements** that are nested inside each other. We also explained the more complex **`if-elif-else`** conditional statement that allows selecting from a number of options. Now we are going to solve some practical exercises and make sure we have an in-depth understanding of the material, by discussing a set of more complex problems that had been given to students on exams. Before moving to the problems, let's first recall what nested conditions are:
## Nested Conditions
```python
if condition1:
if condition2:
# body
else:
# body
```
<table><tr><td><img src="/assets/alert-icon.png" style="max-width:50px" /></td>
<td>Remember that it is not a good practice to write <strong>deeply nested conditional statements</strong> (with more than three levels of nesting). Avoid nesting of more than three conditional statements inside one another. This complicates the code and makes its reading and understanding difficult.</td>
</tr></table>
## If-Elif-Else Conditions
When the program operation depends on the value of a variable, we can do consecutive checks with multiple **`if-elif-else`** blocks:
```python
if condition1:
# body
elif condition2:
# body
elif condition3:
# body
else:
# body
```
The body can consist of any code, as long as it corresponds to the syntactic particularity of the language and is indented one tab-press in.
## Exam Problems
Now, after we refreshed our knowledge on how to use nested conditional statements to implement more complex conditions and program logic, let's solve some exam problems.
## Problem: On Time for The Exam
A student has to attend **an exam at a particular time** (for example at 9:30 am). They arrive in the exam room at a particular **time of arrival** (for example 9:40 am). It is considered that the student has arrived **on time** if they have arrived **at the time when the exam starts or up to half an hour earlier**. If the student has arrived **more than 30 minutes earlier**, the student has come **too early**. If they have arrived **after the time when the exam starts**, they are **late**.
Write a program that inputs the exam starting time and the time of student's arrival, and prints if the student has arrived **on time**, if they have arrived **early** or if they are **late**, as well as **how many hours or minutes** the student is early or late.
### Input Data
**Four integers** are read from the console (each on a new line):
- The first line contains the **exam starting time (hours)** an integer from 0 to 23
- The second line contains the **exam starting time (minutes)** an integer from 0 to 59.
- The third line contains the **hour of arrival** an integer from 0 to 23.
- The fourth line contains **minutes of arrival** an integer from 0 to 59.
### Output Data
Print the following on the first line on the console:
- "**Late**", if the student arrives **later** compared to the exam starting time.
- "**On time**", if the student arrives **exactly** at the exam starting time or up to 30 minutes earlier.
- "**Early**", if the student arrives more than 30 minutes **before** the exam starting time.
If the student arrives with more than one minute difference compared to the exam starting time, print on the next line:
- "**mm minutes before the start**" for arriving less than an hour earlier.
- "**hh:mm hours before the start**" for arriving 1 hour or earlier. Always print minutes using 2 digits, for example "1:05".
- "**mm minutes after the start**" for arriving less than an hour late.
- "**hh:mm hours after the start**" for arriving late with 1 hour or more. Always print minutes using 2 digits, for example "1:03".
### Sample Input and Output
| Input | Output | Input | Output |
|---|---|---|---|
|9<br>30<br>9<br>50|Late<br>20 minutes after the start|16<br>00<br>15<br>00|Early<br>1:00 hours before the start|
|9<br>00<br>8<br>30|On time<br>30 minutes before the start|9<br>00<br>10<br>30|Late<br>1:30 hours after the start|
|14<br>00<br>13<br>55|On time<br>5 minutes before the start|11<br>30<br>8<br>12|Early<br>3:18 hours before the start|
| Input | Output |
|---|---|
|10<br>00<br>10<br>00|On time|
|11<br>30<br>10<br>55|Early<br>35 minutes before the start|
|11<br>30<br>12<br>29|Late<br>59 minutes after the start|
### Hints and Guidelines
<table><tr><td><img src="/assets/alert-icon.png" style="max-width:50px" /></td>
<td>It is recommended <strong>to read the assignment a few times,</strong> take notes and sketch the examples while thinking before you start writing code.</td></tr></table>
#### Processing The Input Data
According to the assignment, we expect **four** lines containing different **integers** to be passed. Examining the provided parameters, we can use the **`int`** type, as it is suitable for the expected values. We simultaneously **read** the input data and **parse** the string value to the selected data type for the **intege**r.
![](/assets/chapter-4-2-images/01.On-time-for-the-exam-01.png)
Examining the expected output, we can create variables that contain the different output data types, to avoid using the so-called **"magic strings"** in the code.
![](/assets/chapter-4-2-images/01.On-time-for-the-exam-02.png)
#### Calculations
After reading the input data, we can now start writing the logic for calculating the result. Let's first calculate the **start time** of the exam **in minutes** for easier and more accurate comparison:
![](/assets/chapter-4-2-images/01.On-time-for-the-exam-03.png)
Let's also calculate the **student arrival time** using the same logic:
![](/assets/chapter-4-2-images/01.On-time-for-the-exam-04.png)
What remains is to calculate the difference between the two times, to determine **when** and **what time compared to the exam time** the student arrived at:
![](/assets/chapter-4-2-images/01.On-time-for-the-exam-05.png)
Our next step is to do the required **checks and calculations**, and finally, we are going to print the output. Let's separate the code into **two** parts.
- First, let's show when the student arrived were they early, late or on time. To do that, we will use an **`if-else`** statement.
- After that, we're going to show the **time difference**, if the student arrives at a **different time** compared to the **exam starting time**.
To spare one additional check (**`else`**), we can, by default, assume that the student was late.
After that, according to the condition, we will check whether the difference in times is **more than 30 minutes**. If this is true, we assume that the student is **early**. If we do not match the first condition, we need to check if **the difference is less than or equal to zero (**`<= 0`**)**, by which we are checking the condition whether the student arrived within the range of **0 to 30 minutes** before the exam.
In all other cases, we assume that the student **was late**, which we set as **default**, and no additional check is needed:
![](/assets/chapter-4-2-images/01.On-time-for-the-exam-06.png)
Finally, we need to print **what is the time difference between exam start time and student arrival time**, as well as whether this time difference indicates the time of arrival **before or after the exam start**.
We check whether the time difference is **more than** one hour, to print hours and minutes in the required **format**, or **less than** one hour, to print **only minutes** as a format and description. We also need to do one more check whether the time of student's arrival is **before** or **after** the exam start time.
![](/assets/chapter-4-2-images/01.On-time-for-the-exam-07.png)
#### Printing The Result
Finally, what remains is to print the result on the console. According to the requirements, if the student arrived right on time **(not even a minute difference)**, we do not need to print a second result. This is why we apply the following **condition**:
![](/assets/chapter-4-2-images/01.On-time-for-the-exam-08.png)
Actually, for the task, printing the result **on the console** can be done at a much earlier stage during the calculations. This, however, is not a very good practice. **Why?**
Let's examine the idea that our code is not 10 lines, but 100 or 1000! One day, printing the result will not be done on the console, but will be written in a **file** or displayed as a **web application**. Then, how many places in the code you will make changes at, due to such a correction? Are you sure you won't miss some places?
<table><tr><td><img src="/assets/alert-icon.png" style="max-width:50px" /></td>
<td>Always consider the code that contains logical calculations as a separate piece, different from the part that processes the input and output data. It has to be able to work regardless of how the data is passed to it and where the result will be displayed.</td></tr></table>
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1052#0](https://judge.softuni.org/Contests/Practice/Index/1052#0).
## Problem: Trip
It is strange, but most people start planning their vacations well in advance. A young programmer from Bulgaria has a **certain budget** and spare time in a particular **season**.
Write a program that accepts **as input the budget and season** and **as output** displays programmer's **vacation place** and **the amount of money they will spend**.
**The budget determines the destination, and the season determines what amount of the budget will be spent**. If the season is summer, the programmer will go camping, if it is winter he will stay in a hotel. If it is in Europe, regardless of the season, the programmer will stay in a hotel. Each camp or hotel, according to the destination, has its price, which corresponds to a particular **percentage of the budget**:
- If **100 BGN or less** somewhere in **Bulgaria**.
- **Summer** **30%** of the budget
- **Winter** **70%** of the budget.
- If **1000 BGN or less** somewhere in the **Balkans**.
- **Summer** **40%** of the budget.
- **Winter** **80%** of the budget.
- If **more than 1000 BGN** somewhere in **Europe**.
- Upon traveling in Europe, regardless of the season, the programmer will spend **90% of the budget**.
### Input Data
The input data will be read from the console and will consist of **two lines**:
- The **first** line holds **the budget** a **floating-point(double) number** in the range [**10.00 … 5000.00**].
- The **second** line holds one of two possible seasons that are "**summer**" or "**winter**".
### Output Data
**Two lines** must be printed on the console.
- On the **first** line "**Somewhere in {destination}**" among "**Bulgaria**", "**Balkans**" and "**Europe**".
- On the **second** line "{**Vacation type**} {**Amount spent**}".
- The **Vacation** can be in a "**Camp**" or "**Hotel**".
- The **Amount** must be **rounded up to the second digit after the decimal point**.
### Sample Input and Output
| Input | Output |
|---|---|
|50<br>summer|Somewhere in Bulgaria<br>Camp - 15.00|
|75<br>winter|Somewhere in Bulgaria<br>Hotel - 52.50|
|312<br>summer|Somewhere in Balkans<br>Camp - 124.80|
|678.53<br>winter|Somewhere in Balkans<br>Hotel - 542.82|
|1500<br>summer|Somewhere in Europe<br>Hotel - 1350.00|
### Hints and Guidelines
Typically, as for the other tasks, we can separate the solution into the following parts:
* Reading the input data
* Doing calculations
* Printing the result
#### Processing The Input Data
While reading the requirements carefully, we understand that we expect **two** lines of input data. Our first parameter is a **real number**, for which we need to pick an appropriate variable type. We can pick **`float`** as a variable for the budget and **`string`** for the season:
![](/assets/chapter-4-2-images/02.Trip-01.png)
<table><tr><td><img src="/assets/alert-icon.png" style="max-width:50px" /></td>
<td>Always take into consideration what <strong>value type</strong> is passed in the input data, as well as what type these need to be converted to, for the program conditions to work properly!</td>
</tr></table>
#### Calculations
Let's create and initialize the variables needed for applying the logic and calculations:
![](/assets/chapter-4-2-images/02.Trip-02.png)
Similar to the example in the previous task, we can initialize variables with some of the output results, to spare additional initialization.
When examining the problem requirements once again, we notice that the main distribution of where the vacation will take place is determined by the **value of the budget**, i.e. our main logic is divided into two cases:
* If the budget is **less than** a particular value.
* If it is **less than** another value or is **more than** the specified border value.
Based on the way we arrange the logical scheme (the order in which we will check the border values), we will have more or fewer conditions in the solution. **Think why!**
After that, we need to apply a condition to check the value of the **season**. Based on it, we will determine what percentage of the budget will be spent, as well as where the programmer will stay in a **hotel** or a **camp**. This is a sample code that may be used to implement the above idea:
![](/assets/chapter-4-2-images/02.Trip-03.png)
We can optimize the conditional check by assigning a **default value** and then checking one variant less. **This saves one logical step**. For example, this block:
![](/assets/chapter-4-2-images/02.Trip-04.png)
can be shortened like so:
![](/assets/chapter-4-2-images/02.Trip-05.png)
#### Printing The Result
What remains is to display the calculated result on the console:
![](/assets/chapter-4-2-images/02.Trip-06.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1052#1](https://judge.softuni.org/Contests/Practice/Index/1052#1).
## Problem: Operations
Write a program that reads **two integers (n1 and n2)** and an **operator** that performs a particular mathematical operation with them. Possible operations are: **summing up** (**`+`**), **subtraction** (**`-`**), **multiplying** (**`*`**), **division** (**`/`**) and **modular division** (**`%`**). Upon summing up, subtracting and multiplying, the console must print the result and display whether it is an **even** or an **odd** number. Upon regular division **just the result**, and upon modular division **the remainder**. You need to take into consideration the fact that **the divisor can be equal to zero** (**`= 0`**), and dividing by zero is not possible. In this case, a **special notification** must be printed.
### Input Data
**3 lines** are read from the console:
- **N1** **integer** within the range [**0 … 40 000**].
- **N2** **integer** within the range [**0 … 40 000**].
- **Operator** **one character** among: "+", "-", "*", "/", "%"."**+**", "**-**", "**\***", "**/**", "**%**".
### Output Data
Print the output as a **single line** on the console:
- If the operation is **summing up**, **subtraction** or **multiplying**:
- **"{N1} {operator} {N2} = {output} {even/odd}"**.
- If the operation is **division**:
- **"{N1} / {N2} = {output}"** the result is **formatted** up **to the second digit after the decimal point**.
- If the operation is **modular division**:
- **"{N1} % {N2} = {remainder}"**.
- In case of **dividing by 0** (zero):
- **"Cannot divide {N1} by zero"**.
### Sample Input and Output
| Input | Output | Input | Output |
|---|---|---|---|
|123<br>12<br>/|123 / 12 = 10.25|112<br>0<br>/|Cannot divide 112 by zero|
|10<br>3<br>%|10 % 3 = 1|10<br>0<br>%|Cannot divide 10 by zero|
| Input | Output |
|---|---|
|10<br>12<br>+|10 + 12 = 22 - even|
|10<br>1<br>-|10 - 1 = 9 - odd|
|7<br>3<br>\*|7 * 3 = 21 - odd|
### Hints and Guidelines
The problem is not complex, but there are a lot of lines of code to write.
#### Processing The Input Data
Upon reading the requirements, we understand that we expect **three** lines of input data. The first two lines are **integers** (within the specified range), and the third one **an arithmetical symbol**.
![](/assets/chapter-4-2-images/03.Operations-01.png)
#### Calculations
Let's create and initialize the variables needed for the logic and calculations. In one variable we will store **the calculations output**, and in the other one, we will use it for the **final output** of the program.
![](/assets/chapter-4-2-images/03.Operations-02.png)
When carefully reading the requirements, we understand that there are cases where we don't need to do **any** calculations, and simply display a result. Therefore, we can first check if the second number is **`0`** (zero), as well as whether the operation is a **division** or a **modular division**, and then initialize the output.
![](/assets/chapter-4-2-images/03.Operations-03.png)
Let's place the output as a value upon initializing the **`output`** parameter. This way we can apply only **one condition** whether it is needed to **recalculate** or **replace** this output.
Based on the approach that we choose, our next condition will be either a simple **`elif`** or a single **`if`**. In the body of this condition, using additional conditions regarding the manner of calculating the output based on the passed operator, we can separate the logic based on the **structure** of the expected **output**.
From the requirements we can see that for **summing up** (**`+`**), **subtraction** (**`-`**) or **multiplying** (**`*`**) the expected output has the same structure: **"{n1} {operator} {n2} = {output} {even/odd}"**, whereas for **division** (**`/`**) and **modular division** (**`%`**) the output has a different structure:
![](/assets/chapter-4-2-images/03.Operations-04.png)
We finish the solution by applying conditions for summing up, subtraction and multiplying:
![](/assets/chapter-4-2-images/03.Operations-05.png)
For short and clear conditions, such as the above example for even and odd numbers, you can use a **ternary operator**. Let's examine the possibility to apply a condition **with** or **without** a ternary operator.
**Without using a ternary operator** the code is longer but easier to read:
![](/assets/chapter-4-2-images/03.Operations-06.png)
**Upon using a ternary operator** the code is much shorter, but may require additional efforts to read and understand the logic:
![](/assets/chapter-4-2-images/03.Operations-07.png)
#### Printing The Output
Finally, what remains is to print the calculated result on the console:
![](/assets/chapter-4-2-images/03.Operations-08.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1052#2](https://judge.softuni.org/Contests/Practice/Index/1052#2).
## Problem: Match Tickets
**A group of football** fans decided to buy **tickets for Euro Cup 2016**. The tickets are sold in **two** price categories:
- **VIP** **499.99** BGN (Bulgarian leva).
- **Normal** **249.99** BGN (Bulgarian leva).
The football fans **have a shared budget**, and the **number of people** in the group determines what percentage of the budget will be **spent on transportation**:
- **1 to 4** 75% of the budget.
- **5 to 9** 60% of the budget.
- **10 to 24** 50% of the budget.
- **25 to 49** 40% of the budget.
- **50 or more** 25% of the budget.
**Write a program** that **calculates whether the money left in the budget** will be enough for the football fans to **buy tickets in the selected category**, as well as **how much money** they will **have left or be insufficient**.
### Input Data
The input data will be read from the **console** and contains **exactly 3 lines**:
- The **first** line contains the budget a real number within the range [**1 000.00 … 1 000 000.00**].
- The **second** line contains the **category** "**VIP**" or "**Normal**".
- The **third** line contains the **number of people in the group** an integer within the range [**1 … 200**].
### Output Data
**Print the following** on the console as **one line**:
- If the **budget is sufficient**:
- "**Yes! You have {N} leva left.**" where **N is the amount of remaining money** for the group.
- If the **budget is NOT sufficient**:
- "**Not enough money! You need {M} leva.**" where **M is the insufficient amount**.
**The amounts** must be **formatted up to the second digit after the decimal point**.
### Sample Input and Output
| Input | Output | Explanations |
|---|---|---|
|1000<br>Normal<br>1|Yes! You have 0.01 leva left.|**1 person : 75%** of the budget is spent on **transportation**.<br>**Remaining amount:** 1000 750 = **250**.<br>Category **Normal**: the ticket **price is 249.99 * 1 = 249.99**<br>249.99 < 250: **the person will have** 250 249.99 = **0.01** money left|
| Input | Output | Explanations |
|---|---|---|
|30000<br>VIP<br>49|Not enough money! You need 6499.51 leva.|**49 people: 40%** of the budget are spent on **transportation**.<br>Remaining amount: 30000 12000 = 18000.<br>Category **VIP**: the ticket **costs** 499.99 * 49.<br>**24499.510000000002** < 18000.<br>**The amount is not enough** 24499.51 - 18000 = **6499.51**|
### Hints and Guidelines
We will read the input data and perform the calculations described in the task requirements, to check if the money will be sufficient.
#### Processing The Input Data
Let's read the requirements carefully and examine what we expect to take as **input data**, what is expected to **return as a result**, as well as what the **main steps** for solving the problem are. For a start, let's process and save the input data in **appropriate variables**:
![](/assets/chapter-4-2-images/04.Match-tickets-01.png)
#### Calculations
Let's create and initialize the variables needed for doing the calculations:
![](/assets/chapter-4-2-images/04.Match-tickets-02.png)
Let's review the requirements once again. We need to perform **two** different block calculations. By the first set of calculations, we must understand what part of the budget has to be spent on **transportation**. You will notice that the logic for doing these calculations only depends on the **number of people in the group**. Therefore, we will do a logical breakdown according to the number of football fans. We will use a conditional statement a sequence of **`if-elif`** blocks:
![](/assets/chapter-4-2-images/04.Match-tickets-03.png)
By the second set of calculations, we need to find out what amount will be needed to **purchase tickets** for the group. According to the requirements, this only depends on the type of tickets that we need to buy. Let's use **`if-elif`** conditional statement:
![](/assets/chapter-4-2-images/04.Match-tickets-04.png)
Once we have calculated the **transportation costs** and **ticket costs**, what remains is to calculate the final result and understand if the group of football fans will **attend** Euro Cup 2016 or **not**, by the provided available parameters.
For the output, to spare one **condition** in the construction, we will assume that the group can, by default, attend Euro Cup 2016:
![](/assets/chapter-4-2-images/04.Match-tickets-05.png)
#### Printing The Result
Finally, we need to display the calculated result on the console.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1052#3](https://judge.softuni.org/Contests/Practice/Index/1052#3).
## Problem: Hotel Room
A hotel offers **two types of rooms: studio and apartment**.
Write a program that calculates **the price of the whole stay for a studio and apartment**. **Prices** depend on the **month** of the stay:
| **May and October** | **June and September** | **July and August** |
|---|---|---|
|Studio **50** BGN/night|Studio **75.20** BGN/night|Studio **76** BGN/night|
|Apartment **65** BGN/night|Apartment **68.70** BGN/night|Apartment **77** BGN/night|
The following **discounts** are also offered:
- For a **studio**, in the case of **more than 7** nights stayed in **May and October: 5% discount**.
- For a **studio**, in the case of **more than 14** nights stayed in **May and October: 30% discount**.
- For a **studio**, in the case of **more than 14** nights stayed in **June and September: 20% discount**.
- For an **apartment**, in the case of **more than 14 nights stayed**, **no limitation regarding the month: 10% discount**.
### Input Data
The input data will be read from the console and contains **exactly two lines**:
- The **first** line contains the **month** **May**, **June**, **July**, **August**, **September** or **October**.
- The **second** line is the **amount of nights stayed** integer within the range [**0 … 200**].
### Output Data
**Print** the following **two lines** on the console:
- On the **first line**: "**Apartment: { price for the whole stay } lv.**"
- On the **second line**: "**Studio: { price for the whole stay } lv.**"
**The price for the whole duration of the stay must be formatted up to two symbols after the decimal point**.
### Sample Input and Output
| Input | Output | Comments |
|---|---|---|
|May<br>15|Apartment: 877.50 lv.<br>Studio: 525.00 lv.| In **May**, in case of more than **14 stays**, the discount for a **studio is 30%** (50 - 15 = 35), and for the **apartment is 10%** (65 - 6.5 = 58.5)..<br>The whole stay in the **apartment: 877.50** lv.<br>The whole stay **in the studio: 525.00** lv.|
| Input | Output |
|---|---|
|June<br>14|Apartment: 961.80 lv.<br>Studio: 1052.80 lv|
|August<br>20|Apartment: 1386.00 lv.<br>Studio: 1520.00 lv.|
### Hints and Guidelines
We will read the input data and do the calculations according to the provided price list and the discount rules, and finally, print the result.
#### Processing The Input Data
According to the task requirements, we expect two lines of input data - the first line is the **month in which the stay is planned**, and the second - the **number of stays**. Let's process and store the input data in the appropriate parameters:
![](/assets/chapter-4-2-images/05.Hotel-room-01.png)
#### Calculations
Now let's create and initialize the variables needed for the calculations:
![](/assets/chapter-4-2-images/05.Hotel-room-02.png)
When doing an additional analysis of the requirements, we understand that our main logic depends on what month is passed and what is the number of **stays**.
In general, there are different approaches and ways to apply the above conditions, but let's examine a basic **`if-elif`** conditional statement, as in each different **case** we will use **`if`** and **`if-elif`** conditional statements.
Let's start with the first group of months: **May** and **October**. For these two months, **the price for a stay is the same** for both types of accommodation a **studio** or an **apartment**. Therefore, the only thing that remains is to apply an internal condition regarding the **number of stays** and recalculate the **relevant price** (if needed):
![](/assets/chapter-4-2-images/05.Hotel-room-03.png)
To some extent, the **logic** and **calculations** will be **identical** for the following months:
![](/assets/chapter-4-2-images/05.Hotel-room-04.png)
![](/assets/chapter-4-2-images/05.Hotel-room-05.png)
After calculating the relevant prices and the total amount for the stay, now let's prepare the formatted result. Before that, we should store it in our output **variables** - **`studio_info`** and **`apartment_info`**:
![](/assets/chapter-4-2-images/05.Hotel-room-06.png)
To calculate the output parameters, we will use the **formatting** **`.2f`**. This formatting **rounds the decimal** number up to a specified number of characters after the decimal point. In our case, we will round the decimal number up to **2 digits** after the decimal point.
#### Printing The Result
Finally, what remains is to print the calculated results on the console.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1052#4](https://judge.softuni.org/Contests/Practice/Index/1052#4).

View File

@@ -0,0 +1,587 @@
# Chapter 5.2 Loops - Exam Problems
In the previous chapter, we learned how to run a command block **more than once**. That's why we implemented **`for` loop** and covered some of its main applications. Our task in the current chapter is to hone our knowledge by solving a couple of more complex problems with loops, which appear in exams. For some of them, well show detailed solved examples, while for others therell be tips only. Before we begin, well recall the **`for` loop** construction:
![](/assets/chapter-5-2-images/00.For-construction-01.png)
**`for` loops** consist of:
* **Initialization block**, where the variable-counter (**`i`**) is declared, and with the help of the **`range(…)`** function built into Python, we define what its starting and ending value will be.
* **Updating the counter** we implement it as a third parameter in the **`range(…)`** function, and it shows with how many steps the variable-counter should be updated.
* **Loop body** - it has a random block full of source code.
## Exam Problems
Lets solve a couple of problems with loops in SoftUnis exams.
## Problem: Histogram
Were given **n-count integers** in the range [**1 … 1000**]. A percent of them, **p1**, is under 200, __p2__ percent are between 200 and 399, **p3** percent are between 400 and 599, **p4** percent are between 600 and 799, and the remaining **p5** percent begin at 800. Write a program that calculates and prints the percentages **p1**, **p2**, **p3**, **p4**, and **p5**.
**Example**: we have n = **20** integers: 53, 7, 56, 180, 450, 920, 12, 7, 150, 250, 680, 2, 600, 200, 800, 799, 199, 46, 128, 65. We get the following distribution and visualization:
| **Group** | **Numbers** |**Number count**| **Percentage** |
|-------------|-------------------------------------------------|:---------------|---------------------------------|
| < 200 | 53, 7, 56, 180, 12, 7, 150, 2, 199, 46, 128, 65 | 12 | p1 = 12 / 20 * 100 = 60.00% |
| 200 … 399 | 250, 200 | 2 | p2 = 2 / 20 * 100 = 10.00% |
| 400 … 599 | 450 | 1 | p3 = 1 / 20 * 100 = 5.00% |
| 600 … 799 | 680, 600, 799 | 3 | p4 = 3 / 20 * 100 = 15.00% |
| ≥ 800 | 920, 800 | 2 | p5 = 2 / 20 * 100 = 10.00% |
### Input Data
On the first line of the input is an integer **n** ( 1 <= **n** <= 1000 ), which stands for the number of lines with numbers, which will be given to us. On the next **n lines**, there is **one integer** in the range [**1 … 1000**] the numbers that the histogram will be based on.
### Output Data
In the console, print a histogram of **5 lines**, each of them containing a number between 0% and 100%, formatted with two-digit precision after the decimal point (for example, 25.00%, 66.67%, 57.14%).
### Sample Input and Output
<table>
<thead>
<tr>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top"><strong>3</strong><br>1<br>2<br>999</td>
<td valign="top">66.67%<br>0.00%<br>0.00%<br>0.00%<br>33.33%</td>
<td valign="top"><strong>4</strong><br>53<br>7<br>56<br>999</td>
<td valign="top">75.00%<br>0.00%<br>0.00%<br>0.00%<br>25.00%</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top"><strong>7</strong><br>800<br>801<br>250<br>199<br>399<br>599<br>799</td>
<td valign="top">14.29%<br>28.57%<br>14.29%<br>14.29%<br>28.57%</td>
<td valign="top"><strong>9</strong><br>367<br>99<br>200<br>799<br>999<br>333<br>555<br>111<br>9</td>
<td valign="top">33.33%<br>33.33%<br>11.11%<br>11.11%<br>11.11%</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top"><strong>14</strong><br>53<br>7<br>56<br>180<br>450<br>920<br>12<br>7<br>150<br>250<br>680<br>2<br>600<br>200</td>
<td valign="top">57.14%<br>14.29%<br>7.14%<br>14.29%<br>7.14%</td>
</tr>
</tbody>
</table>
### Hints and Guidelines
The program that solves this problem can be divided theoretically into three parts:
* **Reading the input data** in the current problem, this means reading the integer **n**, followed by a **count of n integers**, each on a new line.
* **Processing The Input Data** in this case, this means dividing the numbers into groups and calculating the division percentage by those groups.
* **Outputting the final result** printing the histogram in the console, in the given format.
#### Processing The Input Data
Before we transition to the real reading of the input, we have to **declare our variables**, in which the data will be stored:
![](/assets/chapter-5-2-images/01.Histogram-01.png)
We declare variables **`p1_percentage`**, **`p2_percentage`**, etc., in which well store the percentages, as well as **`cnt_p1`**, **`cnt_p2`**, etc., in which well keep the count of numbers for the respective group.
After weve declared the needed variables, we can move on to reading the number **`n`** from the console:
![](/assets/chapter-5-2-images/01.Histogram-02.png)
#### Processing The Output Data
To read and assign each number to its respective group, well use a **`for`-loop** from **0** to **`n`** (the count of the numbers). Each iteration of the cycle will read and assign **only one number** (**`current_number`**) to its respective group. So that we can decide if a selected number belongs to a group, **we check its range**. If it passes, we increase the count of this groups numbers (**`cnt_p1`**, **`cnt_p2`**, etc.) by 1:
![](/assets/chapter-5-2-images/01.Histogram-03.png)
After weve found out how many numbers there are in each group, we can move on to calculating the percentages, which is also the main part of the problem. Well use the following formula:
<p align="center"><strong>(Group percentage) = (Group number count) * 100 / (Count of all numbers)</strong></p>
It doesnt matter whether well divide by **100** (an **`integer`** type), or **100.0**(a **`float`** type) since the **division** will take place and the result will be saved to the variable. Example: **5 / 2 = 2.5**, and **5 / 2.0 = 2.5**. In **`Python 3`**, theres no difference whether well be dividing by an integer or a real number - if the result is a real number itself, then it will be saved in the variable as a floating-point number. But in **`Python 2.7`** we have to convert the numbers to a **`float`** type, to get the correct result a real number. Having that in mind, the first variables formula will look like this:
![](/assets/chapter-5-2-images/01.Histogram-04.png)
To better understand whats happening, lets look at the following example:
|Input|Output|
|--------|---------|
|**3**<br>1<br>2<br>999|66.67%<br>0.00%<br>0.00%<br>0.00%<br>33.33%|
In this case, **`n = 3`**.
The cycle consists of:
- **`i = 0`** - we read the number 1, which is lower than 200 and belongs to the first group, thus increasing the counter of the number (**`cnt_p1`**) by 1.
- **`i = 1`** we read the number 2, which, again, belongs to the first group and we increase the groups counter(**`cnt_p1`**) by 1.
- **`i = 2`** we read the number 999, which belongs to the last group(**`p5`**), because its bigger than 800, and we increase its group counter (**`cnt_p5`**) by 1.
After reading the numbers, we have two of them in the first group, and we have only one in the last group. There are **no numbers** in the other groups. After we apply the aforementioned formula, we calculate the percentage of each group. It doesnt matter whether we multiply by **100** or **100.0** well get the same result: the **first** group has 66.67%, and the **last** group 33.33%. We have to mention that this is valid only for **`Python 3`**.
#### Printing The Final Result
The last step is to print the calculated results. In the problems description, its said that the percentages have to be with **2-digit precision after the decimal point**. To achieve this, we have to write **`.2f`** after the placeholder.
![](/assets/chapter-5-2-images/01.Histogram-05.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1054#0](https://judge.softuni.org/Contests/Practice/Index/1054#0).
## Problem: Smart Lily
Lily is **N years old**. Each **birthday** she receives a gift. For her **odd** birthdays (1, 3, 5, …, n) she receives **toys**, and for each **even** birthday (2, 4, 6, …, n) she receives **money**. For her **second birthday** she receives **10.00 USD**, and **the sum increases by 10 USD with each following even birthday** (2 -> 10, 4 -> 20, 6 -> 30, etc.). Lily has secretly been saving the money for years. **Her brother**, in the years when she **receives money**, **takes 1.00 USD**. Lily **sold the toys** received with the years, **each for P USD**, and added the sum to the saved money. With them, she wants **to buy a washing machine for X USD**. Write a program that calculates **how much money she has saved** and whether **it's enough to buy a washing machine**.
### Input Data
**3 numbers** are read from the console, each on a new line:
- **Lily's age** **integer** in the range [**1 … 77**].
- **The price of the washing machine** a number in the range [**1.00 … 10 000.00**].
- **The price of a single toy** **integer** in the range [**0 … 40**].
### Output Data
Print a single line in the console:
* If Lily's money is enough:
* "**Yes! {N}**" where **N** is the remaining money after the purchase
* If it is not:
* "**No! {M}**" where **M** is the amount of money **lacking**
* The numbers **N** and **M** should be **formatted with 2-digit precision after the decimal point**.
### Sample Input and Output
<table>
<thead>
<tr>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
<th align="left"><strong>Comments</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top">10<br>170.00<br>6</td>
<td valign="top">Yes! 5.00</td>
<td valign="top"><p><strong>On the first birthday</strong> she receives <strong>a toy</strong>; <strong>Second</strong> -> <strong>10 USD</strong>; 3rd -> toy; <strong>4th</strong> -> 10 + 10 = <strong>20 USD</strong>; 5th -> toy; <strong>6th</strong> -> 20 + 10 = <strong>30 USD</strong>; 7th -> toy; <strong>8th</strong> -> 30 + 10 = <strong>40 USD</strong>; 9th -> toy; <strong>10th</strong> -> 40 + 10 = <strong>50 USD</strong><br>
<strong>She has saved</strong> -> 10 + 20 + 30 + 40 + 50 = <strong>150 USD</strong>. She has sold <strong>5 toys by 6 USD = 30 USD</strong>.<br>
<strong>Her brother took 1 USD for 5 years = 5 USD</strong>. <strong>Remaining money</strong> -> 150 + 30 5 = <strong>175 USD</strong>.
<strong>175 &gt;= 170</strong> (washing machine's price) <strong>She has succeeded</strong> buying it and there <strong>remain</strong> 175-170 = <strong>5 USD</strong>.
</p></td>
</tr>
<tr>
<td valign="top">21<br>1570.98<br>3</td>
<td valign="top">No! 997.98</td>
<td valign="top"><p><strong>She has saved 550 USD</strong>. <strong>She's sold</strong> <strong>11 toys</strong> by <strong>3 USD each</strong> = <strong>33 USD</strong>. Her brother <strong>has taken 1 USD for 10 years</strong> = <strong>10 USD</strong>. <strong>There remain</strong> 550 + 33 10 = <strong>573 USD.</strong> <br>
<strong>573 &lt; 1570.98</strong> <strong>She's failed</strong> buying a washing machine. <strong>She needs</strong> 1570.98573 = <strong>997.98 USD more.</strong></p></td>
</tr>
</tbody>
</table>
### Hints and Guidelines
Solving this problem, like the previous one, again can be divided into three parts **reading** the input data, **processing** it, and **outputting** a result.
As we already know, like in most scripting languages, in Python as well, we don't bother defining the types of the variables that we declare. The interpreter decides on its own what it'll be. For Lily's (**`age`**) and a single toy's price (**`present_price`**) in the problem's description, it's said that they'll be **integers**. That's why we'll use **the built-in function `int()`** to convert the read value from string to integer. When the **`input()`** function is used, the input's value in the console is always (**`string`**), that's why if a conversion to another type is needed, we can use **the built-in functions of Python** for this problem. For the washing machine's price, (**`price_of_washing_machine`**), we know that it's a **fractional number and we choose the `float` type**. In the code below **we declare** and **initialize** (assign a value) to the variables:
![](/assets/chapter-5-2-images/02.Smart-lilly-01.png)
To solve the problem, we'll need a couple of helper variables for **the toys' count** (**`number_of_toys`**) for **the saved money** (**`saved_money`**) and **the money received on each birthday** (**`money_for_birthday`**). We initially assign 10 to **`money_for_birthday`**, because in the description it's said that the first sum received by Lily is 10 USD:
![](/assets/chapter-5-2-images/02.Smart-lilly-02.png)
With a **`for` loop**, we go through each of Lily's birthdays. When a loop variable is an **even number**, it means that Lily has **received money** and we add them to her savings. At the same time, we **subtract 1 USD** - the money taken by her brother. After that we **increase** the value of the variable **`money_for_birthday`**, meaning we increase the sum by 10 for the next time she receives money for her birthday. Contrary, when the loop variable is an **odd number**, we increase the **toys**' count. Checking whether it's even or odd happens with a **division with the remainder** (**`%`**) **by 2** when the remainder is 0, the number is even, and when the remainder's 1 - it's odd:
![](/assets/chapter-5-2-images/02.Smart-lilly-03.png)
We add the money from the sold toys to Lily's savings:
![](/assets/chapter-5-2-images/02.Smart-lilly-04.png)
At the end we print the results, taking into account the required formatting, meaning the sum has to be **rounded to 2 digits after the decimal point**:
![](/assets/chapter-5-2-images/02.Smart-lilly-05.png)
In some programming languages there's a construction called **conditional operator (`?:`)** (also known as ternary operator), as it's shorter to write. It has the following syntax in Python: **`operand1 if operand2 else operand3`**. The second operand is our condition and it has to be of **bool type** (meaning it has to return **`true/false`**). If **`operand2`** returns **`true`**, it'll execute **`operand1`**, and if it returns **`false`** **`operand3`**. In our case, we check whether Lily's **saved money** is enough to buy a washing machine. If it's higher or equal to its price, the check **`saved_money >= price_of_washing_machine`** will return **`true`** and it'll print "**Yes! …**", while if it's lower the result will be **`false`**, and "**No! …**" will be printed. Of course, instead of the ternary operator, we can use simple **`if`** expressions.
More about ternary operators: [https://book.pythontips.com/en/latest/ternary_operators.html](https://book.pythontips.com/en/latest/ternary_operators.html).
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1054#1](https://judge.softuni.org/Contests/Practice/Index/1054#1).
## Problem: Back to The Past
John is **18 years old** and receives an inheritance of **X USD** and **a time-traveling machine**. He decides **to travel back to 1800**, but he doesn't know **whether the money** is **enough** to live without working. Write **a program that calculates** whether John **will have enough money**, to live without working **until a given year, including the year itself**. We accept that **each even year** (1800, 1802, etc.) he'll **spend 12 000 dollars**. For **each odd year** (1801, 1803, etc.) he'll spend **12 000 + 50 * [John's age in the given year]**.
### Input Data
The input is read from the console and **contains exactly 2 lines**:
* **The inherited money** a real number in the range [**1.00 … 1 000 000.00**].
* **The year until he has to live (inclusive)** a real number in the range [**1801 … 1900**].
### Output Data
**Print** to the console **1 line**. **The sum** has to be **formatted** with **2-digit precision after the decimal point**:
* If **the money is enough**:
* "**Yes! He will live a carefree life and will have {N} dollars left.**" where **N** is the remaining money.
* If **the money is NOT enough**:
* "**He will need {M} dollars to survive.**" where **M** is the amount **lacking**.
### Sample Input and Output
<table>
<thead>
<tr>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
<th align="left"><strong>Explanation</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top">50000<br>1802</td>
<td valign="top">Yes! He will live a carefree life and<br> will have 13050.00 dollars left.</td>
<td valign="top"><p>1800 &rarr; <strong>even</strong><br>
&nbsp; &nbsp; &nbsp; &nbsp; &rarr; <strong>Spends 12000</strong> dollars <br>
&nbsp; &nbsp; &nbsp; &nbsp; &rarr; Left 50000 12000 = <strong>38000</strong><br>
1801 &rarr; <strong>odd</strong> <br>
&nbsp; &nbsp; &nbsp; &nbsp; &rarr; <strong>Spends</strong> 12000 + <strong>19*50</strong> = 12950 dollars<br>
&nbsp; &nbsp; &nbsp; &nbsp; &rarr; <strong>Left</strong> 38000 12950 = <strong>25050</strong><br>
1802 &rarr; <strong>even</strong> <br>
&nbsp; &nbsp; &nbsp; &nbsp; &rarr; <strong>Spends</strong> 12000 dollars<br>
&nbsp; &nbsp; &nbsp; &nbsp; &rarr; <strong>Left</strong> 25050 12000 = <strong>13050</strong></p></td>
</tr>
<tr>
<td valign="top">100000.15<br>1808</td>
<td valign="top">He will need 12399.85 dollars<br> to survive.</td>
<td valign="top"><p>1800 &rarr; <strong>even</strong><br>
&nbsp; &nbsp; &nbsp; &nbsp; &rarr; Left 100000.15 12000 = <strong>88000.15</strong><br>
1801 &rarr; <strong>odd</strong> <br>
&nbsp; &nbsp; &nbsp; &nbsp; &rarr; <strong>Left</strong> 88000.15 12950 = <strong>75050.15</strong><br>
<strong>…</strong><br>
1808 &rarr; <strong>even</strong> &rarr; -399.85 - 12000 = -12399.85<br>
<strong>12399.85 lacking</strong>
</p></td>
</tr>
</tbody>
</table>
### Hints and Guidelines
The method of solving this problem isn't unlike the previous ones, so we begin by **declaring and initializing** the needed variables. In the problem's description, it's said that John's age is 18, so we declare the variable **`years`** with the initial value of **18**. We read other variables from the console:
![](/assets/chapter-5-2-images/03.Back-to-the-past-01.png)
With the help of a **`for` loop**, we loop through all years. **We begin at 1800** the year when John travels back in time, and we end at **the year until he has to live**. In the loop, we check whether the current year is **even** or **odd**. We check it with **division with a remainder** (**`%`**) by 2. If the year is **even**, from the inheritance (**`inheritance`**) we subtract **12000**, while if it's **odd**, from the inheritance (**`inheritance`**) we subtract **12000 + 50 * (John's age)**:
![](/assets/chapter-5-2-images/03.Back-to-the-past-02.png)
In the end, we print the results, and we do a **check whether the inheritance** (**`inheritance`**) has been enough for him to live without working or not. If the inheritance (**`inheritance`**) is **a positive number**, we print: "**`Yes! He will live a carefree life and will have {N} dollars left.`**", while if it's a **negative number**: "**`He will need {M} dollars to survive.`**". We don't forget to format the sum with 2-digit precision after the decimal point.
**Hint**: Think about using the function **`abs(…)`** when printing the output and the inheritance is not enough.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1054#2](https://judge.softuni.org/Contests/Practice/Index/1054#2).
## Problem: Hospital
For a given amount of time, patients arrive for a checkup in the hospital every day. She **initially** has **7 doctors**. Each of them can **check one patient a day only**, but sometimes there's a shortage of doctors, so **the other patients are sent to other hospitals**. **Every third day** the hospital calculates **whether the count of patients that haven't been examined is higher than those that have been and if so, an additional doctor is assigned**. The assignment happens before the start of the day.
Write a program that calculates **the count of treated and untreated patients for the given period**.
### Input Data
The input is read from the **console** and contains:
* On the first line **the period** for which we'll be calculating. **Integer** in the range [**1 … 1000**].
* On the following lines (equal to the number of days) **the count of patients** that arrive for a checkup **on the current day**. Integer in the range [**0 … 10 000**].
### Output Data
**Print** to the console **2 lines**:
* On **the first line**: "**Treated patients: {count of treated patients}.**"
* On **the second line**: "**Untreated patients: {count of untreated patients}.**"
### Sample Input and Output
<table>
<thead>
<tr>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
<th align="left"><strong>Explanation</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top">4<br>7<br>27<br>9<br>1</td>
<td valign="top">Treated patients: 23.<br>Untreated patients: 21.</td>
<td valign="top"><p><strong>Day 1</strong>: 7 treated and 0 untreated patients for the day<br>
<strong>Day 2</strong>: 7 treated and 20 untreated patients for the day<br>
<strong>Day 3</strong>: Until now the treated patients are 14,<br> and the untreated 20 > A new doctor is assigned <br>>
8 treated and 1 untreated patients for the day<br>
<strong>Day 4</strong>: 1 treated and 0 untreated patients for the day<br>
<strong>Total: 23 treated and 21 untreated patients.</strong></p></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top">6<br>25<br>25<br>25<br>25<br>25<br>2</td>
<td valign="top">Treated patients: 40.<br>Untreated patients: 87.</td>
</tr>
<tr>
<td valign="top">3<br>7<br>7<br>7</td>
<td valign="top">Treated patients: 21.<br>Untreated patients: 0.</td>
</tr>
</tbody>
</table>
### Hints and Guidelines
Again, we begin by **declaring and initializing** the needed variables. The period, for which we have to do our calculations, we read from the console and assign to the variable **`period`**. We'll need a couple of additional variables: the count of treated patients (**`treated_patients`**), the count of untreated patients (**`untreated_patients`**), and the count of doctors (**`count_of_doctors`**), which is initially 7:
![](/assets/chapter-5-2-images/04.Hospital-01.png)
With the help of the **`for` loop**, we go through all days in the given period (**`period`**). For each day we read the number of patients from the console (**`current_patients`**). The addition of doctors is said in the problem's description to happen **every third day**, **BUT** only if the untreated patients' count is **higher** than the treated's count. That's why we check whether the day is the third one with the arithmetic operator for division with a remainder (**`%`**): **`day % 3 == 0`**.
Example:
* If the day is a **third** one, the remainder of division by **3** will be **0** (**`3 % 3 = 0`**) and the check **`day % 3 == 0`** will return **`true`**.
* If the day is a **second** one, the remainder of division by **3** will be **2** (**`2 % 3 = 2`**) and the check will return **`false`**.
* If the day is a **fourth** one, the remainder of the division will be **1** (**`4 % 3 = 1`**) and the check will again return **`false`**.
If the conditional check **`day % 3 == 0`** returns **`true`**, there'll also be a check whether the count of untreated patients is higher than the treated's count: **`untreated_patients > treated_patients`**. If the result is again **`true`**, then the count of doctors (**`count_of_doctors`**) will increase.
After that, we check whether the patients' count for the current day (**`current_patients`**) is higher than the doctors' count (**`count_of_doctors`**). If the patients' count is **higher**:
- We increase the value of the variable **`treated_patients`** with the doctors' count (**`count_of_doctors`**).
- We increase the value of the variable **`untreated_patients`** with the count of patients left, which we calculate by subtracting the doctors' count from the patients' count (**`current_patients - count_of_doctors`**).
If the patients' count is **lower**, we increase only the variable **`treated_patients`** with the current day's count of patients (**`current_patients`**):
![](/assets/chapter-5-2-images/04.Hospital-02.png)
In the end, we only have to print the count of treated and untreated patients.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1054#3](https://judge.softuni.org/Contests/Practice/Index/1054#3).
## Problem: Division
We're given **n integers** in the range [**1 … 1000**]. A percentage of them, **percent p1, are divided by 2 without remainder**, **percent p2** are **divided by 3 without remainder**, **percent p3** are **divided by 4 without remainder**. Write a program that calculates and prints the percentages p1, p2, and p3.
**Example:** we have **n = 10** integers: 680, 2, 600, 200, 800, 799, 199, 46, 128, 65. We get the following distribution and visualization:
<table>
<thead>
<tr>
<th align="left"><strong>Division without remainder by:</strong></th>
<th align="left"><strong>Numbers</strong></th>
<th align="left"><strong>Count</strong></th>
<th align="left"><strong>Percentage</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top">2</td>
<td valign="top">680, 2, 600, 200, 800, 46, 128</td>
<td valign="top">7</td>
<td valign="top">p1 = (7 / 10) * 100 = <strong>70.00%</strong></td>
</tr>
<tr>
<td valign="top">3</td>
<td valign="top">600</td>
<td valign="top">1</td>
<td valign="top">p2 = (1 / 10) * 100 = <strong>10.00%</strong></td>
</tr>
<tr>
<td valign="top">4</td>
<td valign="top">680, 600, 200, 800, 128</td>
<td valign="top">5</td>
<td valign="top">p3 = (5 / 10) * 100 = <strong>50.00%</strong></td>
</tr>
</tbody>
</table>
### Input Data
On the first line of the input stands the integer **n** (1 ≤ **n** ≤ 1000) count of numbers. On the next **n lines**, each stands **a single integer** in the range [**1 … 1000**] the numbers for which we'll check their divisors.
### Output Data
Print to the console **3 lines**, each of them containing a percentage between 0% and 100%, with 2-digit precision after the decimal point, for example: 25.00%, 66.67%, 57.14%.
* On the **first line** the percentage of numbers **divisible by 2**.
* On the **second line** the percentage of numbers **divisible by 3**.
* On the **third line** the percentage of numbers **divisible by 4**.
### Sample Input and Output
<table>
<thead>
<tr>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top"><strong>10</strong><br>680<br>2<br>600<br>200<br>800<br>799<br>199<br>46<br>128<br>65</td>
<td valign="top">70.00%<br>10.00%<br>50.00%</td>
<td valign="top"><strong>3</strong><br>3<br>6<br>9</td>
<td valign="top">33.33%<br>100.00%<br>0.00%</td>
<td valign="top"><strong>1</strong><br>12</td>
<td valign="top">100.00%<br>100.00%<br>100.00%</td>
</tr>
</tbody>
</table>
### Hints and Guidelines
For this and the next problem, you'll have to write the program's code on your own, with the help of the following advice.
The program that solves the current problem is similar to the one from the problem **Histogram**, which we viewed previously. That's why we can begin by declaring our needed variables. For example, a couple of variable names can be **`n`** count of numbers (which we'll read from the console) and **`divisible_by_2`**, **`divisible_by_3`**, **`divisible_by_4`** additional variables, storing the count of numbers in their respective groups.
To read and distribute each number in its respective group, we'll have to start our**`for` loop** from **`0`** and end at **`n`** (the numbers' count). Each of the loop's iterations has to read and distribute **a single number**. The difference is that **a single number can be distributed to more than one group simultaneously**, so we have to do **three different `if` checks for each number** whether it's divided by 2, 3, and 4, and to increase the value of the variable that stores the count of numbers in the respective group.
**Warning**: an **`if-elif`** construction won't be of use to us, since when it detects a match, the loop gets broken before checking the following conditions.
In the end, print the found results while keeping the given in the problem's description format.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1054#4](https://judge.softuni.org/Contests/Practice/Index/1054#4).
## Problem: Logistics
You're responsible for the logistics of different cargos. **Depending on the weight** of each load, a **different vehicle** is needed and costs **a different price per ton**:
* Up to and including **3 tons** **van** (200 USD per ton).
* **Over 3 and up to 11 tons** **truck** (175 USD per ton).
* **Over 11 tons train** (120 USD per ton).
Your task is to calculate **the average price per ton of transported load**, as well as **what percentage of the overall cargo** is transported by **each vehicle**.
### Input Data
**A sequence of numbers** is read from the console, each on a different line:
* **First line**: **count of loads** for transportation **integer** in the range [**1 … 1000**].
* On each following line, **the weight in tons of the current load** is written **integer** in the range [**1 … 1000**].
### Output Data
Print **4 lines** to the console, as given:
* **Line #1** **the average price per ton of transported cargo** (rounded to the second digit after the decimal point).
* **Line #2** **the percentage** of cargo, transported with a **van** (between 0.00% and 100.00%, rounded to the second digit after the decimal point).
* **Line #3** **the percentage** of cargo, transported with a **truck** (between 0.00% and 100.00%).
* **Line #4** **the percentage** of cargo, transported with a **train** (between 0.00% and 100.00%).
### Sample Input and Output
<table>
<thead>
<tr>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
<th align="left"><strong>Explanation</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top">4<br>1<br>5<br>16<br>3</td>
<td valign="top">143.80<br>16.00%<br>20.00%<br>64.00%</td>
<td valign="top">
Two of the cargos are transported with a <b>van</b>: <b>1</b> + <b>3</b>, total <b>4</b> tons.<br>
One cargo is transported with a <b>truck</b>: <b>5</b> tons.<br>
One cargo is transported with a <b>train</b>: <b>16</b> tons.<br>
<b>The sum</b> of all cargos is: 1 + 5 + 16 + 3 = <b>25</b> tons.<br>
The percentage of <b>van-transported</b> cargo: 4/25*100 = <b>16.00%</b><br>
The percentage of <b>truck-transported</b> cargo: 5/25*100 = <b>20.00%</b><br>
The percentage of <b>train-transported</b> cargo: 16/25*100 = <b>64.00%</b><br>
<b>Average price</b> per ton of transported cargo: (4 * 200 + 5 * 175 + 16 * 120) / 25 = <b>143.80</b>
</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
<th align="left"><strong>Input</strong></th>
<th align="left"><strong>Output</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td valign="top">5<br>2<br>10<br>20<br>1<br>7</td>
<td valign="top">149.38<br>7.50%<br>42.50%<br>50.00%</td>
<td valign="top">4<br>53<br>7<br>56<br>999</td>
<td valign="top">120.35<br>0.00%<br>0.63%<br>99.37%</td>
</tr>
</tbody>
</table>
### Hints and Guidelines
First, **we'll read the weight of each load** and we'll **sum** how many tons are being transported by a **van**, **truck**, and **train** respectively, and we'll additionally calculate **the total tons** of transported cargos. We'll calculate **the prices of each transport type** according to the total tons and **the total price**. In the end, we'll calculate and print **the total average price per ton** and **what part of the overall load is transported by each transport type, in percentages**.
We declare our variables, for example: **`count_of_loads`** the count of cargos to be transported (we read them from the console), **`sum_of_tons`** the sum of the overall load's weight, **`microbus_tons`**, **`truck_tons`**, **`train_tons`** variables, holding the sum of the weights transported respectively by a van, truck, and train.
We'll need a **`for` loop** from **`0`** to **`count_of_loads - 1`**, to go through all loads. For each load, **we read its weight** (in tons) from the console and assign it to our variable, for example, **`tons`**. To the sum of all loads (**`sum_of_tons`**), we add our current load's weight (**`tons`**). After we've read our current load's weight, **we have to decide which transport vehicle will be used for it** (van, truck or train). For this we'll need some **`if-elif`** checks:
* If the value of the variable **`tons`** is **lower than 3**, we increase the value of the variable **`microbus_tons`** by the value of **`tons`**:
```python
microbus_tons += tons;
```
* Else, if the value of **`tons`** is **up to 11**, we increase **`truck_tons`** by **`tons`**.
* If **`tons`** is **higher than 11**, we increase **`train_tons`** by **`tons`**.
Before we print our output, we have to **calculate the percentage of tons transported by each vehicle** and **the average price per ton**. For the average price, we'll declare another additional variable **`total_price`**, in which we'll **sum the total price of all transported loads** (with a van, truck, and train). The average price will be calculated by dividing **`total_price`** by **`sum_of_tons`**. You're left with **calculating by yourself** the percentage of tons transported by each vehicle and printing the output, adhering to the format as shown in the problem's description.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1054#5](https://judge.softuni.org/Contests/Practice/Index/1054#5).

View File

@@ -0,0 +1,320 @@
# Chapter 6.2. Nested Loops Exam Problems
In the previous chapter, we introduced **nested loops** and how to use them for **drawing** various kinds of **figures on the console**. We've learned how to print figures with different sizes, establishing suitable logic construction by using **single and nested `for`** loops in combination with different calculations and program logic:
```python
for r in range(5):
print("*", end="")
for c in range(5):
print(" *", end="")
print("")
```
We also learned the **operator `*`**, which lets you for defined by us a **number** of times, a **given string** to be printed:
```python
print_me = ('abc' * 2)
```
## Exam Problems
Now let's solve some Exam Problems to consolidate what we have learned and to develop our algorithmic thinking.
## Problem: Draw Fort
Write a program, that reads from the console an **integer n** and draws a **fortress** with a width of **2 * n columns** and height of **n rows**, as in the below-given examples. The left and the right inner columns have a width of **n / 2**.
### Input Data
The program input consists one element (argument) - **integer n** within the range [**3 … 1000**].
### Output Data
Print on the console **n** text lines, depicting the **fortress**, just as in the examples below.
### Sample Input and Output
|Input|Output|Input|Output|
|----|----|----|----|
|3|<code>&#47;&#94;&#92;&#47;&#94;&#92;</code><br><code>&#124;&nbsp;&nbsp;&nbsp;&nbsp;&#124;</code><br><code>&#92;&#95;&#47;&#92;&#95;&#47;</code>|4|<code>&#47;&#94;&#94;&#92;&#47;&#94;&#94;&#92;</code><br><code>&#124;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#124;</code><br><code>&#124;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#124;</code><br><code>&#92;&#95;&#95;&#47;&#92;&#95;&#95;&#47;</code><br>|
|Input|Output|Input|Output|
|----|----|----|----|
|5|<code>&#47;&#94;&#94;&#92;&#95;&#95;&#47;&#94;&#94;&#92;</code><br><code>&#124;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#124;</code><br><code>&#124;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#124;</code><br><code>&#124;&nbsp;&nbsp;&nbsp;&#95;&#95;&nbsp;&nbsp;&nbsp;&#124;</code><br><code>&#92;&#95;&#95;&#47;&nbsp;&nbsp;&#92;&#95;&#95;&#47;</code><br>|8|<code>&#47;&#94;&#94;&#94;&#94;&#92;&#95;&#95;&#95;&#95;&#47;&#94;&#94;&#94;&#94;&#92;</code><br><code>&#124;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#124;</code><br><code>&#124;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#124;</code><br><code>&#124;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#124;</code><br><code>&#124;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#124;</code><br><code>&#124;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#124;</code><br><code>&#124;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#95;&#95;&#95;&#95;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#124;</code><br><code>&#92;&#95;&#95;&#95;&#95;&#47;&nbsp;&nbsp;&nbsp;&nbsp;&#92;&#95;&#95;&#95;&#95;&#47;</code><br>|
### Hints and Guidelines
By the set task condition, we can see that the **input data** will contain only one **integer** within the range [**3 … 1000**]. Therefore, we will convert the input value into **`int`** type:
![](/assets/chapter-6-2-images/01.Draw-fort-01.png)
After we've declared and initialized the input data, we have to divide the **fortress** into three parts:
* roof
* body
* base
We can see from the examples, that the **roof** consists of **two towers** and **a middle part**. Each tower has a beginning **`/`**, middle part **`^`** and an end **`\`**.
By the set task condition the left and the right inner columns have a width of **`n / 2`**, therefore we can save this value as a separate **variable**, keeping in mind, that if we receive an **odd number** as input, the result of dividing by two will be a number with a whole and fractional part. In this case, we need **only the whole part** (in the set task condition we can see, that when the input is equal to **3** the count of **`^`** in the inner part column is equal to **1**, and the input of **5** it is **3**), we can separate it with the function **`math.trunc(…)`** and to save only its value in our new variable:
![](/assets/chapter-6-2-images/01.Draw-fort-02.png)
<table><tr><td><img src="/assets/alert-icon.png" style="max-width:50px" /></td>
<td>It's always a good practice, whenever we have an expression with the value we intend to use <b>more than once</b>, to keep it in a variable. In this way, on the one hand, our code will be <b>easier to read</b>, and on the other hand, it will be <b>easier to correct</b> possible <b>errors</b>, as we will not have to look for each use of the expression separately. </td>
</tr></table>
We also declare a second **variable**, which will keep **the value** of the part **between the two towers**. By the set task condition, we know that the total width of the fortress is **`n * 2`**. In addition, we have two towers with one slash for a start and one slash for an end (a total of 4 characters), and width of **`col_size`**. Therefore, to get the number of characters in the middle part, we have to subtract the size of the towers from the width of the entire fortress: **`2 * n - 2 * col_size - 4`**.
![](/assets/chapter-6-2-images/01.Draw-fort-03.png)
To print the **roof** part, on the console we will use the **`format(…)`** method in combination with the operator **`*`**, which joins a given string **n** number of times:
![](/assets/chapter-6-2-images/01.Draw-fort-04.png)
<table><tr><td><img src="/assets/alert-icon.png" style="max-width:50px" /></td>
<td><strong><code>\</code></strong> is a special symbol in Python and using it solely in the method <strong><code>print(…)</code></strong>, the console will not print it out, so with <strong><code>\\</code></strong> we indicate on the console, that we want to print out exactly this character, without interpreting it as a special character (<b>character escaping it</b>).</td>
</tr></table>
**The fortress body** consists of beginning **`|`**, middle part **`(white spaces)`**, and an end **`|`**. **The middle part** of white spaces has a width of **`2 * n - 2`**. The number of **rows** for the walls can be determined from the given examples: **`n - 3`**:
![](/assets/chapter-6-2-images/01.Draw-fort-05.png)
To draw a penultimate row, which is part of the base, we need to print a beginning **`|`**, middle part **`(white space)_(white space)`**, and an end **`|`**. To do this, we can use already declared variables **`col_size`** and **`mid_size`** because as we see from the examples they are equal to the number of **`_`** in the roof:
![](/assets/chapter-6-2-images/01.Draw-fort-06.png)
We add to the value of **white spaces** **`+ 1`** because in the examples we have **one** white space more.
The structure of the **fortress base** is the same as the one in the **roof**. It includes **two towers** and a **middle part**. Each **tower** begins with **`\`**, followed by a middle part **`_`**, and an end **`/`**.
![](/assets/chapter-6-2-images/01.Draw-fort-07.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1056#0](https://judge.softuni.org/Contests/Practice/Index/1056#0).
## Problem: Butterfly
Write a program, that takes **an integer n** from the console and draws **butterfly** with a width of **2 * n - 1 columns** and height of **2 * (n - 2) + 1 rows** as in the examples below. **The left and the right part** have a **width of n - 1**.
### Input Data
The input consists of one element (argument) - **integer n** in the range [**3 … 1000**].
### Output Data
Print on the console **2 * (n - 2) + 1** text rows, representing the **butterfly**, exactly as shown in the examples.
### Sample Input and Output
|Input|Output|Input|Output|
|---|---|---|---|
|3|<code>&#42;&#92;&nbsp;&#47;&#42;</code><br><code>&nbsp;&nbsp;&#64;&nbsp;&nbsp;</code><br><code>&#42;&#47;&nbsp;&#92;&#42;</code><br>|5|<code>&#42;&#42;&#42;&#92;&nbsp;&#47;&#42;&#42;&#42;</code><br><code>&#45;&#45;&#45;&#92;&nbsp;&#47;&#45;&#45;&#45;</code><br><code>&#42;&#42;&#42;&#92;&nbsp;&#47;&#42;&#42;&#42;</code><br><code>&nbsp;&nbsp;&nbsp;&nbsp;&#64;&nbsp;&nbsp;&nbsp;&nbsp;</code><br><code>&#42;&#42;&#42;&#47;&nbsp;&#92;&#42;&#42;&#42;</code><br><code>&#45;&#45;&#45;&#47;&nbsp;&#92;&#45;&#45;&#45;</code><br><code>&#42;&#42;&#42;&#47;&nbsp;&#92;&#42;&#42;&#42;</code><br>|
|Input|Output|
|---|---|
|7|<code>&#42;&#42;&#42;&#42;&#42;&#92;&nbsp;&#47;&#42;&#42;&#42;&#42;&#42;</code><br><code>&#45;&#45;&#45;&#45;&#45;&#92;&nbsp;&#47;&#45;&#45;&#45;&#45;&#45;</code><br><code>&#42;&#42;&#42;&#42;&#42;&#92;&nbsp;&#47;&#42;&#42;&#42;&#42;&#42;</code><br><code>&#45;&#45;&#45;&#45;&#45;&#92;&nbsp;&#47;&#45;&#45;&#45;&#45;&#45;</code><br><code>&#42;&#42;&#42;&#42;&#42;&#92;&nbsp;&#47;&#42;&#42;&#42;&#42;&#42;</code><br><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#64;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</code><br><code>&#42;&#42;&#42;&#42;&#42;&#47;&nbsp;&#92;&#42;&#42;&#42;&#42;&#42;</code><br><code>&#45;&#45;&#45;&#45;&#45;&#47;&nbsp;&#92;&#45;&#45;&#45;&#45;&#45;</code><br><code>&#42;&#42;&#42;&#42;&#42;&#47;&nbsp;&#92;&#42;&#42;&#42;&#42;&#42;</code><br><code>&#45;&#45;&#45;&#45;&#45;&#47;&nbsp;&#92;&#45;&#45;&#45;&#45;&#45;</code><br><code>&#42;&#42;&#42;&#42;&#42;&#47;&nbsp;&#92;&#42;&#42;&#42;&#42;&#42;</code><br>|
### Hints and Guidelines
Similar to the previous task, we can see from the condition, that the **input data** will consist of only one **integer** in the range [**3 … 1000**]. That's why we will convert the input value into **`int`** type:
![](/assets/chapter-6-2-images/02.Butterfly-01.png)
We can divide the figure into 3 parts - **upper wing**, **body**, and **lower wing**. To draw the upper wing of the butterfly, we have to divide it into three parts - a beginning with **`*`**, a middle part with **`\ /`**, and an end with **`*`**. After looking at the examples, we can say that the upper wing of the butterfly is with a size of **`n - 2`**:
![](/assets/chapter-6-2-images/02.Butterfly-02.png)
To draw the upper wing we make a loop repeated **`half_row_size`** number of times:
![](/assets/chapter-6-2-images/02.Butterfly-03.png)
We can see in the examples, that on an **even** row we have a beginning **`*`**, middle part **`\ /`** and an end **`*`**, on the other hand on an **odd** row we have a beginning **`-`**, middle part **`\ /`** and an end **`-`**. Therefore, at each iteration of the loop, we have to do an **`if-else`** check to see whether the row that we print is even or odd. From the examples given in the set condition, we can see that the number of star characters and dashes on each row is equal to **`n - 2`**, i. e. we can use again the variable **`half_row_size`** to print them:
![](/assets/chapter-6-2-images/02.Butterfly-04.png)
To draw the **butterfly body**, we have to print exactly **one** row on the console. The structure of the body has a beginning **`(white space)`**, middle part **`@`**, and an end **`(white space)`**. From the examples we can see, that the number of the white spaces is equal to **`n-1`**:
![](/assets/chapter-6-2-images/02.Butterfly-05.png)
What is left now is to print on the console the **lower wing**, which is **analogical to the upper wing**: we only need to swap the places of the slashes.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1056#1](https://judge.softuni.org/Contests/Practice/Index/1056#1).
## Problem: Stop
Write a program, that takes an **integer n** from the console and draws **a STOP warning sign** with size as shown in the examples below.
### Input Data
The input consists of one element (argument) - **integer n** in the range [**3 … 1000**].
### Output Data
Print on the console text lines, representing **the STOP warning sign**, just as in the examples.
### Sample Input and Output
|Input|Output|Input|Output|
|----|----|----|----|
|3|<code>....\_\_\_\_\_\_\_....</code><br><code>...//\_\_\_\_\_\\\\...</code><br><code>..//\_\_\_\_\_\_\_\\\\..</code><br><code>.//\_\_\_\_\_\_\_\_\_\\\\.</code><br><code>//\_\_\_STOP!\_\_\_\\\\</code><br><code>\\\\\_\_\_\_\_\_\_\_\_\_\_//</code><br><code>.\\\\\_\_\_\_\_\_\_\_\_//.</code><br><code>..\\\\\_\_\_\_\_\_\_//..</code><br>|6|<code>.......\_\_\_\_\_\_\_\_\_\_\_\_\_.......</code><br><code>......//\_\_\_\_\_\_\_\_\_\_\_\\\\......</code><br><code>.....//\_\_\_\_\_\_\_\_\_\_\_\_\_\\\\.....</code><br><code>....//\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\\\\....</code><br><code>...//\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\\\\...</code><br><code>..//\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\\\\..</code><br><code>.//\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\\\\.</code><br><code>//\_\_\_\_\_\_\_\_\_STOP!\_\_\_\_\_\_\_\_\_\\\\</code><br><code>\\\\\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_//</code><br><code>.\\\\\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_//.</code><br><code>..\\\\\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_//..</code><br><code>...\\\\\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_//...</code><br><code>....\\\\\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_//....</code><br><code>.....\\\\_\_\_\_\_\_\_\_\_\_\_\_\_//.....</code><br>|
|Input|Output|
|---|---|
|7|<code>........\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_........</code><br><code>.......//\_\_\_\_\_\_\_\_\_\_\_\_\_\\\\.......</code><br><code>......//\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\\\\......</code><br><code>.....//\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\\\\.....</code><br><code>....//\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\\\\....</code><br><code>...//\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\\\\...</code><br><code>..//\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\\\\..</code><br><code>.//\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\\\\.</code><br><code>//\_\_\_\_\_\_\_\_\_\_\_STOP!\_\_\_\_\_\_\_\_\_\_\_\\\\</code><br><code>\\\\\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_//</code><br><code>.\\\\\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_//.</code><br><code>..\\\\\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_//..</code><br><code>...\\\\\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_//...</code><br><code>....\\\\\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_//....</code><br><code>.....\\\\\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_//.....</code><br><code>......\\\\\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_//......</code><br>|
### Hints and Guidelines
As in the previous examples, **the input data** will be on one line, which will contain one **int** in the range [**3 … 1000**]:
![](/assets/chapter-6-2-images/03.Stop-01.png)
We can **divide** the figure into **3 parts** - upper, middle, and lower. **The upper part** consists of two subparts - a starting line and lines in which the sign widens. **The starting line** consists of beginning **`.`**, middle part **`_`** and an end **`.`**. After looking at the examples, we can see that the beginning has a size of **`n + 1`** and it's better to keep this **value** as a separate **variable**. We also have to create a second **variable**, in which we will keep **the value** of the **first-row middle part** which has a size of **`2 * n + 1`**:
![](/assets/chapter-6-2-images/03.Stop-02.png)
Once we have declared and initialized the two variables, we can print the first row on the console:
![](/assets/chapter-6-2-images/03.Stop-03.png)
To draw the rows in which the sign is getting **"wider"**, we have to create a **loop**, that iterates **`n`** number of times. The row structure consists of a beginning **`.`**, **`//`** + middle part **`_`** + **`\\`** and an end **`.`**. To reuse the already created **variables**, we have to decrease **`dots`** by 1 and **`underscores`** by 2, because we've already **printed** the first row, and the dots and underscores in the top part of the figure are **decreasing** on each row:
![](/assets/chapter-6-2-images/03.Stop-04.png)
At each subsequent iteration **the beginning** and **the end** decrease by 1, and **the middle part** increases by 2:
![](/assets/chapter-6-2-images/03.Stop-05.png)
**The middle part** of the figure begins with **`//`** + **`_`**, middle part **`STOP!`** and an end **`_`** + **`\\`**. The count of the underscores **`_`** is **`(underscores - 5) / 2`**:
![](/assets/chapter-6-2-images/03.Stop-06.png)
**The lower part** of the figure, in which the width of the sign **decreases**, can be done by creating a **loop**, that iterates **`n`** number of times. The structure of a row should have a beginning **`.`** + **`\\`**, middle part **`_`** and an end **`//`** + **`.`**. The number of the **dots** in the first loop iteration has to be 0 and each subsequent has to **increase** by one. Therefore we can say that the **dots in the lower part of the figure** are equal to **`i`**. To ensure proper operation of our program, on each **loop** iteration, we have to **decrease** the number of **`_`** by **2**:
![](/assets/chapter-6-2-images/03.Stop-07.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1056#2](https://judge.softuni.org/Contests/Practice/Index/1056#2).
## Problem: Arrow
Write a program that receives from the console **an odd integer n** and draws **a vertical arrow** with size as in the examples below.
### Input Data
The input is **an odd integer n** (argument) within the range [**3 … 79**].
### Output Data
Print on the console a vertical arrow, in which "**`#`**" (hash sign) marks the outline of the arrow, and "**`.`**" - the rest.
### Sample Input and Output
|Input|Output|Input|Output|
|----|----|----|----|
|3|<code>.###.</code><br><code>.#.#.</code><br><code>##.##</code><br><code>.#.#.</code><br><code>..#..</code><br>|5|<code>..#####..</code><br><code>..#...#..</code><br><code>..#...#..</code><br><code>..#...#..</code><br><code>###...###</code><br><code>.#.....#.</code><br><code>..#...#..</code><br><code>...#.#...</code><br><code>....#....</code><br>|
|Input|Output|
|---|---|
|9|<code>....#########....</code><br><code>....#.......#....</code><br><code>....#.......#....</code><br><code>....#.......#....</code><br><code>....#.......#....</code><br><code>....#.......#....</code><br><code>....#.......#....</code><br><code>....#.......#....</code><br><code>#####.......#####</code><br><code>.#.............#.</code><br><code>..#...........#..</code><br><code>...#.........#...</code><br><code>....#.......#....</code><br><code>.....#.....#.....</code><br><code>......#...#......</code><br><code>.......#.#.......</code><br><code>........#........</code><br>|
### Hints and Guidelines
From the explanation we see that **the input data** will be read from one input line only, which will contain **an integer** within the range [**3 … 1000**]. That's why we will convert the input value into **`int`** type:
![](/assets/chapter-6-2-images/04.Arrow-01.png)
We can divide the figure into **3 parts** - upper, middle, and lower. **The upper part** consists of two subparts - the first row and the body of the arrow. We can see from the examples, that the count of **the outer dots** in the first row and the body of the arrow are equal to **`(n - 1) / 2`**. We can keep this value in **a variable** **`outer_dots`**:
![](/assets/chapter-6-2-images/04.Arrow-02.png)
The count of **the inner dots** in the body of the arrow is equal to **`(n - 2)`**. We have to create **the variable** **`inner_dots`**, which will keep this value:
![](/assets/chapter-6-2-images/04.Arrow-03.png)
We can see from the examples the structure of the first row. We can use the declared and initialize by us **variables** **`outer_dots`** and **`n`**, to print **the first row**:
![](/assets/chapter-6-2-images/04.Arrow-04.png)
To draw **the body of the arrow**, we have to create **a loop**, which iterates **`n - 2`** number of times:
![](/assets/chapter-6-2-images/04.Arrow-05.png)
**The middle part of the figure** is made of a beginning **`#`**, middle part **`.`** and an end **`#`**. The count of **`#`** is equal to **`outer_dots`** and that is why we will use the same **variable**:
![](/assets/chapter-6-2-images/04.Arrow-06.png)
To draw **the lower part of the arrow**, we have to assign new values of the two **variables** **`outer_dots`** and **`inner_dots`**.
![](/assets/chapter-6-2-images/04.Arrow-07.png)
On each loop iteration **`outer_dots`** increase by 1, and **`inner_dots`** decrease by 2. We can notice, that on the penultimate row the **`inner_dots`** value will be 1 and on each subsequent loop iteration will be a **negative number**. Since the operator **`*`** cannot concatenate symbol 0 or a negative number of times in a string, it will print nothing on the console. To avoid that we can print the last row of the figure separately. The height of the lower part of the arrow is **`n - 1`**, therefore **the loop**, that will print all the rows, except the last one, have to iterate **`n - 2`** number of times:
![](/assets/chapter-6-2-images/04.Arrow-08.png)
**The last row** of our figure is made of a beginning **`.`**, middle part **`#`** and an end **`.`**. The count of **`.`** is equal to **`outer_dots`**:
![](/assets/chapter-6-2-images/04.Arrow-09.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1056#3](https://judge.softuni.org/Contests/Practice/Index/1056#3).
## Problem: Axe
Write a program, that receives **an integer n** and draws an axe with size as in the example below. The width of the axe is **5 * n** columns.
### Input Data
The input consists one element (argument) - **integer n** within range [**2..42**].
### Output Data
Print on the console **axe**, as in the examples.
### Sample Input and Output
|Input|Output|Input|Output|
|---|---|---|---|
|2|<code>------\*\*--</code><br><code>------\*-\*-</code><br><code>\*\*\*\*\*\*\*-\*-</code><br><code>------\*\*\*-</code><br>|5|<code>---------------\*\*--------</code><br><code>---------------\*-\*-------</code><br><code>---------------\*--\*------</code><br><code>---------------\*---\*-----</code><br><code>---------------\*----\*----</code><br><code>\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*----\*----</code><br><code>\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*----\*----</code><br><code>---------------\*----\*----</code><br><code>--------------\*\*\*\*\*\*\*\*---</code><br>|
|Input|Output|
|---|---|
|8|<code>------------------------\*\*--------------</code><br><code>------------------------\*-\*-------------</code><br><code>------------------------\*--\*------------</code><br><code>------------------------\*---\*-----------</code><br><code>------------------------\*----\*----------</code><br><code>------------------------\*-----\*---------</code><br><code>------------------------\*------\*--------</code><br><code>------------------------\*-------\*-------</code><br><code>\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*-------\*-------</code><br><code>\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*-------\*-------</code><br><code>\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*-------\*-------</code><br><code>\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*-------\*-------</code><br><code>------------------------\*-------\*-------</code><br><code>-----------------------\*---------\*------</code><br><code>----------------------\*-----------\*-----</code><br><code>---------------------\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*----</code><br>|
### Hints and Guidelines
From the explanation we see that **the input data** will be read from one input line only, which will contain **an integer** within the range [**2 … 42**]. That's why we will use **`int`** type. After that, for the solution we need to calculate the **dashes in the left**, **the dashes in the middle**, **the dashes in the right**, and the whole figure length:
![](/assets/chapter-6-2-images/05.Axe-01.png)
Once we have declared and initialized the **variables**, we can draw the figure, starting with the **upper part**. We can see from the examples what the structure of **the first row** is and we can create a loop that iterates **`n`** number of times. At each loop iteration, **the middle dashes** are increasing by 1, and the **right dashes** are decreasing by 1:
![](/assets/chapter-6-2-images/05.Axe-02.png)
Now we have to draw the **handle of the axe**. To be able to use the newly created **variables**, when drawing the handle of the axe, we have to decrease **the middle dashes** by 1 and increase **these on the right and left** by 1.
![](/assets/chapter-6-2-images/05.Axe-03.png)
**The handle of the axe** we can draw, by iterating a loop that repeats **`n / 2`** number of times. We can set this value into a separate **variable**, considering that when dividing **odd number** inputs by 2 the result will be **a real number** with a whole and fractional part. Since in this case, we need **only the whole part** (from the example condition we see that at input **5** the height of the axe handle is **2**), we can use the **`math.trunc(…)`** method, to save only its value in our new variable **`axe_height`**. We get the structure of the handle from the examples given:
![](/assets/chapter-6-2-images/05.Axe-04.png)
**The lower part** of the figure should be divided into two subparts - the **head of the axe** and the **last row of the figure**. We will print on the console **the head of the axe**, by making a self iterating loop **`axe_height - 1`** number of times. On each iteration, **the left dashes** and **the right dashes** decrease by 1, and **the middle dashes** increase by 2:
![](/assets/chapter-6-2-images/05.Axe-05.png)
For **the last row** of the figure, we can use again, the already declared variables **`left_dashes`**, **`middle_dashes`**, **`right_dashes`**.
![](/assets/chapter-6-2-images/05.Axe-06.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1056#4](https://judge.softuni.org/Contests/Practice/Index/1056#4).

View File

@@ -0,0 +1,273 @@
# Chapter 7.2. More Complex Loops Exam Problems
We **already learned** how to execute **a block of commands more than once** using a **`for`** loop. In the previous chapter, **we reviewed some loop structures** that would help us solve more complex problems like:
- **loops with a step**
- **nested** loops
- **`while`** loops
- **`do-while`** loops
- **infinite** loops and breaking out of the loop (**`break`** operator)
- **`try-except`** construction
## Exam Problems
Let's start work on solving the following practical exam problems.
## Problem: Stupid Password Generator
Write a program that enters two integers **n** and **l** and generates in alphabetical order all possible **"dumb” passwords"**, that consist of the following **5 characters**:
- Character 1: digit from **1** to **n**.
- Character 2: digit from **1** to **n**.
- Character 3: small letter among the first **l** letters of the Latin alphabet.
- Character 4: small letter among the first **l** letters of the Latin alphabet.
- Character 5: digit from **1** to **n, bigger than first 2 digits**.
### Input Data
The input is read from the console and consists of **two integers: n** and **l** within the range [**1 … 9**], one per line.
### Output Data
Print on the console **all "dumb" passwords in alphabetical order**, separated by **space**.
### Sample Input and Output
|Input|Output|Input|Output|
|---|---|---|---|
|2<br>4|11aa2 11ab2 11ac2 11ad2 11ba2 11bb2 11bc2 11bd2 11ca2 11cb2 11cc2 11cd2 11da2 11db2 11dc2 11dd2|3<br>1|11aa2 11aa3 12aa3 21aa3 22aa3|
|Input|Output|Input|Output|
|---|---|---|---|
|3<br>2|11aa2 11aa3 11ab2 11ab3 11ba2 11ba3 11bb2 11bb3 12aa3 12ab3 12ba3 12bb3 21aa3 21ab3 21ba3 21bb3 22aa3 22ab3 22ba3 22bb3|4<br>2|11aa2 11aa3 11aa4 11ab2 11ab3 11ab4 11ba2 11ba3 11ba4 11bb2 11bb3 11bb4 12aa3 12aa4 12ab3 12ab4 12ba3 12ba4 12bb3 12bb4 13aa4 13ab4 13ba4 13bb4 21aa3 21aa4 21ab3 21ab4 21ba3 21ba4 21bb3 21bb4 22aa3 22aa4 22ab3 22ab4 22ba3 22ba4 22bb3 22bb4 23aa4 23ab4 23ba4 23bb4 31aa4 31ab4 31ba4 31bb4 32aa4 32ab4 32ba4 32bb4 33aa4 33ab4 33ba4 33bb4|
### Hints and Guidelines
We can split the solution of the problem into 3 parts:
* **Reading the input** in the current problem, this includes reading two numbers **`n`** and **`l`**, each on a separate line.
* **Processing The Input Data** using nested loops to iterate through every possible symbol for each of the five password symbols.
* **Printing the output** printing every "dumb" password that meets the requirements.
#### Reading and Processing The Input Data
For **reading** of **input** data, we will declare two integer variables **`int`**: **`n`** and **`l`**.
![](/assets/chapter-7-2-images/01.stupid-password-generator-1.png)
#### Printing Output
One of the ways to find a solution for this problem is to create **five** **`for`** nested loops, one for each variable. To ensure that the last digit is **greater** than the first two, we will use the built-in method **`max(…)`**:
![](/assets/chapter-7-2-images/01.stupid-password-generator-2.png)
**Do you know that…?**
* For convenience we can use the ASCII value of the symbol **"a"** directly in the declarations of the loops - **`97`**:
![](/assets/chapter-7-2-images/01.stupid-password-generator-3.png)
* If we are not sure about a given value of a symbol or we want to take the values of dynamically generated symbols, we can use the built-in function **`ord(char)`**, which returns the integer representation of the character:
![](/assets/chapter-7-2-images/01.stupid-password-generator-4.png)
* Or the opposite, we can generate a character from a given integer, using a built-in function in Python **`chr(number)`**:
![](/assets/chapter-7-2-images/01.stupid-password-generator-5.png)
* **Python** has a wide range of built-in functions and methods for working with strings. Look for more information on the following functions: **`str(number)`**, **`.lower()`**, **`.format(*args, **kwargs)`**, **`.swapcase()`**, **`.upper()`**.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1058#0](https://judge.softuni.org/Contests/Practice/Index/1058#0).
## Problem: Magic Numbers
Write a program that enters a single integer **magic** number and produces all possible **6-digit numbers** for which **the product of their digits is equal to the magical number**.
Example: "Magic number" &rarr; 2
- 111112 &rarr; 1 \* 1 \* 1 \* 1 \* 1 \* 2 = 2
- 111121 &rarr; 1 \* 1 \* 1 \* 1 \* 2 \* 1 = 2
- 111211 &rarr; 1 \* 1 \* 1 \* 2 \* 1 \* 1 = 2
- 112111 &rarr; 1 \* 1 \* 2 \* 1 \* 1 \* 1 = 2
- 121111 &rarr; 1 \* 2 \* 1 \* 1 \* 1 \* 1 = 2
- 211111 &rarr; 2 \* 1 \* 1 \* 1 \* 1 \* 1 = 2
### Input Data
The input is from the console and consists of **one integer** within the range [**1 … 600 000**].
### Output Data
Print on the console **all magic numbers**, separated by **space**.
### Sample Input and Output
|Input|Output|Input|Output|Input|Output|
|---|---|---|---|---|---|
|2|111112 111121 111211 112111 121111 211111|8|111118 111124 111142 111181 111214 111222 111241 111412 111421 111811 112114 112122 112141 112212 112221 112411 114112 114121 114211 118111 121114 121122 121141 121212 121221 121411 122112 122121 122211 124111 141112 141121 141211 142111 181111 211114 211122 211141 211212 211221 211411 212112 212121 212211 214111 221112 221121 221211 222111 241111 411112 411121 411211 412111 421111 811111|531441|999999|
### Hints and Guidelines
**The solution** of this problem follows the **same** conception (we have to generate all n combinations of the element). Follow the steps and try to solve the problem on your own:
- Declare and initialize an integer type **variable** **`int`** and read the **input** from the console.
- Nest **six `for` loops** one for each digit.
- In the last loop, using an **`if`** statement checks if the **product** of the six digits is **equal** to the **magic** number.
Here is an example implementation of the idea:
![](/assets/chapter-7-2-images/02.magic-numbers-1.png)
In the previous chapter, we reviewed other loop constructions. Let's look at the sample solution of the same problem using the **`while`** loop. First, we need to store the **input magical number** in a suitable variable:
![](/assets/chapter-7-2-images/02.magic-numbers-2.png)
Then we will start writing **`while`** loops.
- We will initialize the **first digit**: **`a = 1`**.
- We will set a **condition for each** loop: the digit will be less than or equal to 9.
- At the **beginning** of each loop, we set a value of the **next** digit, in this case: **`b = 1`**. In the nested **`for`** loops, we initialize the variables in the inner loops at each increment of the outer ones. We want to do the same here.
- At **the end** of each loop, we will **increase** the digit by one: **`a += 1`**, **`b += 1`**, **`c += 1`** etc.
- In the **innermost** loop, we will make **the check** and if necessary, we will print on the console.
![](/assets/chapter-7-2-images/02.magic-numbers-3.png)
As we can see, we can solve a problem using different types of loops. Of course, each task has its most appropriate choice. To practice each type of loop try to solve each of the following problems with all the learned loops.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1058#1](https://judge.softuni.org/Contests/Practice/Index/1058#1).
## Problem: Stop Number
Write a program that prints on the console all numbers from **N** to **M**, that are **divisible by 2** and **3 without remainder**, in **reversed order**. We will read **one more** "stop" number from the console **S**. If any of the numbers divisible by 2 and 3 **is equal to the stop number, it should not be printed** and the program should end. **Otherwise print all numbers up to N**, that meet the condition.
### Input Data
Read from the console 3 numbers, each on a single line:
* **N** - integer number: **0 &le; N &lt; M**.
* **M** - integer number: **N &lt; M &le; 10000**.
* **S** - integer number: **N &le; S &le; M**.
### Output Data
Print on the console on a single line all numbers, that meet the condition, separated by space.
### Sample Input and Output
|Input|Output|Comments|
|---|---|---|
|1<br>30<br>15|30 24 18 12 6|Numbers from 30 to 1, that are divisible at the same time by 2 and 3 without remainder are: 30, 24, 18, 12, and 6. The number 15 **is not equal** to any, so the sequence **continues**.|
|Input|Output|Comments|
|---|---|---|
|1<br>36<br>12|36 30 24 18|Numbers from 36 to 1, that are divisible at the same time by 2 and 3 without remainder are: 36, 30, 24, 18, 12, and 6. The number 12 **is equal** to the stop number, so **we stop by 18**.|
|Input|Output|
|---|---|
|20<br>1000<br>36|996 990 984 978 972 966 960 954 948 942 936 930 924 918 912 906 900 894 888 882 876 870 864 858 852 846 840 834 828 822 816 810 804 798 792 786 780 774 768 762 756 750 744 738 732 726 720 714 708 702 696 690 684 678 672 666 660 654 648 642 636 630 624 618 612 606 600 594 588 582 576 570 564 558 552 546 540 534 528 522 516 510 504 498 492 486 480 474 468 462 456 450 444 438 432 426 420 414 408 402 396 390 384 378 372 366 360 354 348 342 336 330 324 318 312 306 300 294 288 282 276 270 264 258 252 246 240 234 228 222 216 210 204 198 192 186 180 174 168 162 156 150 144 138 132 126 120 114 108 102 96 90 84 78 72 66 60 54 48 42|
### Hints and Guidelines
The problem can be divided into **four** logical parts:
* **Reading** the input from the console.
* **Checking** all numbers in the given range, and then running a **loop**.
* **Checking** the conditions of the problem according to every number in the given range.
* **Printing** the numbers.
The **first** part is ordinary - we read **three** integer numbers from the console
We have already seen examples of the **second** part initialization of the **`for`** loop. It is a bit **tricky** - the explanation mentions that the numbers have to be printed in **reversed order**. This means that the **initial** value of the variable **`i`** will be **bigger**, and from the examples, we can see that it is **M**. Thus, the **final** value of **`i`** should be **N**. The fact that we will print the results in reversed order and the values of **`i`** suggest that the step would be **decreased by 1**:
![](/assets/chapter-7-2-images/03.stop-number-1.png)
After we have initialized the **`for`** loop, it is time for the **third** part of the problem - **checking** the condition if the given **number is divisible both by 2 and 3 without remainder**. We will do this using one simple **`if`** condition that we will leave to the reader to do by themselves.
Another **tricky** part of this problem is that apart from the above check we need to do **another** one whether the **number is equal to the "stop" number**, entered from the console on the third line. To do this check, the previous one has to be passed. For this reason, we will add another **`if`** statement that we will **nest in the previous one**. If the condition is **true**, we need to stop the program from printing. We can do this using a **`break`**, operator, and it will lead us **out** of the **`for`** loop.
If the **condition** that checks whether the number is equal with the "stop" number returns a **`false`**, result, our program should **continue to print**. This covers the **fourth and last** part of our program.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1058#2](https://judge.softuni.org/Contests/Practice/Index/1058#2).
## Problem: Special Numbers
Write a program that **reads one integer number N** and generates all possible **"special numbers** from **1111** to **9999**. To be considered **"special"** a number must correspond to the **following condition**:
- **N to be divisible by each of its digits without remainder**.
**Example:** upon **N = 16, 2418** is a special number:
- 16 / 2 = 8 **without remainder**
- 16 / 4 = 4 **without remainder**
- 16 / 1 = 16 **without remainder**
- 16 / 8 = 2 **without remainder**
### Input Data
The input is read from the program and consists of **one integer** within the range **[1 … 600 000]**.
### Output Data
Print on the console **all special numbers**, separated by **space**.
### Sample Input and Output
|Input|Output|Comments|
|---|---|---|
|3|1111 1113 1131 1133 1311 1313 1331 1333 3111 3113 3131 3133 3311 3313 3331 3333|3 / 1 = 3 without remainder<br>3 / 3 = 1 without remainder<br>3 / 3 = 1 without remainder<br>3 / 3 = 1 without remainder|
|Input|Output|Input|Output|
|---|---|---|---|
|11|1111|16|1111 1112 1114 1118 1121 1122 1124 1128 1141 1142 1144 1148 1181 1182 1184 1188 1211 1212 1214 1218 1221 1222 1224 1228 1241 1242 1244 1248 1281 1282 1284 1288 1411 1412 1414 1418 1421 1422 1424 1428 1441 1442 1444 1448 1481 1482 1484 1488 1811 1812 1814 1818 1821 1822 1824 1828 1841 1842 1844 1848 1881 1882 1884 1888 2111 2112 2114 2118 2121 2122 2124 2128 2141 2142 2144 2148 2181 2182 2184 2188 2211 2212 2214 2218 2221 2222 2224 2228 2241 2242 2244 2248 2281 2282 2284 2288 2411 2412 2414 2418 2421 2422 2424 2428 2441 2442 2444 2448 2481 2482 2484 2488 2811 2812 2814 2818 2821 2822 2824 2828 2841 2842 2844 2848 2881 2882 2884 2888 4111 4112 4114 4118 4121 4122 4124 4128 4141 4142 4144 4148 4181 4182 4184 4188 4211 4212 4214 4218 4221 4222 4224 4228 4241 4242 4244 4248 4281 4282 4284 4288 4411 4412 4414 4418 4421 4422 4424 4428 4441 4442 4444 4448 4481 4482 4484 4488 4811 4812 4814 4818 4821 4822 4824 4828 4841 4842 4844 4848 4881 4882 4884 4888 8111 8112 8114 8118 8121 8122 8124 8128 8141 8142 8144 8148 8181 8182 8184 8188 8211 8212 8214 8218 8221 8222 8224 8228 8241 8242 8244 8248 8281 8282 8284 8288 8411 8412 8414 8418 8421 8422 8424 8428 8441 8442 8444 8448 8481 8482 8484 8488 8811 8812 8814 8818 8821 8822 8824 8828 8841 8842 8844 8848 8881 8882 8884 8888|
### Hints and Guidelines
Solve the problem by yourself using what you learned from the previous two problems. Keep in mind the difference between operators for **integer division `//`** and **division with remainder `%`** in Python.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1058#3](https://judge.softuni.org/Contests/Practice/Index/1058#3).
## Problem: Digits
Write a program that reads from the console 1 integer within the range [**100 … 999**], and then prints it a predefined number of times modifying it before each print, as follows:
- If the number is divisible by **5** without remainder, **subtract** from it **its first digit**.
- If the number is divisible by **3** without remainder, **subtract** from it **its second digit**.
- If none of the above-mentioned conditions is valid, **add** to it **its third digit**.
Print on the console **N lines**, and each line has **M numbers**, that are the result of the above actions. Let:
- N = sum of the first and second digits of the number.
- M = sum of the first and third digits of the number.
### Input Data
The input is read from the console and is **an integer** within the range [**100 … 999**].
### Output Data
Print on the console **all integer numbers**, that is the result of the above-mentioned calculations in the respective number of rows and columns as in the examples.
### Sample Input and Output
|Input|Output|Comments|
|---|---|---|
|132|129 126 123<br>120 119 121<br>123 120 119<br>121 123 120|(1 + 3) = 4 and (1 + 2) = 3 &rarr; 4 lines with 3 numbers in each<br>Input number 132 <br>132 &rarr; division by 3 &rarr; 132 - 3 =<br>= 129 &rarr; division by 3 &rarr; 129 - 3 = <br>= 126 &rarr; division by 3 &rarr; 126 - 3 = <br>= 123 &rarr; division by 3 &rarr; 123 - 3 = <br>= 120 &rarr; division by 5 &rarr; 120 - 1 = <br>..... 121 &rarr; neither by 5, nor 3 &rarr; 121 + 2 = 123|
|Input|Output|Comments|
|---|---|---|
|376|382 388 394 400 397 403 409 415 412<br>418 424 430 427 433 439 445 442 448<br>454 460 457 463 469 475 472 478 484<br>490 487 493 499 505 502 508 514 520<br>517 523 529 535 532 538 544 550 547<br>553 559 565 562 568 574 580 577 583<br>589 595 592 598 604 610 607 613 619<br>625 622 628 634 640 637 643 649 655<br>652 658 664 670 667 673 679 685 682<br>688 694 700 697 703 709 715 712 718|10 lines with 9 numbers in each<br>Input number 376 &rarr; neither 5, nor 3 &rarr; 376 + 6 &rarr; =<br>= 382 &rarr; neither 5, nor 3 &rarr; 382 + 6 =<br>= 388 + 6 = 394 + 6 =<br>400 &rarr; division by 5 &rarr; 400 - 3 = 397|
### Hints and Guidelines
Solve the problem **by yourself**, using what you learned from the previous ones. Remember that you will need to define **different** variables for each digit of the input number.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1058#4](https://judge.softuni.org/Contests/Practice/Index/1058#4).

View File

@@ -0,0 +1,394 @@
# Chapter 8.2. Exam Preparation - Part II
In the current chapter, we will review a **practical exam in Programming Basics**, conducted at SoftUni on December 18, 2016. The problems will give you a good overview of what you can expect at an admission exam in Programming at SoftUni. The exam covers the material studied in the current book.
## Exam Problems
Traditionally, the admission exam at SoftUni consists of **6 practical programming problems**:
- Simple problems (no conditions).
- A problem with a single condition.
- A problem with more complex conditions.
- A problem with a single loop.
- A problem with nested loops (drawing a figure on the console).
- A problem with nested loops and more complex logic.
Let's examine a **real exam topic**, the problems it contains, and their solutions.
## Problem: Distance
Write a program that calculates **what is the distance passed by a car (in kilometers)**, if we know **the initial speed** \(km/h\), **the initial time frame** in minutes, then the **speed is increased by 10%**, **the second time frame**, then the **speed is decreased by 5%**, and the **time until the end** of the trip. To calculate the distance, you need to **convert the minutes into hours** \(for example 70 minutes = 1.1666 hours\).
### Input Data
Read **4 lines** from the console:
* **The start speed in km/h** an integer within the range [**1 … 300**].
* **The first time in minutes** an integer within the range [**1 … 1000**].
* **The second time in minutes** an integer within the range [**1 … 1000**].
* **The third time in minutes** an integer within the range [**1 … 1000**].
### Output Data
Print a number on the console: **the kilometers passed**, formatted up to the **second digit after the decimal point**.
### Sample Input and Output
|Input|Output|Comments|
|-----|------|--------|
|90<br>60<br>70<br>80|330.90|**Distance with initial speed**: 90 km/h \* 1 hour (60 min) = **90 km**<br>**After speed increase**: 90 + 10% = 99.00 km/h \* 1.166 hours (70 min) = **115.50 km**<br>**After speed decrease**: 99 - 5% = 94.05 km/h \* 1.33 hours (80 min) = **125.40 km**<br>**Total number of km passed**: **330.9 km**|
|Input|Output|Comments|
|-----|------|--------|
|140<br>112<br>75<br>190|917.12|**Distance with initial speed**: 140 km/h \* 1.86 hours (112 min) = **261.33 km**<br>**After speed increase**: 140 + 10% = 154.00 km/h \* 1.25 hours (75 min) = **192.5 km**<br>**After speed decrease**: 154.00 - 5% = 146.29 km/h \* 3.16 hours (190 min) = **463.28 km**<br>**Total number of km passed**: **917.1166 km**|
### Hints and Guidelines
Such a description may look **misleading** and incomplete at first glance, which **adds** to the **complexity** of a relatively easy task. Let's **separate** the problem into a few **sub-problems** and try to **solve** each of them one by one, which will lead us to the final result:
* **Receiving** the input data.
* **Execution** of the main programming logic.
* **Calculation** and shaping up the final result.
**The main** part of the programming logic is to calculate what will be the **distance passed after all speed changes**. As during **execution** of the program, part of the data that we have is modified, we could **separate** the program code into a few logically separated parts:
* **Calculation** of the **distance** passed with initial speed.
* Change of **speed** and calculation of the **distance** passed.
* Last change of **speed** and **calculation**.
* **Summing up**.
On condition for **input** will be submitted **four** separate rows, for this reason, we will have to call the function **`input()`** four times:
![](/assets/chapter-8-2-images/01.Distance-01.png)
Next, we have to **convert the input data** to a suitable **type** so we can do the needed computations. We choose type **`int`** because in the description of the problem is mentioned that the input data is going to be in a **determined interval**, for which this data type is enough. We perform the data **conversion** as follows:
![](/assets/chapter-8-2-images/01.Distance-02.png)
In this way, we solved successfully the **first sub-problem** - receiving the input data.
We initially **store** one **variable** that will be used multiple times. This centralization approach gives us **flexibility** and the **possibility** to **modify** the final result of the program with minimum effort. In case we need to change the value, we must do it in **only one place in the code**, which saves us time and effort:
![](/assets/chapter-8-2-images/01.Distance-03.png)
<table>
<tr>
<td width=10%><img src="assets/alert-icon.png" style="max-width:50px" /></td>
<td><strong>Avoiding repetitive code</strong> (centralization of the program logic) in the tasks that we examine in the present book may look unnecessary at first glance, but this approach is very important upon building large applications in a real work environment, and its exercising in an initial stage of training will help you build a quality programming style.
</td>
</tr>
</table>
We calculate the **travel time** (in hours) by **dividing the time by 60** (minutes in an hour). The **travel distance** is calculated by **multiplying the starting speed by the time passed** (in hours). After that, we change the speed by increasing it by **10%**(on condition), as per the task description. Calculating the **percentage**, as well as the following **distances** passed, is done in the following way:
* **The time frame** (in hours) is calculated by **dividing** the provided time frame in minutes by the minutes that are contained in an hour (60).
* **The distance passed** is calculated by **multiplying** the time frame (in hours) by the speed that is obtained after the increase.
* The next step is to **decrease the speed** by **5%**, as per the problem description.
* We calculate the **remaining distance** in the manner described in the first two points.
![](/assets/chapter-8-2-images/01.Distance-04.png)
Up until now, we were able to **solve two** of the **most important sub-problems**, namely the **receiving data input** and **their processing**. What remains is to **calculate the final result**. As by the description, we are required to **format it** up to **2** symbols after the decimal point, we can do this in the following **manner**:
![](/assets/chapter-8-2-images/01.Distance-05.png)
In case you worked accurately and wrote the program using the input data given in the task description, you will be convinced that it works properly.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1060#0](https://judge.softuni.org/Contests/Practice/Index/1060#0).
## Problem: Change Tiles
Haralambi has some **savings** that he wants to use to **change the tiles** on the bathroom floor. The **floor is rectangular**, and the **tiles are triangular**. Write a program that **calculates if his savings will be sufficient**. **The width and length of the floor are submitted**, as well as **one of the sides of the triangle with its height towards it**. We must **calculate how many tiles are needed,** to cover the floor. The **number** of tiles **must be rounded up to the higher integer** and **5 more tiles must be added** as spare tiles. Also, **we have submitted** **the price per tile** and **the amount paid for the work** of a workman.
### Input Data
Read **7 lines** from the console:
* **The savings**.
* **The width** of the floor.
* **The length** of the floor.
* **The side** of the triangle.
* **The height** of the triangle.
* **The price** of a tile.
* **The sum** for the workman.
**All** numbers are real numbers within the range [**0.00 … 5000.00**].
### Output Data
In this problem, our currency will be **lv**, which is BGN (Bulgarian lev).
The following must be printed on the console as a **single line**:
* If the money **is sufficient**:
* “{Remaining funds} left.”
* If the money **IS NOT sufficient**:
* “You'll need {Insufficient funds} lv more.”
The result must be **formatted up to the second symbol** after the decimal point.
### Sample Input and Output
|Input|Output|Comments|
|-----|------|--------|
|500<br>3<br>2.5<br>0.5<br>0.7<br>7.80<br>100|25.60 lv left.|**Floor area** &rarr; 3 \* 2.5 = **7.5**<br>**Tile area** &rarr; 0.5 \* 0.7 / 2 = **0.175**<br>**Needed tiles** &rarr; 7.5 / 0.175 = 42.857… = **43 + 5 spare tiles** = **48**<br>**Total amount** &rarr; 48 \* 7.8 + 100 (workman) = **474.4**<br>**474.4 < 500** &rarr; **25.60 lv (BGN) left**|
|Input|Output|Comments|
|-----|------|--------|
|1000<br>5.55<br>8.95<br>0.90<br>0.85<br>13.99<br>321|You'll need 1209.65 lv more.|**Floor area** &rarr; 5.55 \* 8.95 = **49.67249**<br>**Tile area** &rarr; 0.9 \* 0.85 / 2 = **0.3825**<br>**Needed tiles** &rarr; 49.67249 / 0.3825 = 129.86… = **130 + 5 spare tiles** = **135**<br>**Total amount** &rarr; 135 \* 13.99 + 321 (workman) = **2209.65**<br>**2209.65 > 1000** &rarr; **1209.65 lv (BGN) are insufficient**|
### Hints and Guidelines
The following task requires our problem to accept more input data and to perform a larger amount of calculations, even though the solution is **identical**. Accepting the input data is done **familiarly**. Pay attention that in the **input** part of the description is said that all input data will be **real numbers** and for this reason, we will use **`float`** type.
Now that we already have everything for executing the programming logic, we can move to the following part. How can we **calculate** what is the **needed** number of tiles that will be sufficient to cover the entire floor? The requirement is that tiles have a **triangular** shape, which can confuse, but practically, the task needs just **simple calculations**. We can calculate the **common part of the floor** by the formula for finding a rectangle area, as well as the **area of a single tile** using the relevant formula for the triangle area.
To calculate the **number of tiles** that are needed, **we divide the floor area by the area of a single tile** (we should not forget to add the 5 additional tiles, that were mentioned in the requirements).
<table>
<tr>
<td width="10%"><img src="assets/alert-icon.png" style="max-width:50px" /></td>
<td>Pay attention that the requirements state that we should round up the number of tiles, obtained upon the division, up to the higher number, and then we should add 5. Find more information about the system functionality that does that: <code><strong>math.ceil(…)</strong></code>.
</td>
</tr>
</table>
We can find the final result by **calculating the total amount** that is needed to cover the entire floor, by **summing up the tile price and the price that will be paid to the workman**, that we have from the input data. We can figure out that **the total costs** for tiles can be calculated by **multiplying the number of tiles by the price per tile**. We will find out whether the amount that we have will be sufficient by comparing the savings (based on the input data) and the total costs:
![](/assets/chapter-8-2-images/02.Change-Tiles-01.png)
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1060#1](https://judge.softuni.org/Contests/Practice/Index/1060#1).
## Problem: Flowers
A flowers shop offers 3 types of flowers: **chrysanthemums**, **roses**, and **tulips**. The prices depend on the season. In this problem, our currency will be **lv**, which is BGN (Bulgarian lev).
|Season|Chrysanthemums|Roses|Tulips|
|:---:|:---:|:---:|:---:|
|spring / summer<br>autumn / winter|2.00 lv./pc.<br>3.75 lv./pc.|4.10 lv./pc.<br>4.50 lv./pc.|2.50 lv./pc.<br>4.15 lv./pc.|
On holidays, the prices of all flowers are **increased by 15%.** The following **discounts** are offered:
* For purchasing more than 7 tulips in spring **5% of the price** of the whole bouquet.
* For purchasing 10 or more roses in winter **10% of the price** of the whole bouquet.
* For purchasing more than 20 flowers in total in any season **20% of the price** of the whole bouquet.
**Discounts are made in the above-described order and can be combined! All discounts are valid after increasing the price on a holiday!**
The price for arranging a bouquet is always **2 lv** (BGN). Write a program that calculates the **price of a bouquet**.
### Input Data
The input is read from the **console** and contains **exactly 5 arguments**:
* **The number** of the purchased **chrysanthemums** integer number inside the interval of [**0 … 200**].
* **The number** of the purchased **roses** integer number inside the interval of [**0 … 200**].
* **The number** of the purchased **tulips** integer number inside the interval of [**0 … 200**].
* **The season** [**Spring, Summer, Autumn, Winter**].
* **If the day is a holiday** [**Y - yes / N - no**].
### Output Data
Print on the console 1 number **the price of flowers**, formatted up to the second digit after the decimal point.
### Sample Input and Output
|Input|Output|Comments|
|-----|------|--------|
|2<br>4<br>8<br>Spring<br>Y<br>|46.14|**Price**: 2\*2.00 + 4\*4.10 + 8\*2.50 = 40.40 BGN.<br>**Holiday**: 40.40 + 15% = 46.46 BGN.<br>**5% discount** for more than 7 tulips in spring: 44.14<br>The flowers are in total 20 or less: **no discount**<br>44.14 + 2 **for arranging** = 46.14 BGN.|
|Input|Output|Comments|
|-----|------|--------|
|3<br>10<br>9<br>Winter<br>N<br>|69.39|**Price**: 3\*3.75 + 10\*4.50 + 9\*4.15 = 93.60 BGN.<br>**No holiday**: no increase in price<br>**10% discount** for 10 or more roses in winter: 84.24<br>The flowers are in total over 20: **20% discount** = 67.392<br>67.392 + 2 **for arranging** = 69.392 BGN.|
|Input|Output|
|-----|------|
|10<br>10<br>10<br>Autumn<br>N|101.20|
### Hints and Guidelines
After carefully reading the requirements, we understand that once again we need to do **simple calculations**, however, this time we will need **additional** logical **conditions**. We need to pay more **attention** to the moment of **making changes** in the final price, to be able to properly build the logic of our program. Again, the bold text gives us sufficient **guidelines** on how to proceed. For a start, we will separate the already **defined** values in **variables**, as we did in the previous tasks:
![](/assets/chapter-8-2-images/03.Flowers-01.png)
We will also do the same for the rest of the defined values:
![](/assets/chapter-8-2-images/03.Flowers-02.png)
Our next sub-task is to **read** properly **the input** data from the console. We will do that in an already familiar manner but this way **we combine two** separate functions - one to **read** a line from the console and another to **convert** in a numeric data type:
![](/assets/chapter-8-2-images/03.Flowers-03.png)
Let's think of the most appropriate way to **structure** our programming logic. By the requirements, it becomes clear that the path of the program is divided mainly into two parts: **spring / summer** and **autumn / winter**. We can do the separation by a conditional statement, by storing variables in advance for the **prices** of the individual flowers, as well as for the **final result**:
![](/assets/chapter-8-2-images/03.Flowers-04.png)
What remains is to perform **a few checks** regarding **the discounts** of the different types of flowers, depending on the season, and to modify the final result.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1060#2](https://judge.softuni.org/Contests/Practice/Index/1060#2).
## Problem: Grades
Write a program that **calculates statistics for grades** in an exam. In the beginning, the program receives the **number of students** who attended the exam and for **each student their grade**. In the end, the program must **print the percentage of students** that have grades between 2.00 and 2.99, between 3.00 and 3.99, between 4.00 and 4.99, 5.00 or more, as well as the **average grade** of the exam.
### Input Data
On the console are being read a **sequence of numbers, each on a different row**:
* On the first line **the number of students who attended the exam** an integer within the range [**1 … 1000**].
* For **each student** on a separate line **the grade on the exam** a real number within the range [**2.00 … 6.00**].
### Output Data
Print on the console **5 lines** that hold the following information:
* "Top students: {percentage of students with a grade of 5.00 or more}%".
* "Between 4.00 and 4.99: {between 4.00 and 4.99 included}%".
* "Between 3.00 and 3.99: {between 3.00 and 3.99 included}%".
* "Fail: {less than 3.00}%".
* "Average: {average grade}".
The results must be **formatted up to the second symbol** after the decimal point.
### Sample Input and Output
|Input|Output|Comments|
|-----|------|--------|
|10<br>3.00<br>2.99<br>5.68<br>3.01<br>4<br>4<br>6.00<br>4.50<br>2.44<br>5<br>|Top students: 30.00%<br>Between 4.00 and 4.99: 30.00%<br>Between 3.00 and 3.99: 20.00%<br>Fail: 20.00%<br>Average: 4.06|5 or more - **3 students** = 30% of 10<br>Between 4.00 and 4.99 - **3 students** = 30% of 10<br>Between 3.00 and 3.99 - **2 students** = 20% of 10<br>Under 3 - **2 students** = 20% of 10<br>The average grade is: 3 + 2.99 + 5.68 + 3.01 + 4 + 4 + 6 + 4.50 + 2.44 + 5 = 40.62 / 10 = 4.062|
|Input|Output|
|-----|------|
|6<br>2<br>3<br>4<br>5<br>6<br>2.2|Top students: 33.33%<br>Between 4.00 and 4.99: 16.67%<br>Between 3.00 and 3.99: 16.67%<br>Fail: 33.33%<br>Average: 3.70|
### Hints and Guidelines
By requirements, we see that **first**, we will receive **the number** of students, and then, **their grades**. For that reason, **first**, we will obtain **the number** of students, as we will convert the value we have read to **`int`**. To process the grades themselves, we will use a **`for`** loop. Every iteration of the loop will read and process one grade:
![](/assets/chapter-8-2-images/05.Grades-01.png)
Before executing the code of the **`for`** loop, we will create variables where we will store **the number of students** for each group: poor results (up to 2.99), results from 3 to 3.99, from 4 to 4.99, and grades above 5. We will also need one more variable, where we will store **the sum of all grades**, via which we will calculate the average grade of all students:
![](/assets/chapter-8-2-images/05.Grades-02.png)
We run the **loop** and inside it, we **declare one more** variable, in which we will store the **currently** entered grade. The variable will be of the type **`float`** and on every iteration, we check **what is its value**. According to this value, **we increase** the number of students in the relevant group by **1**, as we should not forget to also increase the **total** amount of the grades, which we also track:
![](/assets/chapter-8-2-images/05.Grades-03.png)
We can calculate what **percentage** is taken by a particular **group of students** from the total number by **multiplying the number of students** in the relevant group by **100** and then dividing this by the **total number of students**.
**The final result** is formed in a well-known way **up to the second symbol** after the decimal point.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1060#3](https://judge.softuni.org/Contests/Practice/Index/1060#3).
## Problem: Christmas Hat
Write a program that reads from the console an **integer `n`** and draws a **Christmas hat** with a width of **4 \* `n` + 1 columns** and a height of **2 \* `n` + 5 rows**, as in the examples below.
### Input Data
The input is read from the console - one **integer `n`** within the range [**3 … 100**].
### Output Data
Print on the console a **Christmas hat**, exactly like in the examples.
### Sample Input and Output
|Input|Output|
|:-----:|:-----:|
|4|<code>......./&#124;\\.......</code><br><code>.......\\&#124;/.......</code><br><code>.......\*\*\*.......</code><br><code>......\*-\*-\*......</code><br><code>.....\*--\*--\*.....</code><br><code>....\*---\*---\*....</code><br><code>...\*----\*----\*...</code><br><code>..\*-----\*-----\*..</code><br><code>.\*------\*------\*.</code><br><code>\*-------\*-------\*</code></br><code>\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*</code><br><code>\*.\*.\*.\*.\*.\*.\*.\*.\*</code><br><code>\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*</code>|
|Input|Output|
|:-----:|:-----:|
|7|<code>............./&#124;\\.............</code><br><code>.............\\&#124;/.............</code><br><code>.............\*\*\*.............</code><br><code>............\*-\*-\*............</code><br><code>...........\*--\*--\*...........</code><br><code>..........\*---\*---\*..........</code><br><code>.........\*----\*----\*.........</code><br><code>........\*-----\*-----\*........</code><br><code>.......\*------\*------\*.......</code><br><code>......\*-------\*-------\*......</code><br><code>.....\*--------\*--------\*.....</code><br><code>....\*---------\*---------\*....</code><br><code>...\*----------\*----------\*...</code><br><code>..\*-----------\*-----------\*..</code><br><code>.\*------------\*------------\*.</code><br><code>\*-------------\*-------------\*</code><br><code>\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*</code><br><code>\*.\*.\*.\*.\*.\*.\*.\*.\*.\*.\*.\*.\*.\*.\*</code><br><code>\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*</code><br>|
### Hints and Guidelines
In tasks requiring **drawing** on the console, most often the user inputs **an integer** that is related to the **total size of the figure** that we need to draw. As the task requirements mention how the total length and width of the figure are calculated, we can use them as **starting points**. In the examples, it is clear that regardless of the input data, we always have the **first two rows** that are almost identical.
<code>......./\|\\.......</code><br><code>.......\\\|/.......</code>
We also notice that the **last three rows** are always present, as **two** of them are completely **the same**.
<code>\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*</code><br><code>\*.\*.\*.\*.\*.\*.\*.\*.\*</code><br><code>\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*</code>
By these observations, we can come up with the **formula** for the **height of the variable part** of the Christmas hat. We use the formula specified in the task to calculate the total height, by subtracting the size of the unchangeable part. We obtain **`(2 * n + 5) 5`** or **`2 * n`**.
To **draw** the **dynamic** or the variable part of the figure, we will use a **loop**. The size of the loop will be from **0** to the **width** that we have by requirements, namely **`4 * n + 1`**. Since we will use this formula in **a few places** in the code, it is a good practice to declare it in a **separate variable**. Before running the loop, we should **declare variables** for the **number** of individual symbols that participate in the dynamic part: **dots** and **dashes**. By analyzing examples, we can also prepare formulas for the **starting values** of these variables. Initially, the **dashes** are **0**, but we can calculate the number of **dots** by subtracting **3** from the **total width** (the number of symbols that are building the top of the Christmas hat) and then **dividing by 2**, as the number of dots on both sides of the hat is the same.
<code>.......\*\*\*.......</code><br><code>......\*-\*-\*......</code><br><code>.....\*--\*--\*.....</code><br><code>....\*---\*---\*....</code><br><code>...\*----\*----\*...</code><br><code>..\*-----\*-----\*..</code><br><code>.\*------\*------\*.</code><br><code>\*-------\*-------\*</code>
What remains is to execute the body of the loop, as **after each** drawing we **decrease** the number of dots by **1** and **increase the number of dashes** by **1**. Let's not forget to draw one **star** between each of them. The sequence of drawing in the body of the loop is the following:
* Symbol string of dots
* Star
* Symbol string of dashes
* Star
* Symbol string of dashes
* Star
* Symbol string of dots
In case we have worked properly, we will obtain figures identical to those in the examples.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1060#4](https://judge.softuni.org/Contests/Practice/Index/1060#4).
## Problem: Letters Combinations
Write a program that prints on the console **all combinations of 3 letters** within a specified range, by skipping the combinations **containing a certain letter**. Finally, print the number of printed combinations.
### Input Data
The input is read from the console and contains **exactly 3 lines**:
* A small letter from the English alphabet between **'a'** and **'z'**.
* A small letter from the English alphabet between the **first letter** and **'z'**.
* A small letter from the English alphabet from **'a'** to **'z'** as the combinations containing this letter are skipped.
### Output Data
Print on one line **all combinations** corresponding to the requirements, followed by **their number**, separated by a space.
### Sample Input and Output
|Input|Output|Comments|
|---|---|---|
|a<br>c<br>b|aaa aac aca acc caa cac cca ccc 8|All possible combinations with letters '**a**', '**b**' and '**c**' are:<br>aaa aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc caa cab cac cba cbb cbc cca ccb ccc<br>The combinations **containing 'b' are not valid**.<br>**8** valid combinations remain.|
|Input|Output|
|---|---|
|f<br>k<br>h|fff ffg ffi ffj ffk fgf fgg fgi fgj fgk fif fig fii fij fik fjf fjg fji fjj fjk fkf fkg fki fkj fkk gff gfg gfi gfj gfk ggf ggg ggi ggj ggk gif gig gii gij gik gjf gjg gji gjj gjk gkf gkg gki gkj gkk iff ifg ifi ifj ifk igf igg igi igj igk iif iig iii iij iik ijf ijg iji ijj ijk ikf ikg iki ikj ikk jff jfg jfi jfj jfk jgf jgg jgi jgj jgk jif jig jii jij jik jjf jjg jji jjj jjk jkf jkg jki jkj jkk kff kfg kfi kfj kfk kgf kgg kgi kgj kgk kif kig kii kij kik kjf kjg kji kjj kjk kkf kkg kki kkj kkk 125|
|Input|Output|
|---|---|
|a<br>c<br>z|aaa aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc caa cab cac cba cbb cbc cca ccb ccc 27|
### Hints and Guidelines
By requirements, we have input data on **3 rows**, each of which is represented by one character of the **ASCII table** ([https://www.asciitable.com/](https://www.asciitable.com/)). We could use the already defined function in Python, **`ord(…)`** through which we will receive the ASCII code of the symbol:
![](/assets/chapter-8-2-images/06.Letters-01.png)
Let's think of how we can achieve the **final result**. In case the task requirement is to print all characters, from the starting to the end one (by skipping a particular letter), what should we do?
The easiest and most efficient way is to use a **loop**, by passing through **all characters** and printing those that are **different** from the **letter** that we need to skip. In Python, we can go around all the symbols from 'a' to 'z' the following way:
![](/assets/chapter-8-2-images/06.Letters-02.png)
The function **`chr(…)`** will convert the received ASCII code into a symbol. The result of running the code is all letters from **a** to **z** included, printed on a single line and separated by spaces. Does this look like the final result of our task? We must find a **way** to print **3 characters**, as required, instead of **1**. Running such a program very much looks like a slot machine. We often win in slots, if we arrange a few identical characters in a row. Let's say that the machine has space for three characters. When we **stop** on a particular **character** in the first place, the other two places will **continue** rolling characters among all possible ones. In our case, **all possible characters** are the letters from the starting to the end one, entered by the user, and the solution of our program is identical to the way a slot machine works.
We use a **loop** that runs through **all characters** from the starting to the end letter (included). On **each iteration** of the **first** loop, we run a **second** one with the same parameters (but **only if** the letter of the first loop is valid, i.e. does not match the one that we must exclude, by requirements). In each iteration of the **second** loop, we run **one** more with the **same parameters** and the same **condition**. This way we have three nested loops and in the body of **the latter** we will add the symbols to the final result:
![](/assets/chapter-8-2-images/06.Letters-03.png)
Let's not forget that we also need to print the **total number of valid combinations** that we have found, and they must be printed on the **same line**, separated by a space. We leave this sub-task to the reader.
### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1060#5](https://judge.softuni.org/Contests/Practice/Index/1060#5).

View File

@@ -0,0 +1,667 @@
# Chapter 8.1. Practical Exam Preparation - Part I
In **the present chapter**, we will examine a few **problems** with a level of **difficulty** that can be expected in **the problems** of the practical **exam** in “Programming Basics”. We will **review** and **practice** all the knowledge that was gained from this book and through the "Programming Basics" course.
## The "Programming Basics" Practical Exam
The **Practical Exam** contains **6** problems included, and you will have **4 hours** to solve them. **Each** of the exam problems will **cover** one of the studied **topics** during the course. Problem topics are as follows:
- Problem with simple calculations (without conditions)
- Problem with simple condition
- Problem with more complex conditions
- Problem with a simple loop
- Problem with nested loops (drawing a figure on the console)
- Problem with nested loops and more complex logic
## The Online Evaluation System (Judge)
**All exams and problems** are automatically **tested** through the online **Judge system**: [https://judge.softuni.org](https://judge.softuni.org). For **each** of the problems, there are **visible** (zero points) tests that help you understand what is expected of the problem and fix your mistakes, as well as **competition** tests that are **hidden** and check if your solution is working properly.
**How** does the testing in the **Judge** system work? **You upload** the source code and from the menu below you choose to compile as a **Python** program. The program is being **tested** with a series of tests, giving **points** for each **successful** test.
## Problems with Simple Calculations
**The first** problem of the "Programming Basics" Practical Exam covers **simple calculations without checks and loops**. Here are a few examples:
### Problem: Triangle Area
<table>
<tr>
<td width="60%">
<b>Triangle in the plain</b> is defined by the coordinates of its three vertices. First, <b>the vertex (x1, y1)</b> is set. Then the other two vertices are set: <b>(x2, y2)</b> and <b>(x3, y3)</b> which <b>lie on a common horizontal line</b> i.e. they have the same Y coordinates). Write a program that calculates <b>the triangle area</b> by the coordinates of its three vertices.
</td>
<td>
<img src="assets/chapter-8-1-images/01.Triangle-area-01.png"/>
</td>
</tr>
</table>
#### Input Data
From the console **6 integers** are read (one per line):
**x1, y1, x2, y2, x3, y3.**
- All input numbers are in the range [**-1000 … 1000**].
- It's guaranteed that **y2 = y3**.
#### Output Data
Print on the console **the triangle area**.
#### Sample Input and Output
|Input|Output|Visualization|Comments|
|-----|------|-------------|--------|
|5<br>-2<br>6<br>1<br>1<br>1|7.5|![](/assets/chapter-8-1-images/01.Triangle-area-01.png)|The side of the triangle **a** = 6 - 1 = **5**<br>The height of the triangle **h** = 1 - (-2) = **3**<br>The area of the triangle **S** = a \* h / 2 = 5 \* 3 / 2 = **7.5**|
|Input|Output|Visualization|Comments|
|-----|------|-------------|--------|
|4<br>1<br>-1<br>-3<br>3<br>-3|8|![](/assets/chapter-8-1-images/01.Triangle-area-02.png)|The side of the triangle **a** = 3 - (-1) = **4**<br>The height of the triangle **h** = 1 - (-3) = **4**<br>The area of the triangle **S** = a \* h / 2 = 4 \* 4 / 2 = **8**|
#### Hints and Guidelines
It is extremely important in these types of tasks, in which some coordinates are given, to pay attention to the **order** in which they are submitted, as well as to correctly understand which of the coordinates we will use and in what way. In this case, the input is in order **x1, y1, x2, y2, x3, y3**. If we do not follow this sequence, the solution becomes wrong. First, we write the code that reads the input data:
![](/assets/chapter-8-1-images/01.Triangle-area-03.png)
We have to calculate **the side** and **the height** of the triangle. From the examples and the condition **`y2 = y3`** we notice that one **side** is always parallel to the horizontal axis. It means that its **length** is equal to the length of the segment between its coordinates **`x2` and `x3`**, which is equal to the difference between the larger and the smaller coordinates. Similarly, we can calculate **the height**. It will always be equal to the difference between **`y1` and `y2`**(or **`y3`**, as they are equal). Since we do not know if **`x2`** is greater than **`x3`**, or **`y1`** will be below or above the triangle side, we will use **the absolute values** of the difference to always get positive numbers because one segment cannot have a negative length.
![](/assets/chapter-8-1-images/01.Triangle-area-04.png)
We will use the formula familiar to us from school for finding the **area of a triangle** to calculate the area.
![](/assets/chapter-8-1-images/01.Triangle-area-05.png)
The only thing left is to print the area on the console.
![](/assets/chapter-8-1-images/01.Triangle-area-06.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1059#0](https://judge.softuni.org/Contests/Practice/Index/1059#0).
### Problem: Bricks
Construction workers have to transfer a total of **x bricks**. **The workers** are **w** and work simultaneously. They transport the bricks in trolleys, each with a **capacity of m** bricks. Write a program that reads the integers **x**, **w**, and **m**, and calculates **what is the minimum number of courses** the workers need to do to transport the bricks.
#### Input Data
From the console **3 integers** are read (one per line):
- **The number of bricks x** is read from the first line.
- **The number of workers w** is read from the second line.
- **The capacity of the trolley m** is read from the third line.
All input numbers are integers in the range [**1 … 1000**].
#### Output Data
Print on the console **the minimum number of courses** needed to transport the bricks.
#### Sample Input and Output
|Input|Output|Comments|
|-----|------|--------|
|120<br>2<br>30|2|We have **2** workers, each transporting **30** bricks per course. In total, workers are transporting **60** bricks per course. To transport **120** bricks, exactly **2** courses are needed.|
|Input|Output|Comments|
|-----|------|--------|
|355<br>3<br>10|12|We have **3** workers, each transporting **10** bricks per course. In total, workers are transporting **30** bricks per course. To transport **355** bricks, exactly **12** courses are needed: **11** complete courses carry **330** bricks and the last **12th** course carries the last **25** bricks.|
|Input|Output|Comments|
|-----|------|--------|
|5<br>12<br>30|1|We have **5** workers, each transporting **30** bricks per course. In total, workers are transporting **150** bricks per course. To transport **5** bricks, only **1** course is enough (although incomplete, with only 5 bricks).|
#### Hints and Guidelines
The input is standard, and we only have to pay attention to the sequence in which we read the data:
![](/assets/chapter-8-1-images/02.Bricks-01.png)
We calculate how many **bricks** the workers transport in a single course:
![](/assets/chapter-8-1-images/02.Bricks-02.png)
By dividing the total number of **bricks transported for 1 course**, we will obtain the number of **courses** needed to carry them. We will use the **`math.ceil (…)`** function to round the result up. **Remember** to add **`import math`** at the beginning of the working file so that the **`math.ceil (…)`** function can work. When the bricks can be transferred with **an exact number of courses**, the division will return a whole number and there will be nothing to round. Accordingly, if not, the result of the division will be **the number of exact courses** but with a decimal fraction. The decimal part will be rounded up and we will get the required **1 course** for the remaining bricks.
![](/assets/chapter-8-1-images/02.Bricks-03.png)
In the end, we print the result on the console:
![](/assets/chapter-8-1-images/02.Bricks-04.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1059#1](https://judge.softuni.org/Contests/Practice/Index/1059#1).
## Problems with Simple Conditions
**The second** problem of the "Programming Basics" Practical Exam covers **conditional statements and simple calculations**. Here are a few examples:
### Problem: Point on Segment
On a horizontal line, **a horizontal segment** is placed, set with the **x** coordinates at both ends: **first** and **second**. **A point** is located **on** the same horizontal line and is set with its **x coordinate**. Write a program that checks whether the point is **inside or outside of the segment** and calculates **the distance to the nearest end** of the segment.
#### Input Data
From the console **3 integers** are read (one per line):
- On the first line is the number first - **one end of the segment**.
- On the second line is the number second - **the other end of the segment**.
- On the third line is the number point - **the location of the point**.
All inputs are integers in the range [**-1000 … 1000**].
#### Output Data
Print the result on the console:
- On the first line, print "**in**" or "**out**" whether the point is inside or outside the segment.
- On the second line, print the distance from the point to the nearest end of the segment.
#### Sample Input and Output
|Input|Output|Visualization|
|-----|------|-------------|
|10<br>5<br>7|in<br>2|![](/assets/chapter-8-1-images/03.Point-on-segment-01.png)|
|Input|Output|Visualization|
|-----|------|-------------|
|8<br>10<br>5|out<br>3|![](/assets/chapter-8-1-images/03.Point-on-segment-02.png)|
|Input|Output|Visualization|
|-----|------|-------------|
|1<br>-2<br>3|out<br>2|![](/assets/chapter-8-1-images/03.Point-on-segment-03.png)|
#### Hints and Guidelines
First, we read the input:
![](/assets/chapter-8-1-images/03.Point-on-segment-04.png)
Since we do not know which **point** is on the left and which is on the right, we will create two variables to mark this. Since **the left point** is always the one with the smaller **x coordinate**, we will use the **`min(…)`** function to find it. Accordingly, **the right point** is always the one with a larger **x coordinate** and we will use the **`max(…)`** function. We will also find the distance from **the point x** to **the two points**. Since we do not know their position relative to each other, we will use the **`abs(…)`** function to get a positive result:
![](/assets/chapter-8-1-images/03.Point-on-segment-05.png)
The shorter of the two **distances** we will find by using **`min(…)`**:
![](/assets/chapter-8-1-images/03.Point-on-segment-06.png)
What remains is to find whether **the point** is on or out of the line. The point will be **on the line** always when it **matches** one of the other two points or its x coordinate lies **between them**. Otherwise, the point is **outside the line**. After checking, we display one of the two messages ("**in**" or "**out**"), depending on which condition is satisfied:
![](/assets/chapter-8-1-images/03.Point-on-segment-07.png)
Finally, we print **the distance** found before.
![](/assets/chapter-8-1-images/03.Point-on-segment-08.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1059#2](https://judge.softuni.org/Contests/Practice/Index/1059#2).
### Problem: Point in Figure
Write a program that checks if a point (with coordinates **x** and **y**) is **inside** or **outside** of the given figure:
![](/assets/chapter-8-1-images/04.Point-in-figure-01.png)
#### Input Data
From the console are read **two integers** (one per line): **x** and **y**.
All inputs are integers in the range **[-1000 … 1000]**.
#### Output Data
Print on the console "**in**" or "**out**" whether the point is **inside** or **outside** the figure (the outline is inside).
#### Sample Input and Output
|Input|Output|Input|Output|
|----|----|----|----|
|8<br>-5|in|6<br>-3|in|
|Input|Output|Input|Output|
|----|----|----|----|
|11<br>-5|out|11<br>2|out|
#### Hints and Guidelines
To find out if **the point** is inside of the figure, we will divide **the figure** into 2 rectangles:
![](/assets/chapter-8-1-images/04.Point-in-figure-02.png)
![](/assets/chapter-8-1-images/04.Point-in-figure-03.png)
A sufficient condition is the **point** to be located in one of them and be in the **figure**.
We read the input from the console:
![](/assets/chapter-8-1-images/04.Point-in-figure-04.png)
We will initialize two variables that will mark whether **the point** is in one of the rectangles:
![](/assets/chapter-8-1-images/04.Point-in-figure-05.png)
When printing the message, we will check whether any of the variables has accepted a value of **`True`**. It's enough **only one** of them to be **`True`** so that the point is in the figure.
![](/assets/chapter-8-1-images/04.Point-in-figure-06.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1059#3](https://judge.softuni.org/Contests/Practice/Index/1059#3).
## Problems with Complex Conditions
**The third** problem of the "Programming Basics" Practical Exam includes **several nested checks combined with simple calculations**. Here are a few examples:
### Problem: Date After 5 days
There are two numbers **d** (day) and **m** (month) that form **a date**. Write a program that prints the date that will be **after 5 days**. For example, 5 days after **28.03** is the date **2.04**. We assume that the months: April, June, September, and November have 30 days, February has 28 days, and the rest have 31 days. Months to be printed with **leading zero** when they are single-digit numbers (e.g. 01, 08).
#### Input Data
The input is read from the console and consists of two lines:
- On the first line, there is an integer **d** in the interval [**1… 31**] - day. The number of the day does not exceed the number of days in the respective month (e.g. 28 for February).
- On the second line, there is an integer **m** in the interval [**1… 12**] - month. Month 1 is January, month 2 is February,…, month 12 is December. The month may contain a leading zero (e.g. April may be written as 4 or 04).
#### Output Data
Print a single line containing the date after 5 days in the format **day.month** on the console. The month must be a two-digit number with a leading zero, if necessary. The day must be written without a leading zero.
#### Sample Input and Output
|Input|Output|Input|Output|
|-----|------|-----|------|
|28<br>03|2.04|27<br>12|1.01|
|Input|Output|Input|Output|
|-----|------|-----|------|
|25<br>1|30.01|26<br>02|3.03|
#### Hints and Guidelines
We read the input data from the console:
![](/assets/chapter-8-1-images/05.Date-after-5-days-01.png)
To make our checks easier, we will create a variable that will contain the **number of days** that we have in the month we set:
![](/assets/chapter-8-1-images/05.Date-after-5-days-02.png)
We increase the **day** by 5:
![](/assets/chapter-8-1-images/05.Date-after-5-days-03.png)
We check if **the day** has exceeded the number of days in **the month**. If so, we must deduct the days of the month from the obtained day to calculate which day of the next month our day corresponds to:
![](/assets/chapter-8-1-images/05.Date-after-5-days-04.png)
After we have passed to **the next month**, this should be noted by increasing the initial one by 1. We need to check if it has become greater than 12 and if it has, to adjust it. Because we cannot skip more than **one month** when we increase by 5 days, the following check is enough:
![](/assets/chapter-8-1-images/05.Date-after-5-days-05.png)
The only thing that remains is to print the result on the console. It is important to **format the output** correctly to display the leading zero in the first 9 months. This is done by adding a **formatted string** **`%02d`** for the second element:
![](/assets/chapter-8-1-images/05.Date-after-5-days-06.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1059#4](https://judge.softuni.org/Contests/Practice/Index/1059#4).
### Problem: Sums 3 Numbers
There are **3 integers** given. Write a program that checks if **the sum of two of the numbers is equal to the third one**. For example, if the numbers are **3**, **5**, and **2**, the sum of two of the numbers is equal to the third one: **2 + 3 = 5**.
#### Input Data
From the console are read **three integers**, one per line. The numbers are in the range [**1 … 1000**].
#### Output Data
- Print a single line on the console containing the solution of the problem in the format "**a + b = c**", where **a**, **b** and **c** are among the three input numbers and **a ≤ b**.
- If the problem has no solution, print “**No**” on the console.
#### Sample Input and Output
|Input|Output|Input|Output|
|-----|------|-----|------|
|3<br>5<br>2|2 + 3 = 5|2<br>2<br>4|2 + 2 = 4|
|Input|Output|Input|Output|
|-----|------|-----|------|
|1<br>1<br>5|No|2<br>6<br>3|No|
#### Hints and Guidelines
We take the input from the console:
![](/assets/chapter-8-1-images/06.Sums-3-numbers-01.png)
We have to check if **the sum** of a pair of numbers is equal to the third number. We have three possible cases:
* a + b = c
* a + c = b
* b + c = a
We will write **a template**, which will later be complemented by the required code. If none of the above three conditions is met, we will make our program print "**No**":
![](/assets/chapter-8-1-images/06.Sums-3-numbers-02.png)
Now it remains to understand the order in which **the two addends** will be displayed at the output of the program. For this purpose, we will make a **nested condition**, which checks which of the two numbers is the greater. In the first case, it will be as follows:
![](/assets/chapter-8-1-images/06.Sums-3-numbers-03.png)
Similarly, we will supplement the other two cases. The full code of the program will look like this:
![](/assets/chapter-8-1-images/06.Sums-3-numbers-04.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1059#5](https://judge.softuni.org/Contests/Practice/Index/1059#5).
## Problems with Simple Loops
**The fourth** problem of the "Programming Basics" Practical Exam includes a **simple loop with simple logic** in it. Here are a few examples:
### Problem: Sums Step 3
There are given **n** integers **a1, a2, …, an**. Calculate the sums:
- **sum1 = a1 + a4 + a7** + … (the numbers are summed, starting from the first one with step of 3).
- **sum2 = a2 + a5 + a8** + … (the numbers are summed, starting from the second one with step of 3).
- **sum3 = a3 + a6 + a9** + … (the numbers are summed, starting from the third one with step of 3).
#### Input Data
The input data is read from the console. The first line contains an integer **n (0 ≤ n ≤ 1000)**. The next **n** lines contain **n** integers in the interval [**-1000 … 1000**]: **a1, a2, …, an**.
#### Output Data
On the console, we should print 3 lines containing the 3 sums in a format such as in the example.
#### Sample Input and Output
|Input|Output|Input|Output|Input|Output|
|-----|------|-----|------|-----|------|
|2<br>3<br>5<br>|sum1 = 3<br>sum2 = 5<br>sum3 = 0|4<br>7<br>-2<br>6<br>12|sum1 = 19<br>sum2 = -2<br>sum3 = 6|5<br>3<br>5<br>2<br>7<br>8|sum1 = 10<br>sum2 = 13<br>sum3 = 2|
#### Hints and Guidelines
We will take **the count of numbers** from the console and will declare **starting values** of the three sums.
![](/assets/chapter-8-1-images/07.Sums-Step-3-01.png)
Since we do not know in advance how many numbers we will process, we will take them one at a time in **a loop** which will be repeated **n times** and we will process them in the body of the loop.
![](/assets/chapter-8-1-images/07.Sums-Step-3-02.png)
To find out which of **the three sums** we need to add the number, we will divide its **sequence number into three** and we will use **the remainder**. We'll use the variable **`i`** which tracks **the number of runs** of the loop, to find out which sequence number we are at. When the remainder of **`i/3`** is **zero**, it means we will add this number to **the first** sum, when it's **1** to **the second**, and when it's **2** to **the third**:
![](/assets/chapter-8-1-images/07.Sums-Step-3-03.png)
Finally, we will print the result on the console in the required **format**:
![](/assets/chapter-8-1-images/07.Sums-Step-3-04.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1059#6](https://judge.softuni.org/Contests/Practice/Index/1059#6).
### Problem: Increasing Elements
A series of **n** numbers is given: **a1**, **a2**, **…**, **an**. Calculate **the length of the longest increasing sequence** of consecutive elements in the series of numbers.
#### Input Data
The input data is read from the console. The first line contains an integer **n** (**0 ≤ n ≤ 1000**). The next **n** lines contain **n** integers in the interval [**-1000 … 1000**]: **a1**, **a2**, **…**, **an**.
#### Output Data
Print on the console one number **the length** of the longest increasing sequence.
#### Sample Input and Output
|Input|Output|Input|Output|Input|Output|Input|Output|
|-----|------|-----|------|-----|------|-----|------|
|3<br>5<br>2<br>4|2|4<br>2<br>8<br>7<br>6|2|4<br>1<br>2<br>4<br>4|3|4<br>5<br>6<br>7<br>8|4|
#### Hints and Guidelines
To solve this problem, we need to think in a bit **more algorithmic way**. A **sequence of numbers** is given to us, and we need to check whether each **subsequent** one will be **larger than the previous one** and if so, we count how long is the sequence in which this condition is fulfilled. Then we have to find **which sequence** of these is **the longest one**. To do this, let's create some variables that we will use during solving the problem:
![](/assets/chapter-8-1-images/08.Increasing-numbers-01.png)
The variable **`n`** is **the count of numbers** we get from the console. In **`count_current_longest`** we'll keep **the number of elements** in the increasing sequence we are **currently counting**. For example, in the sequence: 5, 6, 1, 2, 3 **`count_current_longest`** will be 2 when we reach **the second element** of the counting (5, **6**, 1, 2, 3) and will become 3 when we have reached **the last element** (5, 6, 1, 2, **3**) because the increasing row 1, 2, 3 has 3 elements. We will use **`count_longest`** to keep **the longest** increasing sequence. The other variables we will use are **`a`** - the number we are at **at the moment**, and **`a_prev`** - **the previous number**, which we will compare with **`a`** to find out whether the row **is growing**.
We begin to run the numbers and check if the present number **`a`** is larger than the previous **`a_prev`**. If this is true, then the row **is growing**, and we need to increase its number by **1**. This is stored in the variable that tracks the length of the sequence we are currently in **`count_current_longest`**. If the number **`a`** **isn't bigger** than the previous one, it means that **a new sequence** starts, and we have to start the count from **1**. Finally, after all the checks are done, **`a_prev`** becomes **the number** that we're **currently** using, and we start the loop from the beginning with **the next** entered **`a`**.
Here is a sample implementation of the algorithm described:
![](/assets/chapter-8-1-images/08.Increasing-numbers-02.png)
What remains is to see which of all sequences is **the longest**. We will do this by checking in the loop if **the sequence** we are **currently** in has become longer than **the longest one by now**. The whole loop will look like this:
![](/assets/chapter-8-1-images/08.Increasing-numbers-03.png)
Finally, we print the length of **the longest** sequence found:
![](/assets/chapter-8-1-images/08.Increasing-numbers-04.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1059#7](https://judge.softuni.org/Contests/Practice/Index/1059#7).
## Problems for Drawing Figures on The Console
**The fifth** problem of the "Programming Basics" Practical Exam requires **using one or several nested loops for drawing** a figure on the console. Logical reasoning, simple calculations, and conditional statements may be required. The problem tests the ability of students to think logically and invent simple algorithms for solving problems, i.e. to think algorithmically. Here are some examples of Exam Problems:
### Problem: Perfect Diamond
Write a function that takes as a parameter **n** and draws **a perfect diamond** with size **n** as in the examples below.
#### Input Data
The input is an integer **n** in the interval [**1… 1000**].
#### Output Data
The diamond should be printed on the console as in the examples below.
#### Sample Input and Output
|Input|Output|Input|Output|
|-----|------|-----|------|
|2|<code>&nbsp;&#42;&nbsp;</code><br><code>&#42;-&#42;</code><br><code>&nbsp;&#42;&nbsp;</code>|3|<code>&nbsp;&nbsp;&#42;&nbsp;&nbsp;</code><br><code>&nbsp;&#42;-&#42;&nbsp;</code><br><code>&#42;-&#42;-&#42;</code><br><code>&nbsp;&#42;-&#42;&nbsp;</code><br><code>&nbsp;&nbsp;&#42;&nbsp;&nbsp;</code><br>|
|Input|Output|Input|Output|
|-----|------|-----|------|
|4|<code>&nbsp;&nbsp;&nbsp;&#42;&nbsp;&nbsp;&nbsp;</code><br><code>&nbsp;&nbsp;&#42;-&#42;&nbsp;&nbsp;</code><br><code>&nbsp;&#42;-&#42;-&#42;&nbsp;</code><br><code>&#42;-&#42;-&#42;-&#42;</code><br><code>&nbsp;&#42;-&#42;-&#42;&nbsp;</code><br><code>&nbsp;&nbsp;&#42;-&#42;&nbsp;&nbsp;</code><br><code>&nbsp;&nbsp;&nbsp;&#42;&nbsp;&nbsp;&nbsp;</code><br>|5|<code>&nbsp;&nbsp;&nbsp;&nbsp;&#42;&nbsp;&nbsp;&nbsp;&nbsp;</code><br><code>&nbsp;&nbsp;&nbsp;&#42;-&#42;&nbsp;&nbsp;&nbsp;</code><br><code>&nbsp;&nbsp;&#42;-&#42;-&#42;&nbsp;&nbsp;</code><br><code>&nbsp;&#42;-&#42;-&#42;-&#42;&nbsp;</code><br><code>&#42;-&#42;-&#42;-&#42;-&#42;</code><br><code>&nbsp;&#42;-&#42;-&#42;-&#42;&nbsp;</code><br><code>&nbsp;&nbsp;&#42;-&#42;-&#42;&nbsp;&nbsp;</code><br><code>&nbsp;&nbsp;&nbsp;&#42;-&#42;&nbsp;&nbsp;&nbsp;</code><br><code>&nbsp;&nbsp;&nbsp;&nbsp;&#42;&nbsp;&nbsp;&nbsp;&nbsp;</code><br>|
#### Hints and Guidelines
In tasks for drawing figures, the most important thing to consider is **the sequence** in which we will draw. Which elements are **repeated** and with what **steps**? We can see that **the top and the bottom** parts of the diamond are **the same**. The easiest way to solve the problem is by creating **a loop** that draws **the upper part**, and then **another loop** that draws **the bottom part** (opposite to the top one).
First, we read the number **`n`** from the console:
![](/assets/chapter-8-1-images/09.Perfect-diamond-01.png)
We start drawing **the upper half** of the diamond. We see that **each line** starts with some **whitespaces and <code>*</code>**. If we take a closer look, we will notice that **the whitespaces** are always equal to **`n - index of row - 1`** (the first row is n-1, the second n-2, etc.). We will start by drawing the number of **whitespaces** and **the first asterisk**. Let's not forget to use **`print(…, end='')`** instead of just **`print(…)`** to stay on **the same line**. At the end of the line, we write **`print ()`** to move to a **new line**. Notice that we start counting from **1, not 0**. Then all we have to do is add **`-*`** a few times to **complete the line**.
Here is the complete code for drawing **the upper part of the diamond**:
![](/assets/chapter-8-1-images/09.Perfect-diamond-02.png)
What remains is to **complete each line** with the required number of **`-*`** elements. On each row we have to add **`i - 1`** such **items** (on the first 1-1 -> 0, the second -> 1, etc.)
Here is the complete code for drawing **the upper part of the diamond**:
![](/assets/chapter-8-1-images/09.Perfect-diamond-03.png)
To draw **the bottom part** of the diamond, we have to reverse **the upper part**. We'll count from **`n - 2`** because if we start from **`n - 1`**, we will draw the middle row twice. Be sure to add **`reversed (…)`** to **`range (…)`** of the main loop.
Here is the code for drawing **the bottom part of the diamond**:
![](/assets/chapter-8-1-images/09.Perfect-diamond-04.png)
What remains is **to assemble the whole program** by first reading the input, printing the top part of the diamond, and then the bottom part of the diamond.
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1059#8](https://judge.softuni.org/Contests/Practice/Index/1059#8).
### Problem: Rectangle with Stars
Write a function that takes as a parameter an integer **n** and draws **a rectangle** with size **n with 2 asterisks in the center** as in the examples below.
#### Input Data
The parameter is an integer **n** in the range [**2 … 1000**].
#### Output Data
The rectangle should be printed on the console as in the examples below.
#### Sample Input and Output
|Input|Output|Input|Output|
|-----|------|-----|------|
|2|<code>&#37;&#37;&#37;&#37;</code><br><code>&#37;&#42;&#42;&#37;</code><br><code>&#37;&#37;&#37;&#37;</code><br>|3|<code>&#37;&#37;&#37;&#37;&#37;&#37;</code><br><code>&#37;&nbsp;&nbsp;&nbsp;&nbsp;&#37;</code><br><code>&#37;&nbsp;&#42;&#42;&nbsp;&#37;</code><br><code>&#37;&nbsp;&nbsp;&nbsp;&nbsp;&#37;</code><br><code>&#37;&#37;&#37;&#37;&#37;&#37;</code><br>|
|Input|Output|Input|Output|
|-----|------|-----|------|
|4|<code>&#37;&#37;&#37;&#37;&#37;&#37;&#37;&#37;</code><br><code>&#37;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#37;</code><br><code>&#37;&nbsp;&nbsp;&#42;&#42;&nbsp;&nbsp;&#37;</code><br><code>&#37;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#37;</code><br><code>&#37;&#37;&#37;&#37;&#37;&#37;&#37;&#37;</code><br>|5|<code>&#37;&#37;&#37;&#37;&#37;&#37;&#37;&#37;&#37;&#37;</code><br><code>&#37;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#37;</code><br><code>&#37;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#37;</code><br><code>&#37;&nbsp;&nbsp;&nbsp;&#42;&#42;&nbsp;&nbsp;&nbsp;&#37;</code><br><code>&#37;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#37;</code><br><code>&#37;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#37;</code><br><code>&#37;&#37;&#37;&#37;&#37;&#37;&#37;&#37;&#37;&#37;</code><br>|
#### Hints and Guidelines
We read the input data from the task:
![](/assets/chapter-8-1-images/10.Rectangle-with-stars-01.png)
The first thing we can easily notice is that **the first and the last rows** contain **`2 * n`** symbols **`%`**. We will start with this and then draw the middle part of the rectangle:
![](/assets/chapter-8-1-images/10.Rectangle-with-stars-02.png)
From the examples, we see that **the middle** part of the figure always has an **odd number** of rows. Note that when an **even number** is set, the number of rows is equal to **the previous odd** number (2 -> 1, 4 -> 3, etc.). We create a variable that represents the number of rows that our rectangle will have, and correct it if the number **`n` is even**. Then we will draw **a rectangle without the asterisks**. Each row has for **the beginning and at the end** the symbol **`%`** and between them **`2 * n - 2`** whitespaces (the width is **`2 * n`** and we subtract 2 for the two percent at the end). Do not forget to move the code or **the last line after the loop**:
![](/assets/chapter-8-1-images/10.Rectangle-with-stars-03.png)
We can **start and test the code so far**. Everything without the two asterisks in the middle should work correctly.
Now, **in the body** of the loop let's add the **asterisks**. We'll check if we're on the **middle row**. If we are in the middle, (we will check this by comparing **`i`** with **`floor(num_rows / 2)`**), we will draw **the row** together **with the asterisks**, if not we will draw **a normal row**. **Remember** to add **`from the math import floor`** at the beginning of the work file so that we can use the **`floor(…)`** function. The line with the asterisks has **`n-2` whitespaces** (**`n`** is half the length and we remove the asterisk and the percentage), **two asterisks**, and again **`n-2` whitespaces**. We leave out of the check the two percent at the beginning and the end of the row:
![](/assets/chapter-8-1-images/10.Rectangle-with-stars-04.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1059#9](https://judge.softuni.org/Contests/Practice/Index/1059#9).
## Problems with Nested Loops
**The last** (sixth) problem of the "Programming Basics" Practical Exam requires using of **several nested loops and more complex logic inside them**. The problems examine participants' ability to think algorithmically and to solve non-trivial coding problems that require nested loops. Here are some examples of exam problems.
### Problem: Increasing 4 Numbers
For a given pair of numbers, **a** and **b** generate all four numbers **n1, n2, n3, n4,** for which **a ≤ n1 < n2 < n3 < n4 ≤ b**.
#### Input Data
The input contains two integers **a** and **b** in the interval [**0… 1000**], one per line.
#### Output Data
The output contains all **numbers in batches of four**, in ascending order, one per line.
#### Sample Input and Output
|Input|Output|Input|Output|
|-----|------|-----|------|
|3<br>7|3 4 5 6<br>3 4 5 7<br>3 4 6 7<br>3 5 6 7<br>4 5 6 7|15<br>20|15 16 17 18<br>15 16 17 19<br>15 16 17 20<br>15 16 18 19<br>15 16 18 20<br>15 16 19 20<br>15 17 18 19<br>15 17 18 20<br>15 17 19 20<br>15 18 19 20<br>16 17 18 19<br>16 17 18 20<br>16 17 19 20<br>16 18 19 20<br>17 18 19 20<br>|
|Input|Output|Input|Output|
|-----|------|-----|------|
|5<br>7|No|10<br>13|10 11 12 13|
#### Hints and Guidelines
We read the input data from the console. We also create the additional variable **`count`**, which will keep track of whether **an existing number of ranges**:
![](/assets/chapter-8-1-images/11.Increasing-4-numbers-01.png)
We will most easily solve the problem if we logically divide it **into parts**. If we are required to draw all the rows from a number between **`a`** and **`b`**, we will do it using **one loop** that takes all the numbers from **`a`** to **`b`**. Let's think about how to do this with a **series of two numbers**. The answer is easy we will use **nested loops**:
![](/assets/chapter-8-1-images/11.Increasing-4-numbers-02.png)
We can test the incomplete program to see if it's accurate so far. It must print all pairs of numbers **`i`**, **`j`** for which **`i ≤ j`**.
Since each **next number** of the row must be **greater** than **the previous one**, the second loop will run around **`i + 1`** (the next greater number). Accordingly, if **there is no sequence** of two incremental numbers (**`a`** and **`b`** are equal), the second loop **will not be fulfilled**, and nothing will be printed on the console.
**Similarly**, what remains is to implement **the nested loops** for **four numbers**. We will add an **increase of the counter** (**`count`**) that we initialized to know if **there is such a sequence**:
![](/assets/chapter-8-1-images/11.Increasing-4-numbers-03.png)
Finally, we will check if **the counter** is equal to **0** and we will print "**No**" on the console accordingly, if so.
![](/assets/chapter-8-1-images/11.Increasing-4-numbers-04.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1059#10](https://judge.softuni.org/Contests/Practice/Index/1059#10).
### Problem: Generating Rectangles
By a given number **n** and **a minimum area m**, generate all possible rectangles with integer coordinates in the range [**-n … n**] with an area of at least **m**. The generated rectangles must be printed in the following format:
**(left, top) (right, bottom) -> area**
Rectangles are defined using the top left and bottom right corners. The following inequalities are in effect:
- **-n ≤ left < right ≤ n**
- **-n ≤ top < bottom ≤ n**
#### Input Data
Two numbers are entered from the console, one per line:
- Integer **n** in the range [**1 … 100**] - sets the minimum and maximum coordinate of a vertex.
- Integer **m** in the interval [**0 … 50 000**] - sets the minimum area of the generated rectangles.
#### Output Data
- The described rectangles should be printed on the console in a format such as in the examples below.
- If there are no rectangles for the specified **n** and **m**, then print "**No**".
- The order of rectangles in the output is not important.
#### Sample Input and Output
|Input|Output|Input|Output|
|-----|------|-----|------|
|1<br>2|(-1, -1) (0, 1) -> 2<br>(-1, -1) (1, 0) -> 2<br>(-1, -1) (1, 1) -> 4<br>(-1, 0) (1, 1) -> 2<br>(0, -1) (1, 1) -> 2|2<br>17|No|
|Input|Output|
|-----|------|
|3<br>36|(-3, -3) (3, 3) -> 36|
#### Hints and Guidelines
Let's read the input from the console. Again, we will create a **counter** in which we will store the number of rectangles found:
![](/assets/chapter-8-1-images/12.Generating-rectangles-01.png)
It is very important to be able to imagine the problem before we begin to solve it. In our case, it is required to search for rectangles in a coordinate system. The thing we know is that the **left point** will always have the coordinate **`x`, smaller** than **the right** one. Accordingly, **the upper one** will always have a smaller **`y`** coordinate than **the lower one**. To find all the rectangles, we'll have to create **a loop** similar to the previous problem, but this time, **not every next loop** will start from **the next number** because some of **the coordinates** can be equal (for example **`left`** and **`top`**):
![](/assets/chapter-8-1-images/12.Generating-rectangles-02.png)
With the variables **`left`** and **`right`** we will follow the coordinates along the **horizontal**, and with **`top`** and **`bottom`** - along the **vertical**.
The important thing here is knowing the corresponding coordinates so we can correctly calculate the sides of the rectangle. Now we have to find **the area of the rectangle** and check if it is **greater than** or **equal** to **`m`**. One **side** will be **the difference between `left` and `right`** and **the other one between `top` and `bottom`**. Since the coordinates may be eventually interchanged, we will use **absolute values**. Again, we add **the counter** in the loop, counting **only the rectangles** we write. It is important to note that the writing order is **`left`**, **`top`**, **`right`**, **`bottom`**, as it is set in the problem's description:
![](/assets/chapter-8-1-images/12.Generating-rectangles-03.png)
Finally, we print “**No**”, if there are no such rectangles.
![](/assets/chapter-8-1-images/12.Generating-rectangles-04.png)
#### Testing in The Judge System
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1059#11](https://judge.softuni.org/Contests/Practice/Index/1059#11).