automated terminal push
This commit is contained in:
365
docs/chapter-09/chapter-09-problems-for-champions-part-2.md
Executable file
365
docs/chapter-09/chapter-09-problems-for-champions-part-2.md
Executable file
@@ -0,0 +1,365 @@
|
||||
# Chapter 9.2. Problems for Champions – Part II
|
||||
|
||||
In this chapter, we will review three additional tasks that belong to the category "**For Champions**", i.e. they are more complex than the rest of the tasks in this book.
|
||||
|
||||
## More Complex Tasks on The Studied Material
|
||||
|
||||
Before we move on to particular tasks, we must clarify that these can be solved more easily with **additional knowledge in programming with Python** (functions, arrays, collections, recursion, etc.), but each solution that will be provided now only uses the material covered in this book. The goal is to learn how to construct **more complex algorithms** based on your knowledge collected up to the present moment.
|
||||
|
||||
## Problem: Passion Days
|
||||
|
||||
Lina has a real shopping passion. When she has some money, she immediately goes to the closest shopping center (mall) and tries to spend as much as she can on clothes, bags, and shoes. But her favorite thing is winter sales. Our task is to analyze her strange behavior and **calculate the purchases** that Lina does when she enters the mall, as well as the **money she has left** when the shopping is over.
|
||||
|
||||
The **first line** of the input will pass the **amount** that Lina has **before** she starts shopping. After that, upon reading the "**`mall.Enter`**" command, Lina enters the mall and starts shopping until the "**`mall.Exit`**" command is given. When Lina starts shopping, **on each line** of the input you will be given strings that are **actions performed by Lina**. Each **symbol** in the string is a **purchase or another action**. String commands contain only symbols of the **ASCII table**. The ASCII code of each sign is **related to what Lina must pay** for each of the goods. You need to interpret the symbols in the following way:
|
||||
|
||||
- If the symbol is a **capital letter**, Lina gets a **50% discount**, which means that you must decrease the money she has by 50% of the numeric representation of the symbol from the ASCII table.
|
||||
- If the symbol is a **small letter**, Lina gets a **70% discount**, which means that you must decrease the money she has by 30% of the numeric representation of the symbol from the ASCII table.
|
||||
- If the symbol is **"`%`"**, Lina makes a **purchase** that decreases her money in half.
|
||||
- If the symbol is **"`*`"**, Lina **withdraws money from her debit card** and adds 10 BGN to her available funds.
|
||||
- If the symbol is **different from all of the aforementioned**, Lina just purchases without discount, and in this case, you should simply subtract the value of the symbol from the ASCII table from her available funds.
|
||||
|
||||
If a certain value of her purchases is **higher** than her current available funds, Lina **DOES NOT** make the purchase. Lina's funds **cannot be less than 0**.
|
||||
|
||||
The shopping ends when the "**`mall.Exit`**" command is given. When this happens, you need to **print the number of purchases made and the money** that Lina has left.
|
||||
|
||||
### Input Data
|
||||
|
||||
The input data must be read from the console. The **first line** of the input will indicate the **amount that Lina has before starting to purchase**. On each of the following lines, there will be a particular command. After you read the command "**`mall.Enter`**", on each of the following lines you will be given strings holding **information regarding the purchases / actions** that Lina wants to perform. These strings will keep being passed until the "**`mall.Exit`**" command is given.
|
||||
|
||||
Always only one "**`mall.Enter`**" command will be given, as well as only one "**`mall.Exit`**" command.
|
||||
|
||||
### Output Data
|
||||
|
||||
When shopping is over, you must print on the console a particular output depending on what purchases have been made:
|
||||
|
||||
- If **no purchases have been made** – "**No purchases. Money left: {remaining funds} lv.**"
|
||||
- If **at least one purchase** is made – "**{number of purchases} purchases. Money left: {remaining funds} lv.**"
|
||||
|
||||
**The funds** must be printed with an **accuracy of up to 2 symbols after the decimal point**.
|
||||
|
||||
### Constraints
|
||||
|
||||
- Money is a **float** number within the range: [**0 - 7.9 x 10<sup>28</sup>**].
|
||||
- The number of strings between "**`mall.Enter`**" and "**`mall.Exit`**" will be within the range: [**1 - 20**].
|
||||
- The number of symbols in each string that represents a command will be within the range: [**1 - 20**].
|
||||
- Allowed execution time: **0.1 seconds**.
|
||||
- Allowed memory: **16 MB**.
|
||||
|
||||
### Sample Input and Output
|
||||
|
||||
| Input | Output | Comment |
|
||||
|----------------------------|------------------------------------|-----------|
|
||||
| 110<br>mall.Enter<br>d<br>mall.Exit | 1 purchases. Money left: 80.00 lv. | ‘d’ has an ASCII code of 100. ‘d’ is a small letter, this is why Lina gets a 70% discount. 100% – 70% = 30. 110 - 30 = 80 lv. |
|
||||
|
||||
| Input | Output |Input | Output |
|
||||
|------|-------|------|-------|
|
||||
| 110<br>mall.Enter<br>%<br>mall.Exit|1 purchases. Money left: 55.00 lv.| 100<br>mall.Enter<br>Ab<br>\*\*<br>mall.Exit|2 purchases. Money left: 58.10 lv.|
|
||||
|
||||
### Hints and Guidelines
|
||||
|
||||
We will separate the solution of the problem into three main parts:
|
||||
|
||||
- **Processing** of the input.
|
||||
- **Algorithm** for solving the problem.
|
||||
- **Formatting** the output.
|
||||
|
||||
Let's examine each of the parts in detail.
|
||||
|
||||
#### Processing The Input Data
|
||||
|
||||
The input of our task consists of a few components:
|
||||
|
||||
- In the **first argument, we have all the money** that Lina has for shopping.
|
||||
- In the **second argument, we have an array** that is a series of commands.
|
||||
|
||||
The first part is simple:
|
||||
|
||||

|
||||
|
||||
But in the second part is a detail that we need to take into consideration. The requirements state the following:
|
||||
|
||||
> Each of the next rolls will contain specific command. When we receive the command **"mall.Enter"**, on each of the next rolls the element will be a string containing information regarding the purchases/actions that Lina wants to perform.
|
||||
|
||||
This is where we need to take into consideration the fact that inside **our array we should start processing commands**, but **only after we receive** the command **"mall.Enter"**. How can we do that? Using a **`while`** or a **`do-while`** loop is a good option. Here is an exemplary solution of how **to skip** all commands before processing the command **"mall.Enter"**:
|
||||
|
||||

|
||||
|
||||
Here is the place to say that by calling **`input()`** after the end of the loop is used to **pass from the first command** for processing.
|
||||
|
||||
#### Algorithm for Solving The Problem
|
||||
|
||||
The algorithm for solving the problem is a direct one – we continue **reading commands** from the console **until the command "mall.Exit" is passed**. In the meantime, we **process** each symbol (**`char`**) of each one of the commands according to the rules specified in the task requirements, and in parallel, we **modify the amount** that Lina has and **store the number of purchases**.
|
||||
|
||||
Let's examine the first two problems for our algorithm. The first problem concerns the way we read the commands until we reach the **"mall.Exit"** command. The solution that we previously saw uses a **`while-loop`**. The second problem for the task is to **access each symbol** of the command passed. Keeping in mind that the input data with the commands is a **`string`** type, the easiest way to access each symbol inside the strings is via a **`for-in` loop**.
|
||||
|
||||
This is how the code may look like using two loops like this:
|
||||
|
||||

|
||||
|
||||
The next part of the algorithm is to **process the symbols from the commands**, according to the following rules in the requirements:
|
||||
|
||||
> - If the symbol is a **capital letter**, Lina gets a 50% discount, which means that you must decrease the money she has by 50% of the numeric representation of the symbol from the ASCII table.
|
||||
> - If the symbol is a **small letter**, Lina gets a 70% discount, which means that you must decrease the money she has by 30% of the numeric representation of the symbol from the ASCII table.
|
||||
> - If the symbol is **"%"**, Lina purchases and that decreases her money in half.
|
||||
> - If the symbol is **"\*"**, Lina withdraws money from her debit card and adds 10 BGN to her available funds.
|
||||
> - If the symbol is **different from all of the aforementioned**, Lina just purchases without discount, and in this case, you should simply subtract the value of the symbol from the ASCII table from her available funds.
|
||||
|
||||
Let's examine the problems that we will be facing in the first condition. The first one is how to distinguish if a particular **symbol is a capital letter**. We can use one of the following ways:
|
||||
- Keeping in mind the fact that the letters in the alphabet have a particular order, we can use the following condition **`action >= 'A' && action <= 'Z'`**, to check if our symbol is within the capital letters range.
|
||||
- We can use the function **`.isupper(…)`**.
|
||||
|
||||
The other problem is how **to skip a particular symbol** if it is not an operation that requires more money than Lina has. This is doable using the **`continue`** construction.
|
||||
|
||||
An exemplary condition for the first part of the requirements looks like this:
|
||||
|
||||

|
||||
|
||||
**Note**: the variable **`purchases`** is of **`int`** type, in which we store the number of all purchases.
|
||||
|
||||
We believe the reader should not have difficulties implementing all the other conditions because they are very similar to the first one.
|
||||
|
||||
#### Formatting The Output
|
||||
|
||||
At the end of our task we must **print** a particular **output**, depending on the following condition:
|
||||
|
||||
> - If no purchases have been made – "**No purchases. Money left: {remaining funds} lv.**"
|
||||
> - If at least one purchase is made – "**{number of purchases} purchases. Money left: {remaining funds} lv.**"
|
||||
|
||||
The printing operations are simple, as the only thing we need to take into consideration is that **the amount has to be printed with an accuracy of up to 2 symbols after the decimal point**.
|
||||
|
||||
How can we do that? We will leave the answer to this question to the reader.
|
||||
|
||||
### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1062#0](https://judge.softuni.org/Contests/Practice/Index/1062#0).
|
||||
|
||||
|
||||
## Problem: X Expression
|
||||
|
||||
Bonny is an exceptionally powerful witch. As her natural power is not sufficient to successfully fight vampires and werewolves, she has started to master the power of Expressions. An expression is very hard to master because the spell relies on the ability to **quickly solve mathematical expressions**.
|
||||
|
||||
To use an "Expression spell", the witch must know the result of a mathematical expression in advance. An **Expression spell** consists of a few simple mathematical expressions. Each mathematical expression can contain operators for **summing up**, **subtraction**, **multiplying**, and/or **division**.
|
||||
|
||||
The expression is solved **without considering the mathematical rules** for calculating numerical expressions. This means that the priority is applied according to the sequence of the operators, and not the type of calculation that they do. The expression **can contain brackets**, as **everything inside the brackets is calculated first**. Every expression can contain multiple brackets, but no nested brackets:
|
||||
- An expression containing **(…(…)…) is an invalid one**.
|
||||
- An expression containing **(…)…(…) is a valid one**.
|
||||
|
||||
### Problem
|
||||
|
||||
The expression
|
||||
|
||||

|
||||
|
||||
is solved in the following way:
|
||||
|
||||

|
||||
|
||||
Bonny is very pretty, but not as wise, so she will need our help to master the power of Expressions.
|
||||
|
||||
### Input Data
|
||||
|
||||
The input data consists of a single text line, passed from the console. It contains a **mathematical expression for calculation**. The line **always ends with the "=" symbol**. The **"="** symbol means **the end of the mathematical expression**.
|
||||
|
||||
The input data is always valid and always in the described format. No need to validate it.
|
||||
|
||||
### Output Data
|
||||
|
||||
The output data must be printed on the console. The output consists of one line: the result of the **calculated mathematical expression**.
|
||||
|
||||
The result must be rounded up to the **second digit after the decimal point**.
|
||||
|
||||
### Constraints
|
||||
|
||||
- The expressions will consist of **a maximum of 2500 symbols**.
|
||||
- The numbers of each mathematical expression will be within the range [**1 … 9**].
|
||||
- The operators in the mathematical expressions will always be among **`+`** (summing up), **`-`** (subtraction), **`/`** (division) or **`*`** (multiplying).
|
||||
- The result of the mathematical expression will be within the range [**-100000.00 … 100000.00**].
|
||||
- Allowed execution time: **0.1 seconds**.
|
||||
- Allowed memory: **16 MB**.
|
||||
|
||||
### Sample Input and Output
|
||||
|
||||
| Input | Output |Input | Output |
|
||||
|--------------------------------|--------|-------------------------------|--------|
|
||||
| 4+6/5+(4\*9–8)/7\*2= | 8.57 |3+(6/5)+(2\*3/7)\*7/2\*(9/4+4\*1)= | 110.63 |
|
||||
|
||||
### Hints and Guidelines
|
||||
|
||||
As usual, we will first read and process the input, after that, we will solve the problem, and finally, we will print the result, formatted as required.
|
||||
|
||||
#### Processing The Input Data
|
||||
|
||||
The input data will consist of exactly one text line read from the console. To have access to each expression, we have to read the input with **`input()`** function and then convert the string into an array of symbols. Using the function **`pop(…)`** we can process each symbol:
|
||||
|
||||

|
||||
|
||||
#### Algorithm for Solving The Problem
|
||||
|
||||
For the tasks of our problem we need to use some variables:
|
||||
|
||||
* One variable will store our **current result**.
|
||||
* And our final variable will store the **current operator** from our expression.
|
||||
|
||||

|
||||
|
||||
We have to clarify that in the code above, by default the operator is **`+`**, so that the first meet number can be summed with our result.
|
||||
|
||||
Now that we already have our starting variables, we must decide **what will be the main structure** of our program. By the requirements, we understand that **each expression ends with `=`**, i.e. we must read and process symbols until we reach a **`=`**. This is followed by an accurately written **`while` loop**.
|
||||
|
||||

|
||||
|
||||
Our next step is to process our **`symbol`** variable. We have 3 possible cases for it:
|
||||
|
||||
- If the symbol is a **start of a sub-expression placed in brackets** i.e. the found symbol is a **`(`**.
|
||||
- If the symbol is a **digit between 0 and 9**. But how can we check this? How can we check if our symbol is a digit? We can use for assistance the **ASCII code** of the symbol, via which we can use the following formula: **`[ASCII code of our symbol] – [ASCII code of the symbol 0] = [the digit that represents the symbol]`**. If **the result of this condition is between 0 and 9**, then our symbol is a **number**.
|
||||
|
||||
**Note**: to get the ASCII code of a certain symbol, we will use the function **`ord(…)`**.
|
||||
|
||||
- If the symbol is an **operator**, i.e. it is **`+`**, **`-`**, **`*`** or **`/`**.
|
||||
|
||||

|
||||
|
||||
Let's examine the actions that we need to undertake in the relevant cases that we defined:
|
||||
|
||||
- If our symbol is an **operator**, then the only thing we need to do is to **set a new value for the `expression_operator` variable**.
|
||||
- If our symbol is a **digit**, then we need to **change the current result of the expression depending on the current operator**, i.e. if **`expression_operator`** is a **`-`**, then we must **decrease the result by the numerical representation of the current symbol**. We can get the numerical representation of the current symbol via the formula that we used upon checking the condition for this case (**`[ASCII code of our symbol] – [the ASCII code of the symbol `0`] = [the digit that represents the symbol]`**).
|
||||
|
||||

|
||||
|
||||
- If our symbol is a **`(`**, this indicates the **beginning of a sub-expression** (an expression in brackets). By definition, **the sub-expression must be calculated before modifying the result of the whole expression** (the actions in brackets are performed first). This means that we will have a local result for the sub-expression and a local operator.
|
||||
|
||||

|
||||
|
||||
After that, to **calculate the sub-expression value**, we will use the same methods that we used for calculating the main expression – we use a **`while` loop** to **read symbols** (until we reach an **`)`** symbol). Depending on whether the read symbol is a number or an operator, we modify the result of the sub-expression. The implementation of these operations is identical to the above-described implementation for calculating expressions. This is why we believe the reader will be able to easily handle it.
|
||||
|
||||
After finishing the result calculation for our sub-expression, we **modify the result of the whole expression** depending on the value of the **`expression_operator`**.
|
||||
|
||||

|
||||
|
||||
#### Formatting The Output
|
||||
|
||||
The only output that the program must print on the console is the **result of solving the expression with an accuracy of up to two symbols after the decimal point**. How can we format the output this way? We will leave the answer to this question to the reader.
|
||||
|
||||
### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1062#1](https://judge.softuni.org/Contests/Practice/Index/1062#1).
|
||||
|
||||
## Problem: Bulls and Cows
|
||||
|
||||
We all know the game called "Bulls and Cows" ([https://en.wikipedia.org/wiki/Bulls_and_cows](https://en.wikipedia.org/wiki/Bulls_and_cows)). Upon having a particular 4-digit **secret number** and a 4-digit **suggested number**, the following rules are applied:
|
||||
|
||||
- If a digit in the suggested number matches a digit in the secret number and is located at the **same position**, we have a ***bull***.
|
||||
- If a digit in the suggested number matches a digit in the secret number but is located at a **different position**, we have a ***cow***.
|
||||
|
||||
Here are a few examples of the game:
|
||||
|
||||
| Secret number | 1 | 4 | 8 | 1 |Comment|
|
||||
|:-------------------:|:---:|:---:|:---:|:---:|:--------------------------:|
|
||||
| Suggested number | 8 | 8 | 1 | 1 | Bulls = 1<br>Cows = 2 |
|
||||
|
||||
| Secret number | 2 | 2 | 4 | 1 |Comment|
|
||||
|:-------------------:|:---:|:---:|:---:|:---:|:-------------------------:|
|
||||
| Suggested number | 9 | 9 | 2 | 4 | Bulls = 0<br>Cows = 2 |
|
||||
|
||||
Upon having a particular secret number and the bulls and cows pertaining to it, our task is **to find all possible suggested numbers** in ascending order. If there are **no suggested numbers** that match the criteria provided from the console, we must print "**No**".
|
||||
|
||||
### Input Data
|
||||
|
||||
The input data is read from the console. We have 3 lines in the input data:
|
||||
|
||||
- The first contains **the secret number**.
|
||||
- The second contains **the number of bulls**.
|
||||
- The third contains **the number of cows**.
|
||||
|
||||
The input data will always be valid. There is no need to verify them.
|
||||
|
||||
### Output Data
|
||||
|
||||
The output data must be printed on the console. The output must consist of **a single line** - **all suggested numbers**, space-separated. If there are **no suggested numbers** that match the criteria provided from the console, we must **print “No”**.
|
||||
|
||||
### Constraints
|
||||
|
||||
- The secret number will always consist of **4 digits in the range** [**1..9**].
|
||||
- The number of **cows and bulls** will always be in the range [**0..9**].
|
||||
- Allowed execution time: **0.15 seconds**.
|
||||
- Allowed memory: **16 MB**.
|
||||
|
||||
### Sample Input and Output
|
||||
|
||||
| Input | Output |
|
||||
|--------------|------------|
|
||||
| 2228<br>2<br>1 | 1222 2122 2212 2232 2242 2252 2262 2272 2281 2283 2284 2285 2286 2287 2289 2292 2322 2422 2522 2622 2722 2821 2823 2824 2825 2826 2827 2829 2922 3222 4222 5222 6222 7222 8221 8223 8224 8225 8226 8227 8229 9222 |
|
||||
|
||||
| Input | Output |
|
||||
|--------------|------------|
|
||||
| 1234<br>3<br>0 | 1134 1214 1224 1231 1232 1233 1235 1236 1237 1238 1239 1244 1254 1264 1274 1284 1294 1334 1434 1534 1634 1734 1834 1934 2234 3234 4234 5234 6234 7234 8234 9234 |
|
||||
|
||||
| Input | Output |
|
||||
|--------------|------------|
|
||||
| 1234<br>3<br>1 | No |
|
||||
|
||||
### Hints and Guidelines
|
||||
|
||||
To complete our task we can do the followings steps:
|
||||
|
||||
- We will generate all possible **four-digit combinations** (candidates for verification).
|
||||
- For each generated combination we will calculate **how many bulls** and **how many cows** it has according to the secret number. Upon matching the needed bulls and cows, we will **print the combination**.
|
||||
|
||||
#### Processing The Input Data
|
||||
|
||||
We have 3 lines in the input data:
|
||||
- The first contains **the secret number**.
|
||||
- The second contains **the number of bulls**.
|
||||
- The third contains **the number of cows**.
|
||||
|
||||
Reading the input data is simple:
|
||||
|
||||

|
||||
|
||||
#### Algorithm for Solving The Problem
|
||||
|
||||
Before starting to write the algorithm for solving our problem, we must **declare a flag** that indicates whether a solution is found:
|
||||
|
||||

|
||||
|
||||
If after finishing our algorithm this flag is still **`False`**, then we will print **`No`** on the console, as specified in the requirements:
|
||||
|
||||

|
||||
|
||||
Let's start analyzing our problem. What we need to do is **analyze all numbers from `1111` to `9999`**, excluding those that contain zeroes (for example **`9011`**, **`3401`**, etc. are invalid). What is the easiest way to **generate** all these **numbers**? We will **use nested loops**. As we have a **4-digit number**, we will have **4 nested loops**, as each of them will generate **an individual digit in our number** for testing:
|
||||
|
||||

|
||||
|
||||
Thanks to these loops, **we have access to every digit** of all numbers that we need to check. Our next step is to **separate the secret number into digits**. This can be achieved very easily by **slicing the string (string slicing)**. An alternative solution is to access the symbols by index:
|
||||
|
||||

|
||||
|
||||
Only two last steps remain until we start analyzing how many cows and bulls there are in a particular number. Accordingly, the first one is **the declaration of counter variables** in the nested loops, to **count the cows and bulls** for the current number. The second step is to make **copies of the digits of the current number** that we will analyze, to prevent problems upon working with nested loops, in case we make changes to them.
|
||||
|
||||

|
||||
|
||||
We are ready to start analyzing the generated numbers. What logic can we use? The easiest way to check how many cows and bulls there are inside a number is via a **sequence of `if-elif` conditions**. Yes, this is not the most optimal way, but to stick to what is covered in the current book, we will use this approach.
|
||||
|
||||
What conditions do we need?
|
||||
|
||||
The condition for the bulls is very simple – we check whether the **first digit** of the generated number matches the **same digit** in the secret number. We remove the digits that are already checked to avoid repetitions of bulls and cows:
|
||||
|
||||

|
||||
|
||||
We repeat the action for the second, third, and fourth digits.
|
||||
|
||||
Our conditional statement for cows can be done by this method - we check if the **first digit** from the generated number **matches with the second**, **the third**, or **the fourth** digit of the secret number. Example:
|
||||
|
||||

|
||||
|
||||
After that, we sequentially check whether the **second digit** of the generated number **matches the first one**, the **third one**, or the **fourth digit** of the secret number; whether the **third digit** of the generated number matches the **first one**, the **second one**, or the **fourth digit** of the secret number; and finally, we check whether the **fourth digit** of the generated number matches the **first one**, the **second one** or the **third digit** of the secret number.
|
||||
|
||||
#### Printing The Output
|
||||
|
||||
After completing all conditions, we just need to **check whether the bulls and cows in the currently generated number match the desired bulls and cows read from the console**. If this is true, we print the current number on the console:
|
||||
|
||||

|
||||
|
||||
### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1062#2](https://judge.softuni.org/Contests/Practice/Index/1062#2).
|
||||
331
docs/chapter-09/chapter-09-problems-for-champions.md
Executable file
331
docs/chapter-09/chapter-09-problems-for-champions.md
Executable file
@@ -0,0 +1,331 @@
|
||||
# Chapter 9.1. Problems for Champions – Part I
|
||||
|
||||
In this chapter, we will offer the reader a few **more difficult tasks**, that aim to develop **algorithmic skills** and acquire **programming techniques** to solve tasks of higher complexity.
|
||||
|
||||
## More Complex Problems on The Studied Material
|
||||
|
||||
Together we will solve several programming problems that cover the material studied in the book, but are more difficult than the usual problems of the practical exams at SoftUni. If you want to **become a programming basics champion**, we recommend practicing solving such complex tasks to make it easier for you to take exams.
|
||||
|
||||
|
||||
## Problem: Crossing Sequences
|
||||
|
||||
We have two sequences:
|
||||
- **a sequence of Tribonacci** (by analogy with the Fibonacci sequence), where each number is **the sum of the previous three** (with given three numbers)
|
||||
- a sequence generated by a **numerical spiral**, defined by looping like a spiral (right, bottom, left, top, right, bottom, left, top, etc.) of a matrix of numbers starting from its center with a given starting number and incremental step, by storing the current numbers in the sequence each time we make a turn.
|
||||
|
||||
Write a program that finds the first number that appears **in both sequences defined in an aforementioned way**.
|
||||
|
||||
### Problem
|
||||
|
||||
Let **the Tribonacci sequence** start with **1**, **2** and **3**. This means that **the first sequence** will contain the numbers 1, 2, 3, 6, 11, 20, 37, 68, 125, 230, 423, 778, 1431, 2632, 4841, 8904, 16377, 30122, 55403, 101902, and so on.
|
||||
|
||||
At the same time, let the **numbers in the spiral** begin with **5**, and the spiral increases by **2** at each step.
|
||||
|
||||
<img src="assets/chapter-9-1-images/01.Crossing-sequences-01.png" style="float: right; height: 300px;" />
|
||||
|
||||
Then **the second sequence** will contain the numbers 5, 7, 9, 13, 17, 23, 29, 37, and so on. We see that **37** is the first number to be found both in the Tribonacci sequence and in the spiral one, and that is the desired solution to the problem.
|
||||
|
||||
### Input Data
|
||||
|
||||
Input data should be read from the console.
|
||||
* On the first three lines of the input, we will read **three integers**, representing **the first three numbers** in the Tribonacci sequence.
|
||||
* On the next two lines of the input, we will read **two integers**, representing **the first numbers** and **the step** for each cell of the matrix for the spiral of numbers.
|
||||
|
||||
Input data will always be valid and will always be in the format described. No need to check.
|
||||
|
||||
### Output Data
|
||||
|
||||
The result should be printed on the console.
|
||||
|
||||
On the single line of the output, you must print **the lowest number that occurs in both sequences**. If there is no number in the **range** [**1 … 1 000 000**], which can be found in both sequences, print "**No**".
|
||||
|
||||
### Constraints
|
||||
|
||||
* All numbers in the input will be in the range [**1 … 1 000 000**].
|
||||
* Allowed program time: 1.5 seconds.
|
||||
* Allowed memory: 16 MB.
|
||||
|
||||
### Sample Input and Output
|
||||
|
||||
| Input | Output | Input | Output | Input | Output |
|
||||
| ------------------------- | ----- | ------------------------ | ----- | ------------------------ | ----- |
|
||||
| 1<br>2<br>3<br>5<br>2<br> | 37 | 13<br>25<br>99<br>5<br>2 | 13 | 99<br>99<br>99<br>2<br>2 | No |
|
||||
|
||||
|
||||
| Input | Output | Input | Output |
|
||||
| --------------------- | ----- | ---------------------- | ----- |
|
||||
| 1<br>1<br>1<br>1<br>1 | 1 | 1<br>4<br>7<br>23<br>3 | 23 |
|
||||
|
||||
### Hints and Guidelines
|
||||
|
||||
The problem seems quite complicated, so we will break it into simpler sub-problems: processing the input, generating Tribonacci sequence, generating numerical spiral, and sending the number for the sequences.
|
||||
|
||||
#### Processing The Input Data
|
||||
|
||||
The first step in solving the problem is to read and process the input. Input data consists of **5 integers**: **3** for the Tribonacci sequence and **2** for the numerical spiral:
|
||||
|
||||

|
||||
|
||||
Once we have the input data, we need to think about how we will generate the numbers in the two sequences.
|
||||
|
||||
#### Generating Tribonacci Sequence
|
||||
|
||||
For the Tribonacci sequence, we will always **collect the previous three values** and then move the values of those numbers (the three previous ones) to one position in the sequence, i.e. the value of the first one must accept the value of the second one, and so on. When we are done with the number, we will store its value in **an array**. Since the problem description states that the numbers in the sequences do not exceed 1,000,000, we can stop generating this range at exactly 1,000,000.
|
||||
|
||||

|
||||
|
||||
#### Generating Numerical Spiral
|
||||
|
||||
We need to think of **a relationship** between numbers in the numerical spiral so we can easily generate every next number without having to look at matrices and loop through them. If we carefully look at the picture from the description, we will notice that **every 2 "turns" in the spiral, the numbers we skip are increased by 1**, i.e. from *5 to 7* and from *7 to 9*, not a single number is skipped, but we directly **add with the step** with the sequence. From *9 to 13* and from *13 to 17* we skip a number, i.e. we add the step twice. From *17 to 23* and from *23 to 29* we skip two numbers, i.e. we add the step three times and so on.
|
||||
|
||||
Thus, we see that for the first two we have the **`last number + 1 * step`**, the next two we add with the **`2 * step`**, and so on.
|
||||
Every time we want to get to the next number of the spiral, we will have to make similar calculations.
|
||||
|
||||

|
||||
|
||||
What we have to take care of is **for every two numbers, our multiplier** (let's call it "coefficient") **must increase by 1** (**`spiral_step_mul++`**), which can be achieved with a simple check (**`spiral_count % 2 == 0`**). The whole code from the generation of the spiral in **an array** is given below:
|
||||
|
||||

|
||||
|
||||
#### Finding Common Number for The Sequences
|
||||
|
||||
Once we have generated the numbers in both sequences, we can proceed to unite them and build the final solution. How will it look? For **each of the numbers** in the first sequence (starting from the smaller one) we will check if it exists in the next one. The first number that meets this criteria will be **the answer** to the problem.
|
||||
|
||||
We will do a **linear**, search in the second array, and we will leave the more curious participants to optimize it using the technique called **binary search** because the second array is generated in sorted form, i.e. it meets the requirement to apply this type of search. The code for finding our solution will look like this:
|
||||
|
||||

|
||||
|
||||
The previous solution to the problem uses arrays to store the values. Arrays are not needed to solve the problem. There is an **alternative solution**, that generates the numbers and works directly with them instead of keeping them in an array. On **every step**, we can check whether **the numbers in the two sequences match**. If this is the case, we will print the number on the console and terminate the execution of our program. Otherwise, we will see the current number of which sequence is the smaller one and we will generate the next one where we are **"lagging"**. The idea is that **we will generate numbers from the sequence that is "behind"** until we skip the current number of the other sequence and then vice versa, and if we find a match in the meantime, we will terminate the execution:
|
||||
|
||||

|
||||
|
||||
### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1061#0](https://judge.softuni.org/Contests/Practice/Index/1061#0).
|
||||
|
||||
|
||||
## Problem: Magic Dates
|
||||
|
||||
**Date** is given in a "**dd-mm-yyyy**" format, e.g. 17-04-2018. We calculate **the weight of that date**, by taking all of its digits, multiplying each digit with the ones after it, and finally summing up all the results obtained. In our case, we have 8 digits: **17032007**, so the weight is **`1*7 + 1*0 + 1*3 + 1*2 + 1*0 + 1*0 + 1*7`** **+** **`7*0 + 7*3 + 7*2 + 7*0 + 7*0 + 7*7`** **+** **`0*3 + 0*2 + 0*0 + 0*0 + 0*7`** **+** **`3*2 + 3*0 + 3*0 + 3*7`** **+** **`2*0 + 2*0 + 2*7`** **+** **`0*0 + 0*7`** **+** **`0*7`** = **144**.
|
||||
|
||||
Our task is to write a program that finds all the **magical dates between two specific years (inclusively) corresponding to the given weight**. Dates must be printed in ascending order (by date) in the format "**dd-mm-yyyy**". We will only use the valid dates in the traditional calendar (the leap years have 29 days in February).
|
||||
|
||||
### Input Data
|
||||
|
||||
Input data should be read from the console. It consists of 3 lines:
|
||||
|
||||
* The first line contains an integer: **start year**.
|
||||
* The second line contains an integer: **end year**.
|
||||
* The third line contains an integer: **the search weight** for the dates.
|
||||
*
|
||||
Input data will always be valid and will always be in the format described. No need to check.
|
||||
|
||||
### Output Data
|
||||
|
||||
The result should be printed on the console as consecutive dates in **dd-mm-yyyy" format"**, sorted by date in ascending order. Each string must be in a separate line. If there are no existing magic dates, print "**No**".
|
||||
|
||||
### Constraints
|
||||
|
||||
* The start and final years are integer numbers in the range [**1900 - 2100**].
|
||||
* Magic weight is an integer in the range [**1 … 1000**].
|
||||
* Allowed program time: 0.75 seconds.
|
||||
* Allowed memory: 16 MB.
|
||||
|
||||
### Sample Input and Output
|
||||
|
||||
| Input | Output | Input | Output |
|
||||
| ------------------- | -------------------------------------- | ------------------------ | ----- |
|
||||
| 2007<br>2007<br>144 | 17-03-2007<br>13-07-2007<br>31-07-2007 | 2003<br>2004<br>1500<br> | No |
|
||||
|
||||
| Input | Output | Input | Output |
|
||||
| ------------------ | ---------------------------------------- | ---------------------- | ---------------------------------------- |
|
||||
| 2012<br>2014<br>80 | 09-01-2013<br>17-01-2013<br>23-03-2013<br>11-07-2013<br>01-09-2013<br>10-09-2013<br>09-10-2013<br>17-10-2013<br>07-11-2013<br>24-11-2013<br>14-12-2013<br>23-11-2014<br>13-12-2014<br>31-12-2014 | 2011<br>2012<br>14<br> | 01-01-2011<br>10-01-2011<br>01-10-2011<br>10-10-2011 |
|
||||
|
||||
### Hints and Guidelines
|
||||
|
||||
We start with inserting the necessary functionality and reading the input from the console. In this case, we insert the type `date` (with new name `datetype`), the functions `timedelta` and `floor` and read **3 integers**:
|
||||
|
||||

|
||||
|
||||
Having the start and the end year, it is nice to know how we will go through every date, not to worry about how many days there are in the month and whether it is a leap year, and so on.
|
||||
|
||||
#### Loop Through Dates
|
||||
|
||||
For looping through the dates, we will take advantage of the functionality that gives us the **`date`** type in **Python**. We will define a **start date variable**, that we can do using the constructor that accepts a year, month, and day. We know the year is the starting year we read from the console and the month and the day must be January and 1st respectively:
|
||||
|
||||

|
||||
|
||||
Once we have the start date, we want to create a **loop that runs until we exceed the final year** (or until we pass December 31 in the final year if we compare the full dates), increasing each day by 1 day.
|
||||
|
||||
To increase by one day in each rotation, we will use the method **`timedelta()`** in Python for creating a 1-day difference, which will be added to `date`. Adding 1 day to the date will help Python to take care instead of us, to decide where to skip the next month, how many days there is a month, and everything around the leap years:
|
||||
|
||||

|
||||
|
||||
In the end, our loop may look like this:
|
||||
|
||||

|
||||
|
||||
#### Calculating Date Weight
|
||||
|
||||
Each date consists of exactly **8 characters (digits)** - **2 for the day** (**`d1`**, **`d2`**), **2 for the month** (**`d3`**, **`d4`**), and **4 for the year** (**`d5`** to **`d8`**). This means that we will always have the same calculation every time, and we can benefit from this **to define the formula statically** (i.e. not to use loops, referring to different numbers from the date, but write the whole formula). To be able to write it, we will need **all digits from the date** in individual variables to make all the necessary multiplications. By using the division and partition operations on the individual components of the date, using the **`day`**, **`month`** and **`year`**, properties, we can retrieve each digit. We have to be careful with the integer division by 10 (**`/ 10`**), which won't be an integer division, that's why after each operation we have to round down to the lowest integer number by using **`floor(…)`**:
|
||||
|
||||

|
||||
|
||||
Let's also explain one of the more interesting lines here. Let's take the second digit of the year for example (**`d6`**). We divide the year by 100, and we take a remainder of 10. What do we do? First, we eliminate the last 2 digits of the year by dividing by 100 (Example: **`2018 / 100 = 20`**). With the remainder of 10, we take the last digit of the resulting number (**`20 % 10 = 0`**) and so we get 0, which is the second digit of 2018.
|
||||
|
||||
What remains is to do the calculation that will give us the magical weight of a given date. In order **not to write all multiplications**, as shown in the example, we will simply apply a **grouping**. What we need to do is multiply each digit with those that follow it. Instead of typing **`d1 * d2 + d1 * d3 + … + d1 * d8`**, we can shorten this expression to **`d1 * (d2 + d3 + … + d8)`**, for grouping when we have multiplication and summing up. Applying the same simplification for the other multiplications, we get the following formula:
|
||||
|
||||

|
||||
|
||||
#### Printing The Output
|
||||
|
||||
Once we have the weight calculated on a given date, we need **to check and see if it matches the magical weight we want**, to know if it should be printed or not. Checking can be done using a standard **`if`** operator, taking care to print the date in the correct format. Fortunately, we already have each one of the digits that we need to print from **`d1`** to **`d8`**. Here we have to be careful with the data types. Since the concatenation of strings and the summation are done by the same operator, we have to convert numbers to strings:
|
||||
|
||||

|
||||
|
||||
***Caution***: as we go through the dates from the start of the year to the end of it, they will always be arranged in ascending order as per the description.
|
||||
|
||||
Finally, if we have not found an eligible date, we will have a **`False`** value in the **`found`** variable and we will be able to print **`"No"`**:
|
||||
|
||||

|
||||
|
||||
### Testing in The Judge System
|
||||
|
||||
Test your solution here: [https://judge.softuni.org/Contests/Practice/Index/1061#1](https://judge.softuni.org/Contests/Practice/Index/1061#1).
|
||||
|
||||
|
||||
## Problem: Five Special Letters
|
||||
|
||||
Two numbers are given: **start** and **end**. Write a program that **generates all combinations of 5 letters**, each among the sets of **`{'a', 'b', 'c', 'd', 'e'}`**, so that the weight of these 5 letters is a number in the range **`[start … end]`**, inclusive. Print them in alphabetical order, in a single row, separated by a space.
|
||||
|
||||
**The weight of the letters** is calculated as follows:
|
||||
|
||||
```python
|
||||
weight('a') = 5;
|
||||
weight('b') = -12;
|
||||
weight('c') = 47;
|
||||
weight('d') = 7;
|
||||
weight('e') = -32;
|
||||
```
|
||||
|
||||
**The weight of the sequence** of the letters **`c1, c2, …, cn`** is calculated by removing all the letters that are repeated (from right to left) and then calculating the formula:
|
||||
|
||||
```python
|
||||
weight(c1, c2, …, cn) = 1 * weight(c1) + 2 * weight(c2) + … + n * weight(cn)
|
||||
```
|
||||
|
||||
**For example**, the weight of **`bcddc`** is calculated as follows:
|
||||
|
||||
First **we remove the repeating letters** and get **`bcd`**. Then we apply the formula: **`1 * weight('b') + 2 * weight('c') + 3 * weight('d') = 1 * (-12) + 2 * 47 + 3 * 7 = 103`**.
|
||||
|
||||
**Another example**: **`weight("cadae") = weight("cade") = 1 * 47 + 2 * 5 + 3 * 7 + 4 * (-32) = -50`**.
|
||||
|
||||
### Input Data
|
||||
|
||||
The input data is read from the console. It consists of two numbers:
|
||||
* The number for **start** is on the first line.
|
||||
* The number for **end** is on the second line.
|
||||
|
||||
Input data will always be valid and will always be in the format described. No need to check.
|
||||
|
||||
### Output Data
|
||||
|
||||
The result should be printed on the console as a sequence of strings, **arranged in alphabetical order**. Each string must be separated from the next one by a single space. If the weight of any of the 5 letter strings does not exist within the specified range, print "**No**".
|
||||
|
||||
### Constraints
|
||||
|
||||
* Numbers for **start** and **end** are integers in the range [**-10000 … 10000**].
|
||||
* Allowed program time: 0.75 seconds.
|
||||
* Allowed memory: 16 MB.
|
||||
|
||||
### Sample Input and Output
|
||||
|
||||
| Input | Output | Comments |
|
||||
| -------- | ----------- | -------------------------------------------- |
|
||||
| 40<br>42 | bcead bdcea | weight("bcead") = 41<br>weight("bdcea") = 40 |
|
||||
|
||||
| Input | Output |
|
||||
| ------- | ---------------------------------------- |
|
||||
| -1<br>1 | bcdea cebda eaaad eaada eaadd eaade eaaed eadaa eadad eadae eadda eaddd eadde eadea eaded eadee eaead eaeda eaedd eaede eaeed eeaad eeada eeadd eeade eeaed eeead |
|
||||
|
||||
| Input | Output |
|
||||
| ---------- | ---------------------------------------- |
|
||||
| 200<br>300 | baadc babdc badac badbc badca badcb badcc badcd baddc bbadc bbdac bdaac bdabc bdaca bdacb bdacc bdacd bdadc bdbac bddac beadc bedac eabdc ebadc ebdac edbac |
|
||||
|
||||
| Input | Output |
|
||||
| ---------- | ----- |
|
||||
| 300<br>400 | No |
|
||||
|
||||
### Hints and Guidelines
|
||||
|
||||
Like every problem, we start the solution by **Processing The Input Data**:
|
||||
|
||||

|
||||
|
||||
We have several main points in the problem - **generating all combinations** with a length of 5 including the 5 letters, **removing repeating letters**, and **calculating weight** for a simplified word. The answer will consist of every word whose weight is within the given range **`[first_number, second_number]`**.
|
||||
|
||||
#### Generating All Combinations
|
||||
|
||||
To generate **all combinations with a length of 1** using 5 symbols, we would use a **loop from 0..4**, as we want each number of the loop to match one character. To generate **all combinations with a length of 2** using 5 characters (i.e "aa", "ab", "ac", …, "ba", …), we would create **two nested loops each running through the digits from 0 to 4**, as we will once again make sure that each digit matches a specific character. We will repeat this step 5 times, so we will finally have **5 nested loops** with indexes **`i1`**, **`i2`**, **`i3`**, **`i4`**, and **`i5`**:
|
||||
|
||||

|
||||
|
||||
Now that we have all 5-digit combinations, we must find a way to "turn" the five digits into a word with the letters from '**a**' to '**e**'. One of the ways to do that is to **predefine a simple string that contains the letters**, that we have:
|
||||
|
||||

|
||||
|
||||
and **for each digit, we take the letter from the particular position**. This way the number **00000** will become **"aaaaa"**, the number **02423** will become **"acecd"**. We can create the 5-letter string in the following way:
|
||||
|
||||

|
||||
|
||||
***Another solution***: we can convert the digits to letters by using their arrangement in the **ASCII table**. The expression **`chr(ord('a') + i)`** returns the result **`'a'`** in case **`i = 0`**, **`'b'`** in case **`i = 1`**, **`'c'`** in case **`i = 2`**, etc.
|
||||
|
||||
This way we already have generated all 5-letter combinations and can proceed with the following part of the task.
|
||||
|
||||
***Caution***: as we have chosen a **`pattern`**, that takes into consideration the alphabetical arrangement of the letters, and cycles are run appropriately, the algorithm will generate the works in alphabetical order and there is no need for additional sorting before printing the output.
|
||||
|
||||
#### Removing Repetitive Letters
|
||||
|
||||
Once we have the finished string, we have to remove all the repeating symbols. We will do this by adding **the letters from left to right in a new string and each time before adding a letter, we will check if it already exists** - if it does, we will skip it and if it doesn't, we will add it. To begin with, we will add the first letter to the starting string.:
|
||||
|
||||

|
||||
|
||||
Then we will do the same with the other 4, checking each time with the following condition and the **`find(…)`** method. This can be done with a loop by **`full_word`** (leaving it to the reader for exercise), and it can be done lazily by copy-paste.:
|
||||
|
||||

|
||||
|
||||
The **`find(…)`** method returns **the index of the particular element if it is found or **`-1`** if the item is not found**. Therefore, every time we get **`-1`**, it means that we still do not have this letter in the new string with unique letters and we can add it, and if we get a value other than **`-1`**, this will mean we already have the letter and we'll not add it.
|
||||
|
||||
#### Calculating Weight
|
||||
|
||||
Calculating the weight is simply **going through the unique word** (**`word`**), obtained in the last step, and for each letter, we need to take its weight and multiply it by the position. For each letter, we need to calculate what value we will multiply its position by, for example by using **`if`** constructions:
|
||||
|
||||

|
||||
|
||||
Once we have the value of that letter, we should **multiply it by its position**. Because the indexes in the string differ by 1 from the actual positions, i.e. index 0 is position 1, index 1 is position 2, etc., we will add 1 to the indexes.
|
||||
|
||||

|
||||
|
||||
All intermediate results obtained must be added to the **total amount for each letter of the 5-letter combination**.
|
||||
|
||||
#### Preparing The Output
|
||||
|
||||
Whether a word needs to be printed is determined by its weight. We need a condition to determine if **the current weight is in the range** [**start … end**], passed to the input at the start of the program. If this is the case, we print the **full** word (**`full_word`**).
|
||||
|
||||
**Be careful** not to print the word with unique letters. It was only needed to calculate the weight!
|
||||
|
||||
The words are **separated with a space** and we'll accumulate them in an intermediate variable **`result`**, which is defined as an empty string at the beginning.:
|
||||
|
||||

|
||||
|
||||
#### Final Touches
|
||||
|
||||
The condition is met **unless we do not have a single word in the entered range**. To find out if we have found a word, we can simply check whether the string **`result`** has its initial value (i.e., an empty string), if it does, we print **`"No"`**, otherwise we print the whole string without the last space (using the **`.strip(…)`** method):
|
||||
|
||||

|
||||
|
||||
For the curious ones, we will leave as an exercise to optimize the loop's function by reducing the number of iterations in nested loops.
|
||||
|
||||
### Testing in The Judge System
|
||||
|
||||
Test your solution here [https://judge.softuni.org/Contests/Practice/Index/1061#2](https://judge.softuni.org/Contests/Practice/Index/1061#2).
|
||||
Reference in New Issue
Block a user