├── .github
└── ISSUE_TEMPLATE
│ ├── bug_report.md
│ ├── custom.md
│ ├── feature_request.md
│ └── question.md
├── .gitignore
├── Advanced
├── 1.Stacks, Queues, Tuples and Sets
│ ├── Lists as Stacks and Queues - Exercise
│ │ ├── 01. Reverse Numbers.py
│ │ ├── 02. Stacked Queries.py
│ │ ├── 03. Fast Food.py
│ │ ├── 04. Fashion Boutique.py
│ │ ├── 05. Truck Tour.py
│ │ ├── 06. Balanced Parentheses.py
│ │ ├── 07. Robotics.py
│ │ ├── 08. Crossroads.py
│ │ ├── 09. Key Revolver.py
│ │ └── 10. Cups and Bottles.py
│ ├── Lists as Stacks and Queues - Lab
│ │ ├── 01. Reverse Strings.py
│ │ ├── 02. Matching Parentheses.py
│ │ ├── 03. Supermarket.py
│ │ ├── 04. Water Dispenser.py
│ │ └── 05. Hot Potato.py
│ ├── Stacks, Queues, Tuples and Sets - Exercise
│ │ ├── 01. Numbers.py
│ │ ├── 02. Expression Evaluator.py
│ │ ├── 03. Milkshakes.py
│ │ ├── 04. Honey.py
│ │ ├── 05. Santa's Present Factory.py
│ │ └── 06. Paint Colors.py
│ ├── Tuples and Sets - Exercise
│ │ ├── 01. Unique Usernames.py
│ │ ├── 02. Sets of Elements.py
│ │ ├── 03. Periodic Table.py
│ │ ├── 04. Count Symbols.py
│ │ ├── 05. Longest Intersection.py
│ │ └── 06. Battle of Names.py
│ └── Tuples and Sets - Lab
│ │ ├── 01. Count Same Values.py
│ │ ├── 02. Students' Grades.py
│ │ ├── 03. Record Unique Names.py
│ │ ├── 04. Parking Lot.py
│ │ ├── 05. SoftUni Party.py
│ │ └── 06. Summation Pairs.py
├── 2.Multidimensional Lists
│ ├── 1.Multidimensional Lists - Exercise
│ │ ├── 01. Diagonals.py
│ │ ├── 02. Diagonal Difference.py
│ │ ├── 03. 2x2 Squares in Matrix.py
│ │ ├── 04. Maximal Sum.py
│ │ ├── 05. Matrix of Palindromes.py
│ │ ├── 06. Matrix Shuffling.py
│ │ ├── 07. Snake Moves.py
│ │ ├── 08. Bombs.py
│ │ ├── 09. Miner.py
│ │ └── 10. Radioactive Mutate Vampire Bunnies.py
│ ├── 2.Multidimensional Lists - Exercise
│ │ ├── 01. Flatten Lists.py
│ │ ├── 02. Matrix Modification.py
│ │ ├── 03. Knight Game.py
│ │ ├── 04. Easter Bunny.py
│ │ ├── 05. Alice in Wonderland.py
│ │ ├── 06. Range Day.py
│ │ └── 07. Present Delivery.py
│ └── Multidimensional Lists - Lab
│ │ ├── 01. Sum Matrix Elements.py
│ │ ├── 02. Even Matrix.py
│ │ ├── 03. Flattening Matrix.py
│ │ ├── 04. Sum Matrix Columns.py
│ │ ├── 05. Primary Diagonal.py
│ │ ├── 06. Symbol in Matrix.py
│ │ └── 07. Square with Maximum Sum.py
├── 3.Functions Advanced
│ ├── Functions Advanced - Exercise
│ │ ├── 01. Negative vs Positive.py
│ │ ├── 02. Keyword Arguments Length.py
│ │ ├── 03. Even or Odd.py
│ │ ├── 04. Numbers Filter.py
│ │ ├── 05. Concatenate.py
│ │ ├── 06. Function Executor.py
│ │ ├── 07. Grocery.py
│ │ ├── 08. Age Assignment.py
│ │ ├── 09. Recursion Palindrome.py
│ │ ├── 10. Fill the Box.py
│ │ └── 11. Math Operations.py
│ └── Functions Advanced - Lab
│ │ ├── 01. Multiplication Function.py
│ │ ├── 02. Person Info.py
│ │ ├── 03. Cheese Showcase.py
│ │ ├── 04. Rectangle.py
│ │ ├── 05. Operate.py
│ │ └── 06. Recursive Power.py
├── 4.Error Handling
│ ├── Error Handling - Exercise
│ │ ├── 01. Numbers Dictionary.py
│ │ └── 02. Email Validator.py
│ └── Error Handling - Lab
│ │ ├── 01. So Many Exceptions.py
│ │ ├── 02. Repeat Text.py
│ │ └── 03. Value Cannot Be Negative.py
├── 5.File Handling
│ ├── File Handling - Exercise
│ │ ├── 01. Even Lines
│ │ │ ├── 01. Even Lines.py
│ │ │ └── text.txt
│ │ ├── 02. Line Numbers
│ │ │ ├── 02. Line Numbers.py
│ │ │ └── text.txt
│ │ ├── 03. File Manipulator
│ │ │ └── 03. File Manipulator.py
│ │ └── 04. Directory Traversal
│ │ │ ├── 04. Directory Traversal.py
│ │ │ └── directory
│ │ │ ├── demo.pptx
│ │ │ ├── index.html
│ │ │ ├── index.js
│ │ │ ├── log.txt
│ │ │ ├── my_personal_favorite.py
│ │ │ ├── notes.txt
│ │ │ ├── program.py
│ │ │ └── python.py
│ └── File Handling - Lab
│ │ ├── 01. File Opener
│ │ ├── 01. File Opener.py
│ │ └── text.txt
│ │ ├── 02. File Reader
│ │ ├── 02. File Reader.py
│ │ └── numbers.txt
│ │ ├── 03. File Writer
│ │ ├── 03. File Writer.py
│ │ └── my_first_file.txt
│ │ ├── 04. File Delete
│ │ ├── 04. File Delete.py
│ │ └── my_first_file.txt
│ │ └── 05. Word Count
│ │ ├── 05. Word Count.py
│ │ ├── result.txt
│ │ ├── text.txt
│ │ └── words.txt
├── 6.Workshop
│ ├── Workshop - Exercise
│ │ └── Tic-Tac-Toe.py
│ └── Workshop - Lab
│ │ └── connect4.py
└── 7.Modules
│ ├── Modules - Exercise
│ ├── NEW
│ │ ├── __pycache__
│ │ │ ├── authentication.cpython-39.pyc
│ │ │ ├── buying_page.cpython-39.pyc
│ │ │ ├── canvas.cpython-39.pyc
│ │ │ └── helpers.cpython-39.pyc
│ │ ├── authentication.py
│ │ ├── buying_page.py
│ │ ├── canvas.py
│ │ ├── db
│ │ │ ├── products_data.json
│ │ │ └── users_information.txt
│ │ ├── helpers.py
│ │ ├── images
│ │ │ ├── black_jeans.png
│ │ │ ├── blue_t_shirt.png
│ │ │ └── shoes.png
│ │ └── main.py
│ └── OLD
│ │ ├── __pycache__
│ │ ├── authentication.cpython-39.pyc
│ │ ├── canvas.cpython-39.pyc
│ │ ├── helpers.cpython-39.pyc
│ │ └── products.cpython-39.pyc
│ │ ├── authentication.py
│ │ ├── canvas.py
│ │ ├── databases
│ │ ├── current_user.txt
│ │ ├── products.txt
│ │ ├── user_credentials_db.txt
│ │ └── users.txt
│ │ ├── helpers.py
│ │ ├── images
│ │ ├── linkedIn.png
│ │ ├── tree.png
│ │ └── vscode.png
│ │ ├── main.py
│ │ └── products.py
│ └── Modules - Lab
│ ├── 01. Calculate Logarithm.py
│ ├── 02. ASCII Art.py
│ ├── 03. Triangle.py
│ ├── 04. Mathematical Operations.py
│ ├── 05. Fibonacci Sequence.py
│ └── custom_module
│ ├── __init__.py
│ ├── fibonacci_sequence.py
│ ├── math_operations.py
│ └── triangle.py
├── Errors.py
├── Fundamentals
├── (A) Not Included In Final Score - Exercise
│ ├── (1) Basic Syntax, Conditional Statement and Loops
│ │ ├── 10. Mutate Strings.py
│ │ ├── 11. Easter Bread.py
│ │ └── 12. Christmas Spirit.py
│ ├── (2) Data Types and Variables
│ │ ├── 08. Party Profit.py
│ │ ├── 09. Snowballs.py
│ │ └── 10. Gladiator Expenses.py
│ ├── (3) Lists Basics
│ │ ├── 07. Easter Gifts.py
│ │ ├── 08. Seize the Fire.py
│ │ ├── 09. Hello, France.py
│ │ └── 10. Bread Factory
│ │ │ ├── 10. Bread Factory.py
│ │ │ └── fails.png
│ ├── (4) Functions
│ │ ├── 11. Loading Bar.py
│ │ └── 12. Factorial Division.py
│ ├── (5) Lists Advanced
│ │ ├── 09. Anonymous Threat.py
│ │ ├── 10. Pokemon Don't Go.py
│ │ └── 11. SoftUni Course Planning.py
│ ├── (6) Objects and Classes
│ │ ├── 08. Vehicle.py
│ │ └── 09. Movie.py
│ ├── (7) Dictionaries
│ │ ├── 11. Force Book.py
│ │ └── 12. SoftUni Exam Results.py
│ ├── (8) Text Processing
│ │ ├── 08. Letters Change Numbers.py
│ │ ├── 09. Rage Quit.py
│ │ └── 10. Winning Ticket.py
│ └── (9) Regular Expressions
│ │ └── 06. Extract the Links.py
├── (B) Basic Syntax, Conditional Statements and Loops
│ ├── Basic Syntax, Conditional Statements and Loops-Esercise
│ │ ├── 01. Jenny's Secret Message.py
│ │ ├── 02. Drink something.py
│ │ ├── 03. Chat Codes.py
│ │ ├── 04. Maximum Multiple.py
│ │ ├── 05. Orders.py
│ │ ├── 06. String Pureness.py
│ │ ├── 07. Double Char.py
│ │ ├── 08. How Much Coffee Do You Need.py
│ │ └── 09. Sorting Hat.py
│ ├── Basic Syntax, Conditional Statements and Loops-Lab
│ │ ├── 01. Number Definer.py
│ │ ├── 02. Largest Of Three Numbers.py
│ │ ├── 03. Word Reverse.py
│ │ ├── 04. Even Numbers.py
│ │ ├── 05. Number Between 1 and 100.py
│ │ ├── 06. Shopping.py
│ │ └── 07. Patterns.py
│ └── More Exercise
│ │ ├── 01. Find the largest.py
│ │ ├── 02. Find the capitals.py
│ │ ├── 03. Wolf in Sheep's clothing.py
│ │ └── 04. Sum of beach #on 2 lines!#.py
├── (C) Data Types and Variables
│ ├── Data Types and Variables - Exercise
│ │ ├── 01. Integer operations.py
│ │ ├── 02. Chars to String.py
│ │ ├── 03. Elevator.py
│ │ ├── 04. Sum of Chars.py
│ │ ├── 05. Print Part of the ASCII Table.py
│ │ ├── 06. Triples of Latin Letters.py
│ │ └── 07. Water Overflow.py
│ ├── Data Types and Variables - Lab
│ │ ├── 01. Concat Names.py
│ │ ├── 02. Centuries to Minutes.py
│ │ ├── 03. Special Numbers.py
│ │ ├── 04. Convert Meters to Kilometers.py
│ │ ├── 05. Pounds to Dollars.py
│ │ └── 06. Next Happy Year.py
│ └── More Exercise
│ │ ├── (1) Conditions.docx
│ │ ├── 01. Exchange Integers.py
│ │ ├── 02. Prime Number Checker.py
│ │ ├── 03. Decrypting Messages.py
│ │ └── 04. Balanced Brackets.py
├── (D) Lists Basics
│ ├── Lists Basics - Exercise
│ │ ├── 01. Invert Values.py
│ │ ├── 02. Multiples List.py
│ │ ├── 03. Football Cards.py
│ │ ├── 04. Number Beggars.py
│ │ ├── 05. Faro Shuffle.py
│ │ └── 06. Survival of The Biggest.py
│ ├── Lists Basics - Lab
│ │ ├── 01. Strange Zoo.py
│ │ ├── 02. Courses.py
│ │ ├── 03. List Statistics.py
│ │ ├── 04. Search.py
│ │ └── 05. Numbers Filter.py
│ └── More Exercise
│ │ ├── 01. Zeros to Back.py
│ │ ├── 02. Messaging.py
│ │ ├── 03. Car Race.py
│ │ ├── 04. Josephus Permutation.py
│ │ ├── 05. Tic-Tac-Toe
│ │ ├── 05. Tic-Tac-Toe solved with current knowledge.py
│ │ ├── 05. Tic-Tac-Toe solved with functions and loops.py
│ │ └── 05. Tic-Tac-Toe solved with if-elif-else.py
│ │ └── 06. List Manipulator.py
├── (F) Lists Advanced
│ ├── Lists Advanced - Exercise
│ │ ├── 01. Which Are In.py
│ │ ├── 02. Next Version.py
│ │ ├── 03. Word Filter.py
│ │ ├── 04. Number Classification.py
│ │ ├── 05. Office Chairs.py
│ │ ├── 06. Electron Distribution.py
│ │ ├── 07. Group of 10's.py
│ │ └── 08. Decipher This!.py
│ ├── Lists Advanced - Lab
│ │ ├── 01. No Vowels.py
│ │ ├── 02. Trains.py
│ │ ├── 03. To-do List.py
│ │ ├── 04. Palindrome String.py
│ │ ├── 05. Sorting Names.py
│ │ ├── 06. Even Numbers.py
│ │ └── 07. The Office.py
│ └── More Exercise
│ │ ├── 01. Social Distribution.py
│ │ ├── 02. Take_Skip Rope.py
│ │ ├── 03. Kate's Way Out.py
│ │ ├── 04. Battle Ships.py
│ │ └── 05. Dots.py
├── (I) Objects and Classes
│ ├── Objects and Classes - Exercise
│ │ ├── 01. Storage.py
│ │ ├── 02. Weapon.py
│ │ ├── 03. Catalogue.py
│ │ ├── 04. Town.py
│ │ ├── 05. Class.py
│ │ ├── 06. Inventory.py
│ │ └── 07. Articles.py
│ └── Objects and Classes - Lab
│ │ ├── 01. Comment.py
│ │ ├── 02. Party.py
│ │ ├── 03. Email.py
│ │ ├── 04. Zoo.py
│ │ └── 05. Circle.py
├── (J) Dictionaries
│ ├── Dictionaries - Exercise
│ │ ├── 01. Count Chars in a String.py
│ │ ├── 02. A Miner Task.py
│ │ ├── 03. Capitals.py
│ │ ├── 04. Phonebook.py
│ │ ├── 05. Legendary Farming.py
│ │ ├── 06. Orders.py
│ │ ├── 07. SoftUni Parking.py
│ │ ├── 08. Courses.py
│ │ ├── 09. Student Academy.py
│ │ └── 10. Company Users.py
│ ├── Dictionaries - Lab
│ │ ├── 01. Bakery.py
│ │ ├── 02. Stock.py
│ │ ├── 03. Statistics.py
│ │ ├── 04. Students.py
│ │ ├── 05. ASCII Values.py
│ │ ├── 06. Odd Occurrences.py
│ │ └── 07. Word Synonyms.py
│ └── More Exercise
│ │ ├── 01. Ranking.py
│ │ ├── 02. Judge.py
│ │ ├── 03. MOBA Challenger.py
│ │ ├── 04. Show White.py
│ │ └── 05. Dragon Army.py
├── (K) Text Processing
│ ├── Text Processing - Exercise
│ │ ├── 01. Valid Usernames.py
│ │ ├── 02. Character Multiplier.py
│ │ ├── 03. Extract File.py
│ │ ├── 04. Caesar Cipher.py
│ │ ├── 05. Emoticon Finder.py
│ │ ├── 06. Replace Repeating Chars.py
│ │ └── 07. String Explosion.py
│ ├── Text Processing - Lab
│ │ ├── 01. Reverse Strings.py
│ │ ├── 02. Repeat Strings.py
│ │ ├── 03. Substring.py
│ │ ├── 04. Text Filter.py
│ │ └── 05. Digits, Letters and Other.py
│ └── Text Processing - More Exercise
│ │ ├── 01. Extract Person Information.py
│ │ ├── 02. ASCII Sumator.py
│ │ ├── 03. Treasure Finder.py
│ │ ├── 04. Morse Code Translator.py
│ │ └── 05. HTML.py
└── (L) Regular Expressions
│ ├── Regular Expressions - Exercise
│ ├── 01. Capture the Numbers.py
│ ├── 02. Find Variable Names in Sentences.py
│ ├── 03. Find Occurrences of Word in Sentence.py
│ ├── 04. Extract Emails.py
│ └── 05. Furniture.py
│ ├── Regular Expressions - Lab
│ ├── 01. Match Full Name.py
│ ├── 02. Match Phone Number.py
│ ├── 03. Match Dates.py
│ └── 04. Match Numbers.py
│ └── Regular Expressions - More Exercise
│ ├── 01. Race.py
│ ├── 02. SoftUni Bar Income.py
│ ├── 03. Star Enigma.py
│ ├── 04. Nether Realms.py
│ └── 05. HTML Parser.py
├── __main__.py
├── __pycache__
├── Errors.cpython-310.pyc
├── Errors.cpython-39.pyc
├── file_manipulator.cpython-310.pyc
└── file_manipulator.cpython-39.pyc
├── file_manipulator.py
├── license
├── readme.md
└── softuni_exercise_solutions.app.zip
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: 'bug'
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/custom.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: custom
3 | about: something else.
4 | title: ''
5 | labels: 'custom'
6 | assignees: ''
7 |
8 | ---
9 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: 'feedback'
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/question.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: question
3 | about: If something is not understandable or you just don't know something.
4 | title: ''
5 | labels: 'question'
6 | assignees: ''
7 |
8 | ---
9 |
10 |
11 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__/
2 | .github/
3 |
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Exercise/01. Reverse Numbers.py:
--------------------------------------------------------------------------------
1 | class Stack:
2 |
3 | def __init__(self):
4 | self.stack = []
5 |
6 | def push(self, element):
7 | self.stack.append(element)
8 |
9 | def pop(self):
10 | return self.stack.pop()
11 |
12 | def peek(self):
13 | return self.stack[-1]
14 |
15 | def count(self):
16 | return len(self.stack)
17 |
18 |
19 | reverse_integers = Stack()
20 |
21 | [reverse_integers.push(int(num)) for num in input().split()]
22 | [print(reverse_integers.pop(), end=" ") for _ in range(reverse_integers.count())]
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Exercise/02. Stacked Queries.py:
--------------------------------------------------------------------------------
1 | class Stack:
2 |
3 | def __init__(self):
4 | self.stack = []
5 |
6 | def push(self, element):
7 | self.stack.append(element)
8 |
9 | def pop(self):
10 | return self.stack.pop()
11 |
12 | def peek(self):
13 | return self.stack[-1]
14 |
15 | def count(self):
16 | return len(self.stack)
17 |
18 |
19 | stack = Stack()
20 | numbers_list = []
21 |
22 | lines = int(input())
23 |
24 | for queries in range(lines):
25 | query = input()
26 |
27 | if query.startswith("1"):
28 | num = int(query.split()[1])
29 | stack.push(num)
30 | numbers_list.append(num)
31 |
32 | elif query == "2":
33 | if stack.count():
34 | stack.pop()
35 | numbers_list.pop()
36 |
37 | elif query == "3":
38 | if stack.count():
39 | print(max(numbers_list))
40 |
41 | elif query == "4":
42 | if stack.count():
43 | print(min(numbers_list))
44 |
45 |
46 | print(", ".join([str(stack.pop()) for _ in range(stack.count())]))
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Exercise/03. Fast Food.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 | food_quantity = int(input())
4 | orders = deque(map(int, input().split()))
5 | too_many_orders = False
6 |
7 | print(max(orders))
8 |
9 | for order in range(len(orders)):
10 | if food_quantity - orders[0] >= 0:
11 | food_quantity -= orders.popleft()
12 |
13 | else:
14 | too_many_orders = True
15 | print("Orders left:", ' '.join([str(order) for order in orders]))
16 | break
17 |
18 | if not too_many_orders:
19 | print('Orders complete')
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Exercise/04. Fashion Boutique.py:
--------------------------------------------------------------------------------
1 | class Stack:
2 |
3 | def __init__(self):
4 | self.stack = [int(num) for num in input().split()]
5 |
6 | def push(self, element):
7 | self.stack.append(element)
8 |
9 | def pop(self):
10 | return self.stack.pop()
11 |
12 | def peek(self):
13 | return self.stack[-1]
14 |
15 | def count(self):
16 | return len(self.stack)
17 |
18 |
19 | clothes = Stack()
20 | capacity_per_rack = int(input())
21 |
22 | racks_used = 1
23 |
24 | sum_clothes = 0
25 | while clothes.count():
26 |
27 | if clothes.peek() + sum_clothes <= capacity_per_rack:
28 | sum_clothes += clothes.pop()
29 |
30 | elif clothes.peek() + sum_clothes > capacity_per_rack:
31 | racks_used += 1
32 | sum_clothes = clothes.pop()
33 |
34 | print(racks_used)
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Exercise/05. Truck Tour.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 | number_petrol_pumps = int(input())
4 | pumps = deque()
5 |
6 | for pump in range(number_petrol_pumps):
7 | pumps.append([int(num) for num in input().split()])
8 |
9 | for attempt in range(number_petrol_pumps):
10 |
11 | trunk = 0
12 | failed_attempt = False
13 |
14 | for petrol, distance in pumps:
15 | trunk = trunk + petrol - distance
16 | if trunk < 0:
17 | failed_attempt = True
18 | break
19 |
20 | if failed_attempt:
21 | pumps.append(pumps.popleft())
22 |
23 | elif not failed_attempt:
24 | print(attempt)
25 | break
26 |
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Exercise/06. Balanced Parentheses.py:
--------------------------------------------------------------------------------
1 | class Stack:
2 |
3 | def __init__(self):
4 | self.stack = []
5 |
6 | def push(self, element):
7 | self.stack.append(element)
8 |
9 | def pop(self):
10 | return self.stack.pop()
11 |
12 | def peek(self):
13 | return self.stack[-1]
14 |
15 | def count(self):
16 | return len(self.stack)
17 |
18 |
19 | pairs = {
20 | '{': '}',
21 | '(': ')',
22 | '[': ']'
23 | }
24 |
25 | bracket_integers = Stack()
26 | parentheses = input()
27 |
28 | balanced = True
29 |
30 | for index, bracket in enumerate(parentheses):
31 |
32 | if bracket in pairs.keys():
33 | bracket_integers.push(index)
34 |
35 | elif bracket in pairs.values():
36 | if bracket_integers.count():
37 |
38 | last_index = bracket_integers.peek()
39 |
40 | if bracket == pairs[parentheses[last_index]]:
41 | bracket_integers.pop()
42 |
43 | else:
44 | balanced = False
45 |
46 | else:
47 | balanced = False
48 |
49 | if not balanced:
50 | break
51 |
52 | if balanced:
53 | print('YES')
54 |
55 | elif not balanced:
56 | print("NO")
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Exercise/08. Crossroads.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 | green_light = int(input())
4 | window = int(input())
5 |
6 | cars = deque()
7 | cars_counter = 0
8 | crashed = False
9 |
10 | command = input()
11 | while command != "END":
12 | if command == "green":
13 | if cars:
14 | current_car = cars.popleft()
15 | seconds_left = green_light - len(current_car)
16 |
17 | while seconds_left > 0:
18 | cars_counter += 1
19 |
20 | if cars:
21 | current_car = cars.popleft()
22 | seconds_left -= len(current_car)
23 |
24 | else:
25 | break
26 |
27 | if seconds_left == 0:
28 | cars_counter += 1
29 |
30 | if window >= abs(seconds_left):
31 | if seconds_left < 0:
32 | cars_counter += 1
33 |
34 | else:
35 | index = window + seconds_left
36 | print("A crash happened!")
37 | print(f"{current_car} was hit at {current_car[index]}.")
38 | crashed = True
39 | break
40 | else:
41 | cars.append(command)
42 |
43 | command = input()
44 |
45 | if not crashed:
46 | print("Everyone is safe.")
47 | print(f"{cars_counter} total cars passed the crossroads.")
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Exercise/09. Key Revolver.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 | bullet_price = int(input())
4 | size_barrel = int(input())
5 |
6 | bullets = input().split()
7 | bullets = deque([int(item) for item in bullets])
8 |
9 | org_bullets = deque(bullets)
10 |
11 | locks = input().split(' ')
12 | locks = deque([int(item) for item in locks])
13 |
14 | intelligence = int(input())
15 | shoot = 0
16 |
17 | while bullets and locks:
18 |
19 | if bullets and shoot == size_barrel:
20 | print(f'Reloading!')
21 | shoot = 0
22 |
23 | if bullets[-1] <= locks[0]:
24 | print('Bang!')
25 | bullets.pop()
26 | locks.popleft()
27 | shoot += 1
28 |
29 | else:
30 | print('Ping!')
31 | bullets.pop()
32 | shoot += 1
33 |
34 | if bullets and shoot == size_barrel:
35 | print(f'Reloading!')
36 | shoot = 0
37 |
38 | if locks:
39 | print(f"Couldn't get through. Locks left: {len(locks)}")
40 |
41 | else:
42 | cost = (len(org_bullets) - len(bullets)) * bullet_price
43 | profit = intelligence - cost
44 | print(f"{len(bullets)} bullets left. Earned ${profit}")
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Exercise/10. Cups and Bottles.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 | cups = deque(int(cup) for cup in input().split())
4 | bottles = list(int(bottle) for bottle in input().split())
5 |
6 | wasted_water = 0
7 |
8 | while True:
9 | if cups and bottles:
10 | current_cup = cups.popleft()
11 | current_bottle = bottles.pop()
12 |
13 | if current_bottle >= current_cup:
14 | wasted_water += current_bottle - current_cup
15 |
16 | else:
17 | cups.appendleft(current_cup - current_bottle)
18 | else:
19 | break
20 |
21 | if cups:
22 | print(f"Cups: {' '.join([str(cup) for cup in cups])}")
23 |
24 | if bottles:
25 | print(f"Bottles: {' '.join([str(bottle) for bottle in bottles])}")
26 |
27 | print(f"Wasted litters of water: {wasted_water}")
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Lab/01. Reverse Strings.py:
--------------------------------------------------------------------------------
1 | class Stack:
2 |
3 | def __init__(self):
4 | self.stack = []
5 |
6 | def push(self, element):
7 | self.stack.append(element)
8 |
9 | def pop(self):
10 | return self.stack.pop()
11 |
12 | def peek(self):
13 | return self.stack[-1]
14 |
15 | def count(self):
16 | return len(self.stack)
17 |
18 |
19 | reverser = Stack()
20 |
21 | string = input()
22 |
23 | [reverser.push(char) for char in string]
24 | [print(reverser.pop(), end="") for _ in range(len(string))]
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Lab/02. Matching Parentheses.py:
--------------------------------------------------------------------------------
1 | class Stack:
2 |
3 | def __init__(self):
4 | self.stack = []
5 |
6 | def push(self, element):
7 | self.stack.append(element)
8 |
9 | def pop(self):
10 | return self.stack.pop()
11 |
12 | def peek(self):
13 | return self.stack[-1]
14 |
15 | def count(self):
16 | return len(self.stack)
17 |
18 |
19 | parentheses = Stack()
20 |
21 | expression = input()
22 |
23 | for index in range(len(expression)):
24 |
25 | if expression[index] == '(':
26 | parentheses.push(index)
27 |
28 | elif expression[index] == ')':
29 | opening_bracket = parentheses.pop()
30 | closing_bracket = index
31 | print(expression[opening_bracket:closing_bracket+1])
32 |
33 |
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Lab/03. Supermarket.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 | supermarket = deque()
4 |
5 | command = input()
6 | while command != "End":
7 |
8 | if command == "Paid":
9 | queue_length = len(supermarket)
10 | [print(supermarket.popleft()) for _ in range(queue_length)]
11 |
12 | else:
13 | supermarket.append(command)
14 |
15 | command = input()
16 |
17 | print(f"{len(supermarket)} people remaining.")
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Lab/04. Water Dispenser.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 | queue = deque()
4 |
5 | dispenser_quantity = int(input())
6 |
7 | command = input()
8 | while command != "Start":
9 | queue.append(command)
10 | command = input()
11 |
12 | command = input()
13 | while command != "End":
14 |
15 | if command.isdigit():
16 | liters = int(command)
17 |
18 | if liters <= dispenser_quantity:
19 | dispenser_quantity -= liters
20 | print(f"{queue.popleft()} got water")
21 |
22 | elif liters > dispenser_quantity:
23 | print(f"{queue.popleft()} must wait")
24 |
25 | elif command.startswith("refill"):
26 | liters = int(command.split()[1])
27 | dispenser_quantity += liters
28 |
29 | command = input()
30 |
31 | print(f"{dispenser_quantity} liters left")
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Lists as Stacks and Queues - Lab/05. Hot Potato.py:
--------------------------------------------------------------------------------
1 | players = input().split()
2 |
3 | toss = int(input())
4 | number = toss
5 | kid_index = -1
6 |
7 | while len(players) != 1:
8 |
9 | kid_index += 1
10 | number -= 1
11 |
12 | if kid_index >= len(players):
13 | kid_index = 0
14 |
15 | if number == 0:
16 | kid_name = players.pop(kid_index)
17 | kid_index -= 1
18 | number = toss
19 | print(f"Removed {kid_name}")
20 |
21 | print(f"Last is {players[0]}")
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Stacks, Queues, Tuples and Sets - Exercise/01. Numbers.py:
--------------------------------------------------------------------------------
1 | first_integers, second_integers = set(map(int, input().split())), set(map(int, input().split()))
2 |
3 | commands = int(input())
4 |
5 | for command in range(commands):
6 | curr_command = input().split()
7 |
8 | if curr_command[0] == "Add":
9 | if curr_command[1] == "First":
10 | integers = curr_command[2:]
11 | [first_integers.add(int(num)) for num in integers]
12 |
13 | elif curr_command[1] == "Second":
14 | integers = curr_command[2:]
15 | [second_integers.add(int(num)) for num in integers]
16 |
17 | elif curr_command[0] == "Remove":
18 | if curr_command[1] == "First":
19 | integers = curr_command[2:]
20 | [first_integers.remove(int(num)) for num in integers if int(num) in first_integers]
21 |
22 | elif curr_command[1] == "Second":
23 | integers = curr_command[2:]
24 | [second_integers.remove(int(num)) for num in integers if int(num) in second_integers]
25 |
26 | elif curr_command == ['Check', 'Subset']:
27 | if first_integers.issubset(second_integers) or second_integers.issubset(first_integers):
28 | print(True)
29 | continue
30 | print(False)
31 |
32 | print(f"{', '.join([str(num) for num in sorted(first_integers)])}"
33 | f"\n"
34 | f"{', '.join([str(num) for num in sorted(second_integers)])}")
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Stacks, Queues, Tuples and Sets - Exercise/03. Milkshakes.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 |
4 | class Stack:
5 |
6 | def __init__(self, items):
7 | self.stack = list(items)
8 |
9 | def push(self, element):
10 | self.stack.append(element)
11 |
12 | def pop(self):
13 | return self.stack.pop()
14 |
15 | def peek(self):
16 | return self.stack[-1]
17 |
18 | def count(self):
19 | return len(self.stack)
20 |
21 | def __repr__(self):
22 | return ', '.join([str(item) for item in self.stack])
23 |
24 |
25 | chocolates = Stack(map(int, input().split(", ")))
26 | cups_of_milk = deque(map(int, input().split(", ")))
27 |
28 | milkshakes = 0
29 |
30 | while chocolates.count() and cups_of_milk and milkshakes < 5:
31 |
32 | current_chocolate = chocolates.pop()
33 | current_cup = cups_of_milk.popleft()
34 |
35 | if current_chocolate <= 0 and current_cup <= 0:
36 | continue
37 |
38 | elif current_chocolate <= 0:
39 | cups_of_milk.appendleft(current_cup)
40 | continue
41 |
42 | elif current_cup <= 0:
43 | chocolates.push(current_chocolate)
44 | continue
45 |
46 | if current_chocolate == current_cup:
47 | milkshakes += 1
48 |
49 | else:
50 | cups_of_milk.append(current_cup)
51 | chocolates.push(current_chocolate - 5)
52 |
53 | if milkshakes == 5:
54 | print("Great! You made all the chocolate milkshakes needed!")
55 |
56 | else:
57 | print("Not enough milkshakes.")
58 |
59 | if chocolates.count():
60 | print(f"Chocolate: {chocolates}")
61 |
62 | else:
63 | print("Chocolate: empty")
64 |
65 | if cups_of_milk:
66 | print(f"Milk: {', '.join([str(num) for num in cups_of_milk])}")
67 |
68 | else:
69 | print("Milk: empty")
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Stacks, Queues, Tuples and Sets - Exercise/06. Paint Colors.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 | substring = deque(input().split())
4 |
5 | colors = {
6 | "all colors": ("red", "yellow", "blue", "orange", "purple", "green"),
7 | "required colors": {
8 | "orange": ("red", "yellow"),
9 | "purple": ("red", "blue"),
10 | "green": ("yellow", "blue")
11 | }
12 | }
13 |
14 | result = []
15 |
16 | while substring:
17 |
18 | last_part = ""
19 |
20 | if len(substring) > 1:
21 |
22 | last_part = substring.pop()
23 |
24 | first_part = substring.popleft()
25 |
26 | for color in (first_part + last_part, last_part + first_part):
27 |
28 | if color in colors["all colors"]:
29 |
30 | result.append(color)
31 |
32 | break
33 | else:
34 |
35 | for item in (first_part[:-1], last_part[:-1]):
36 |
37 | if item:
38 |
39 | substring.insert(len(substring) // 2, item)
40 |
41 | for color, req_colors in colors["required colors"].items():
42 |
43 | if any(x not in result and color in result for x in req_colors):
44 |
45 | result.remove(color)
46 |
47 | print(result)
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Tuples and Sets - Exercise/01. Unique Usernames.py:
--------------------------------------------------------------------------------
1 | names = int(input())
2 |
3 | unique_usernames = {input() for username in range(names)}
4 |
5 | print('\n'.join(unique_usernames))
6 |
7 |
8 | # print('\n'.join({input() for username in range(int(input()))}))
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Tuples and Sets - Exercise/02. Sets of Elements.py:
--------------------------------------------------------------------------------
1 | n, m = list(map(int, input().split()))
2 |
3 | set_n, set_m = set(), set()
4 |
5 | for first_set in range(n):
6 | num = int(input())
7 | set_n.add(num)
8 |
9 | for second_set in range(m):
10 | num = int(input())
11 | set_m.add(num)
12 |
13 | print('\n'.join([str(num) for num in set_n.intersection(set_m)]))
14 |
15 |
16 |
17 |
18 | # n, m = list(map(int, input().split()))
19 | # print('\n'.join([str(num) for num in set([int(input()) for num in range(n)]).intersection(set([int(input()) for num in range(m)]))]))
20 |
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Tuples and Sets - Exercise/03. Periodic Table.py:
--------------------------------------------------------------------------------
1 | lines = int(input())
2 |
3 | periodic_table = set()
4 |
5 | for element in range(lines):
6 | chemical_elements = input().split()
7 | [periodic_table.add(elem) for elem in chemical_elements]
8 |
9 | print('\n'.join(periodic_table))
10 |
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Tuples and Sets - Exercise/04. Count Symbols.py:
--------------------------------------------------------------------------------
1 | symbols = tuple([symbol for symbol in input()])
2 |
3 | result = {}
4 |
5 | for symbol in symbols:
6 | if symbol not in result.keys():
7 | result[symbol] = 1
8 | continue
9 | result[symbol] += 1
10 |
11 | result = sorted(result.items(), key=lambda x: x[0])
12 |
13 | for char in result:
14 | print(f"{char[0]}: {char[1]} time/s")
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Tuples and Sets - Exercise/05. Longest Intersection.py:
--------------------------------------------------------------------------------
1 | lines = int(input())
2 |
3 | max_intersection = 0
4 |
5 | longest_intersection = set()
6 | first_set = set()
7 | second_set = set()
8 |
9 | for index in range(lines):
10 |
11 | intersections = input().split("-")
12 |
13 | range_1 = [int(num) for num in intersections[0].split(",")]
14 | range_2 = [int(num) for num in intersections[1].split(",")]
15 |
16 | for number in range(range_1[0], range_1[1] + 1):
17 | first_set.add(number)
18 |
19 | for number in range(range_2[0], range_2[1] + 1):
20 | second_set.add(number)
21 |
22 | sets_intersection = first_set.intersection(second_set)
23 |
24 | if len(sets_intersection) > max_intersection:
25 |
26 | max_intersection = len(sets_intersection)
27 | longest_intersection = sets_intersection
28 |
29 | first_set.clear()
30 | second_set.clear()
31 |
32 | print(f"Longest intersection is {[num for num in longest_intersection]} with length {max_intersection}")
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Tuples and Sets - Exercise/06. Battle of Names.py:
--------------------------------------------------------------------------------
1 | def even_odd_or_equal(even: set, odd: set):
2 |
3 | if sum(even) == sum(odd):
4 | return ", ".join([str(num) for num in odd | even])
5 |
6 | elif sum(odd) > sum(even):
7 | return ", ".join([str(num) for num in odd - even])
8 |
9 | elif sum(even) > sum(odd):
10 | return ", ".join([str(num) for num in odd ^ even])
11 |
12 |
13 | names = int(input())
14 |
15 | even_set = set()
16 | odd_set = set()
17 |
18 | for row in range(1, names + 1):
19 |
20 | name_ascii_sum = sum([ord(char) for char in input()]) / row
21 | name_ascii_sum = int(name_ascii_sum)
22 |
23 | if name_ascii_sum % 2 == 0:
24 | even_set.add(name_ascii_sum)
25 |
26 | elif name_ascii_sum % 2 != 0:
27 | odd_set.add(name_ascii_sum)
28 |
29 | print(even_odd_or_equal(even_set, odd_set))
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Tuples and Sets - Lab/01. Count Same Values.py:
--------------------------------------------------------------------------------
1 | numbers = tuple(map(float, input().split()))
2 | used_numbers = set()
3 |
4 | for num in numbers:
5 | if num not in used_numbers:
6 | print(f"{num:.1f} - {numbers.count(num)} times")
7 | used_numbers.add(num)
8 |
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Tuples and Sets - Lab/02. Students' Grades.py:
--------------------------------------------------------------------------------
1 | grades = int(input())
2 |
3 | students = {}
4 |
5 | for curr_student in range(grades):
6 | student, grade = input().split()
7 |
8 | if student not in students:
9 | students[student] = [float(grade)]
10 | continue
11 |
12 | students[student].append(float(grade))
13 |
14 | for student, student_grades in students.items():
15 | print(student, '->', ' '.join([f'{grade:.2f}' for grade in student_grades]), f'(avg: {sum(student_grades) / len(student_grades):.2f})')
16 |
17 |
18 |
19 | # ---- OLD ----
20 | # student_grades = {}
21 | #
22 | # number_of_grades = int(input())
23 | #
24 | # for grades in range(number_of_grades):
25 | # name, grade = input().split()
26 | # if name not in student_grades:
27 | # student_grades[name] = [f'{float(grade):.2f}']
28 | # continue
29 | # student_grades[name].append(f'{float(grade):.2f}')
30 | #
31 | # [print(f'{name} -> {" ".join(grades)} (avg: {sum(list(map(float, grades))) / len(list(map(float, grades))):.2f})') for name, grades in student_grades.items()]
32 |
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Tuples and Sets - Lab/03. Record Unique Names.py:
--------------------------------------------------------------------------------
1 | names = int(input())
2 |
3 | unique_names = set()
4 |
5 | for curr_name in range(names):
6 | name = input()
7 | unique_names.add(name)
8 |
9 | print('\n'.join(unique_names))
10 |
11 |
12 | # names = set([input() for name in range(int(input()))])
13 | # print('\n'.join(names))
14 |
15 |
16 | # print('\n'.join(set([input() for name in range(int(input()))])))
17 |
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Tuples and Sets - Lab/04. Parking Lot.py:
--------------------------------------------------------------------------------
1 | directions = int(input())
2 |
3 | cars = set()
4 |
5 | for car_direction in range(directions):
6 | direction, car_number = input().split(', ')
7 |
8 | if direction == "IN":
9 | cars.add(car_number)
10 |
11 | else:
12 | cars.remove(car_number)
13 |
14 | if cars:
15 | print('\n'.join(cars))
16 |
17 | else:
18 | print("Parking Lot is Empty")
--------------------------------------------------------------------------------
/Advanced/1.Stacks, Queues, Tuples and Sets/Tuples and Sets - Lab/06. Summation Pairs.py:
--------------------------------------------------------------------------------
1 | numbers = list(map(int, input().split()))
2 | number_indexes = set()
3 | target_number = int(input())
4 |
5 | for first_index in range(len(numbers)):
6 |
7 | for second_index in range(len(numbers)):
8 |
9 | if first_index != second_index and first_index not in number_indexes and second_index not in number_indexes \
10 | and numbers[first_index] + numbers[second_index] == target_number:
11 |
12 | print(f"{numbers[first_index]} + {numbers[second_index]} = {target_number}")
13 | number_indexes.add(first_index), number_indexes.add(second_index)
14 | break
15 |
16 |
17 |
18 | # ---- OLD ----
19 | # numbers = list(map(int, input().split()))
20 | # target = int(input())
21 | #
22 | # summations = []
23 | # indexes = set()
24 | #
25 | # for index, number_one in enumerate(numbers):
26 | #
27 | # if index in indexes:
28 | # continue
29 | #
30 | # for second_index, number_two in enumerate(numbers):
31 | #
32 | # if second_index in indexes or second_index == index or index in indexes:
33 | # continue
34 | #
35 | # if number_one + number_two == target:
36 | #
37 | # summations.append([number_one, number_two])
38 | # indexes.add(index)
39 | # indexes.add(second_index)
40 | #
41 | # for summation in summations:
42 | #
43 | # first_number = summation[0]
44 | # second_number = summation[1]
45 | #
46 | # print(f'{first_number} + {second_number} = {target}')
47 |
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/1.Multidimensional Lists - Exercise/01. Diagonals.py:
--------------------------------------------------------------------------------
1 | rows = int(input())
2 |
3 | matrix = [
4 | [int(num) for num in input().split(", ")]
5 | for row in range(rows)
6 | ]
7 |
8 | primary_diagonal = [matrix[row_col][row_col] for row_col in range(rows)]
9 | secondary_diagonal = [matrix[::-1][row_col][row_col] for row_col in range(rows)][::-1]
10 |
11 | print(f"Primary diagonal: {', '.join([str(num) for num in primary_diagonal])}. Sum: {sum(primary_diagonal)}")
12 | print(f"Secondary diagonal: {', '.join([str(num) for num in secondary_diagonal])}. Sum: {sum(secondary_diagonal)}")
13 |
14 |
15 |
16 | # rows = int(input())
17 | #
18 | # matrix = []
19 | # primary_diagonal = []
20 | # secondary_diagonal = []
21 | #
22 | # for row in range(rows):
23 | # ''' Appending the columns into the matrix '''
24 | # columns = [int(num) for num in input().split(", ")]
25 | # matrix.append(columns)
26 | #
27 | # ''' Getting the matrix primary diagonal'''
28 | # column = row
29 | # primary_diagonal.append(matrix[row][column])
30 | #
31 | # ''' Getting the matrix secondary diagonal '''
32 | # secondary_columns = columns[::-1]
33 | # secondary_diagonal.append(secondary_columns[row])
34 | #
35 | # print(f"Primary diagonal: {', '.join([str(num) for num in primary_diagonal])}. Sum: {sum(primary_diagonal)}")
36 | # print(f"Secondary diagonal: {', '.join([str(num) for num in secondary_diagonal])}. Sum: {sum(secondary_diagonal)}")
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/1.Multidimensional Lists - Exercise/02. Diagonal Difference.py:
--------------------------------------------------------------------------------
1 | rows = int(input())
2 |
3 | matrix = [
4 | [int(num) for num in input().split()]
5 | for row in range(rows)
6 | ]
7 |
8 | primary_diagonal = [matrix[row_col][row_col] for row_col in range(rows)]
9 | secondary_diagonal = [matrix[::-1][row_col][row_col] for row_col in range(rows)][::-1]
10 |
11 | print(abs(sum(primary_diagonal) - sum(secondary_diagonal)))
12 |
13 |
14 | # rows = int(input())
15 | #
16 | # matrix = []
17 | # primary_diagonal = []
18 | # secondary_diagonal = []
19 | #
20 | # for row in range(rows):
21 | # ''' Appending the columns into the matrix '''
22 | # columns = [int(num) for num in input().split()]
23 | # matrix.append(columns)
24 | #
25 | # ''' Getting the matrix primary diagonal'''
26 | # column = row
27 | # primary_diagonal.append(matrix[row][column])
28 | #
29 | # ''' Getting the matrix secondary diagonal '''
30 | # secondary_columns = columns[::-1]
31 | # secondary_diagonal.append(secondary_columns[row])
32 | #
33 | # print(abs(sum(primary_diagonal) - sum(secondary_diagonal)))
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/1.Multidimensional Lists - Exercise/03. 2x2 Squares in Matrix.py:
--------------------------------------------------------------------------------
1 | rows, columns = list(map(int, input().split()))
2 |
3 | matrix = [input().split() for row in range(rows)]
4 |
5 | squares = 0
6 |
7 | for row in range(rows):
8 |
9 | for col in range(columns):
10 | if row+1 < rows and col+1 < columns:
11 | symbol = matrix[row][col]
12 | if matrix[row][col+1] == symbol and matrix[row+1][col] == symbol and matrix[row+1][col+1] == symbol:
13 | squares += 1
14 |
15 | print(squares)
16 |
17 |
18 | # rows, columns = list(map(int, input().split()))
19 | #
20 | # matrix = []
21 | # squares = 0
22 | #
23 | # for row in range(rows):
24 | # columns = input().split()
25 | # matrix.append(columns)
26 | #
27 | # try:
28 | #
29 | # for index, column in enumerate(columns):
30 | # if columns[index + 1] == column:
31 | # if 0 < row and matrix[row - 1][index] == column and matrix[row - 1][index + 1] == column:
32 | # squares += 1
33 | #
34 | # except IndexError:
35 | # continue
36 | #
37 | # print(squares)
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/1.Multidimensional Lists - Exercise/05. Matrix of Palindromes.py:
--------------------------------------------------------------------------------
1 | from string import ascii_letters
2 |
3 | letters = dict(zip([ord(c)%32 for c in ascii_letters], ascii_letters.lower()))
4 |
5 | rows, columns = list(map(int, input().split()))
6 |
7 | matrix = []
8 |
9 | for row in range(rows):
10 |
11 | cols = []
12 |
13 | for col in range(columns):
14 | column = letters[row+1] + letters[col+row+1] + letters[row+1]
15 | cols.append(column)
16 |
17 | matrix.append(cols)
18 | print(' '.join(cols))
19 |
20 |
21 | # import string
22 | #
23 | # letters_to_numbers = dict(zip(string.ascii_lowercase, range(1, 26 + 1)))
24 | #
25 | # numbers_to_letters = {number: letter for letter, number in letters_to_numbers.items()}
26 | #
27 | # rows, columns = [int(num) for num in input().split()]
28 | #
29 | # palindromes_matrix = []
30 | #
31 | # for row in range(rows):
32 | #
33 | # cols = []
34 | #
35 | # for column in range(columns):
36 | #
37 | # palindrome = numbers_to_letters[row+1] + numbers_to_letters[row+1 + column] + numbers_to_letters[row+1]
38 | # cols.append(palindrome)
39 | #
40 | # palindromes_matrix.append(cols)
41 | #
42 | # [print(' '.join(palindromes)) for palindromes in palindromes_matrix]
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/1.Multidimensional Lists - Exercise/07. Snake Moves.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 |
3 | rows, columns = list(map(int, input().split()))
4 |
5 | snake = input()
6 |
7 | matrix = []
8 |
9 | index_snake = 0
10 |
11 | for row in range(rows):
12 |
13 | result = deque()
14 |
15 | for col in range(columns):
16 |
17 | if index_snake == len(snake):
18 | index_snake = 0
19 |
20 | if row % 2 == 0:
21 | result.append(snake[index_snake])
22 |
23 | else:
24 | result.appendleft(snake[index_snake])
25 |
26 | index_snake += 1
27 |
28 | matrix.append(list(result))
29 | print("".join(result))
30 |
31 |
32 | # from collections import deque
33 | #
34 | # rows, columns = [int(num) for num in input().split()]
35 | # snake = input()
36 | #
37 | # index_snake = 0
38 | #
39 | # for row in range(rows):
40 | #
41 | # result = deque()
42 | #
43 | # for col in range(columns):
44 | #
45 | # if index_snake == len(snake):
46 | # index_snake = 0
47 | #
48 | # if row % 2 == 0:
49 | # result.append(snake[index_snake])
50 | #
51 | # else:
52 | # result.appendleft(snake[index_snake])
53 | #
54 | # index_snake += 1
55 | #
56 | # print("".join(result))
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/1.Multidimensional Lists - Exercise/08. Bombs.py:
--------------------------------------------------------------------------------
1 | matrix = [[int(num) for num in input().split()] for rows in range(int(input()))]
2 |
3 | for row, col in [[int(num) for num in bomb.split(",")] for bomb in input().split(" ")]:
4 | if matrix[row][col] <= 0: continue
5 | bomb_damage, matrix[row][col] = matrix[row][col], 0
6 | for row_pos, col_pos in ((0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (1, -1), (-1, 1), (1, 1)):
7 | if 0 <= row + row_pos < len(matrix) and 0 <= col + col_pos < len(matrix[0]):
8 | if matrix[row + row_pos][col + col_pos] > 0: matrix[row + row_pos][col + col_pos] -= bomb_damage
9 |
10 | alive_cells = [num for row in range(len(matrix)) for num in matrix[row] if num > 0]
11 | print(f"Alive cells: {len(alive_cells)}\nSum: {sum(alive_cells)}")
12 | [print(*matrix[row]) for row in range(len(matrix))]
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/2.Multidimensional Lists - Exercise/01. Flatten Lists.py:
--------------------------------------------------------------------------------
1 | matrix = [nums.split() for nums in input().split("|")]
2 | [[print(value, end=" ") for value in lst] for lst in matrix[::-1]]
3 |
4 |
5 | # [[print(value, end=" ") for value in lst] for lst in [nums.split() for nums in input().split("|")][::-1]]
6 |
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/2.Multidimensional Lists - Exercise/02. Matrix Modification.py:
--------------------------------------------------------------------------------
1 | rows = int(input())
2 |
3 | matrix = [
4 | [int(num) for num in input().split()]
5 | for row in range(rows)
6 | ]
7 |
8 | command = input()
9 | while command != "END":
10 | try:
11 |
12 | operation, row, col, value = command.split()
13 | row, col, value = int(row), int(col), int(value)
14 |
15 | if row >= 0 and col >= 0:
16 |
17 | if operation == "Add":
18 | matrix[row][col] += value
19 |
20 | elif operation == "Subtract":
21 | matrix[row][col] -= value
22 |
23 | else:
24 | print("Invalid coordinates")
25 |
26 | command = input()
27 |
28 | except Exception:
29 | print("Invalid coordinates")
30 | command = input()
31 |
32 | [print(" ".join([str(num) for num in line])) for line in matrix]
33 |
34 |
35 | # rows = int(input())
36 | #
37 | # matrix = []
38 | #
39 | # for row in range(rows):
40 | # columns = [int(num) for num in input().split()]
41 | # matrix.append(columns)
42 | #
43 | # command = input().split()
44 | # while command[0] != "END":
45 | #
46 | # row = int(command[1])
47 | # col = int(command[2])
48 | # value = int(command[3])
49 | #
50 | # if 0 <= row < len(matrix) and 0 <= col < len(matrix[row]):
51 | #
52 | # if command[0] == "Add":
53 | # matrix[row][col] += value
54 | #
55 | # elif command[0] == "Subtract":
56 | # matrix[row][col] -= value
57 | #
58 | # else:
59 | # print("Invalid coordinates")
60 | #
61 | # command = input().split()
62 | #
63 | # [print(*row) for row in matrix]
64 |
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/2.Multidimensional Lists - Exercise/05. Alice in Wonderland.py:
--------------------------------------------------------------------------------
1 | rows = int(input())
2 | matrix = [[char for char in input().split()] for row in range(rows)]
3 | columns = len(matrix[0])
4 |
5 | score, movement = [0], {"up": [-1, 0], "down": [1, 0], "left": [0, -1], "right": [0, 1]}
6 |
7 |
8 | def check_movement(row, col):
9 |
10 | if 0 <= row < rows and 0 <= col < columns and matrix[row][col] != "R":
11 | return True
12 |
13 | print("Alice didn't make it to the tea party.")
14 |
15 | rabit_row, rabit_col = find_position("R", False)
16 |
17 | if rabit_row + rabit_col == row + col:
18 | matrix[row][col] = "*"
19 |
20 | show_result()
21 | exit()
22 |
23 |
24 | def find_position(symbol, alice=True):
25 |
26 | for row in range(rows):
27 |
28 | if symbol in matrix[row]:
29 |
30 | col = matrix[row].index(symbol)
31 |
32 | if alice:
33 |
34 | matrix[row][col] = "*"
35 |
36 | return row, col
37 |
38 |
39 | alice_row, alice_col = find_position("A")
40 |
41 |
42 | def alice_movement(row, col, movement_pos):
43 |
44 | move_row, move_col = row + movement[movement_pos][0], col + movement[movement_pos][1]
45 |
46 | if check_movement(move_row, move_col):
47 |
48 | if matrix[move_row][move_col][-1].isdigit():
49 |
50 | score[0] += int(matrix[move_row][move_col])
51 |
52 | matrix[move_row][move_col] = "*"
53 |
54 | return move_row, move_col
55 |
56 |
57 | def show_result():
58 | [print(*matrix[row]) for row in range(rows)]
59 |
60 |
61 | while score[0] < 10:
62 | move = input()
63 | alice_row, alice_col = alice_movement(alice_row, alice_col, move)
64 |
65 | print("She did it! She went to the party.")
66 | show_result()
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/Multidimensional Lists - Lab/01. Sum Matrix Elements.py:
--------------------------------------------------------------------------------
1 | rows, columns = list(map(int, input().split(", ")))
2 |
3 | matrix = []
4 |
5 | sum_matrix = 0
6 |
7 | for row in range(rows):
8 | cols = list(map(int, input().split(", ")))
9 | matrix.append(cols)
10 | sum_matrix += sum(cols)
11 |
12 | print(sum_matrix)
13 | print(matrix)
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/Multidimensional Lists - Lab/02. Even Matrix.py:
--------------------------------------------------------------------------------
1 | rows = int(input())
2 |
3 | matrix = []
4 | even_matrix = []
5 |
6 | for row in range(rows):
7 | columns = list(map(int, input().split(", ")))
8 | matrix.append(columns)
9 |
10 | [even_matrix.append([num for num in matrix[row] if num % 2 == 0]) for row in range(rows)]
11 |
12 | print(even_matrix)
13 |
14 |
15 |
16 | # rows = int(input())
17 | #
18 | # matrix = []
19 | # for row in range(rows):
20 | # columns = [int(num) for num in input().split(", ")]
21 | # matrix.append([num for num in columns if num % 2 == 0])
22 | # # matrix.append(
23 | # # [
24 | # # int(num) for num in input().split(", ")
25 | # # if int(num) % 2 == 0
26 | # # ]
27 | # # )
28 | #
29 | # print(matrix)
30 |
31 |
32 |
33 | # even_matrix = []
34 | # result = [[even_matrix.append([num for num in list(map(int, input().split(", "))) if num % 2 == 0]) for row in range(int(input()))], print(even_matrix)]
35 |
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/Multidimensional Lists - Lab/03. Flattening Matrix.py:
--------------------------------------------------------------------------------
1 | rows = int(input())
2 |
3 | matrix = []
4 |
5 | for row in range(rows):
6 | columns = list(map(int, input().split(", ")))
7 | matrix.append(columns)
8 |
9 | flattening_matrix = []
10 | [[flattening_matrix.append(num) for num in matrix[row]] for row in range(rows)]
11 |
12 | print(flattening_matrix)
13 |
14 |
15 |
16 | # rows = int(input())
17 | #
18 | # matrix = []
19 | #
20 | # for row in range(rows):
21 | # columns = input().split(", ")
22 | # matrix.append(columns)
23 | #
24 | # flattening_matrix = [int(num) for elements in matrix for num in elements]
25 | # print(flattening_matrix)
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/Multidimensional Lists - Lab/04. Sum Matrix Columns.py:
--------------------------------------------------------------------------------
1 | rows, columns = list(map(int, input().split(", ")))
2 |
3 | matrix = []
4 | sum_columns = [[] for _ in range(columns)]
5 |
6 | for row in range(rows):
7 | cols = list(map(int, input().split()))
8 | matrix.append(cols)
9 |
10 | for col in range(columns):
11 | sum_columns[col].append(cols[col])
12 |
13 | [print(sum(cols)) for cols in sum_columns]
14 |
15 |
16 | # rows, columns = [int(num) for num in input().split(", ")]
17 | #
18 | # matrix = []
19 | #
20 | # for row in range(rows):
21 | # cols = [int(num) for num in input().split()]
22 | # matrix.append(cols)
23 | #
24 | # sum_matrix = []
25 | #
26 | # for column in range(columns):
27 | # column_sum = 0
28 | #
29 | # for row in range(rows):
30 | # column_sum += matrix[row][column]
31 | #
32 | # sum_matrix.append(column_sum)
33 | #
34 | # [print(num) for num in sum_matrix]
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/Multidimensional Lists - Lab/05. Primary Diagonal.py:
--------------------------------------------------------------------------------
1 | square_size = int(input()) # rows and columns
2 |
3 | matrix = []
4 | primary_diagonal_sum = 0
5 |
6 | for row in range(square_size):
7 | columns = list(map(int, input().split()))
8 | matrix.append(columns)
9 | primary_diagonal_sum += columns[row]
10 |
11 | print(primary_diagonal_sum)
12 |
13 |
14 | # rows = int(input())
15 | #
16 | # matrix = [
17 | # [
18 | # int(num)
19 | # for num in input().split()
20 | # ]
21 | # for row in range(rows)
22 | # ]
23 | #
24 | # sum_diagonal = 0
25 | #
26 | # for column in range(rows):
27 | # row = column
28 | # sum_diagonal += matrix[row][column]
29 | #
30 | # print(sum_diagonal)
--------------------------------------------------------------------------------
/Advanced/2.Multidimensional Lists/Multidimensional Lists - Lab/06. Symbol in Matrix.py:
--------------------------------------------------------------------------------
1 | rows = int(input())
2 |
3 | matrix = [
4 | [
5 | char for char in input()
6 | ]
7 | for row in range(rows)
8 | ]
9 |
10 | find_symbol = input()
11 | found_symbol = False
12 |
13 | for row in range(rows):
14 | columns = len(matrix[row])
15 |
16 | if found_symbol:
17 | break
18 |
19 | for column in range(columns):
20 |
21 | if matrix[row][column] == find_symbol:
22 |
23 | found_symbol = True
24 | print((row, column))
25 | break
26 |
27 | if not found_symbol:
28 | print(f"{find_symbol} does not occur in the matrix")
29 |
30 |
31 |
32 | # square_size = int(input()) # rows and columns
33 | #
34 | # matrix = []
35 | #
36 | # for row in range(square_size):
37 | # columns = [char for char in input()]
38 | # matrix.append(columns)
39 | #
40 | # search_symbol = input()
41 | # found_symbol = False
42 | #
43 | # for row in range(square_size):
44 | #
45 | # for col in range(square_size):
46 | # if matrix[row][col] == search_symbol:
47 | # print((row, col))
48 | # found_symbol = True
49 | # break
50 | # if found_symbol:
51 | # break
52 | #
53 | # if not found_symbol:
54 | # print(f"{search_symbol} does not occur in the matrix")
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Exercise/01. Negative vs Positive.py:
--------------------------------------------------------------------------------
1 | def negative_vs_positive(*args):
2 | sum_negatives = sum([num for num in args if num < 0])
3 | sum_positives = sum([num for num in args if num >= 0])
4 |
5 | print(sum_negatives)
6 | print(sum_positives)
7 |
8 | if abs(sum_negatives) > sum_positives:
9 | print("The negatives are stronger than the positives")
10 |
11 | elif sum_positives > abs(sum_negatives):
12 | print("The positives are stronger than the negatives")
13 |
14 |
15 | numbers = [int(num) for num in input().split()]
16 | negative_vs_positive(*numbers)
17 |
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Exercise/02. Keyword Arguments Length.py:
--------------------------------------------------------------------------------
1 | def kwargs_length(**kwargs):
2 | return len(kwargs)
3 |
4 |
5 | ''' TESTS '''
6 | # dictionary = {'name': 'Peter', 'age': 25}
7 |
8 | # print(kwargs_length(**dictionary))
9 | # ---------------------------------
10 | # dictionary = {}
11 |
12 | # print(kwargs_length(**dictionary))
13 |
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Exercise/03. Even or Odd.py:
--------------------------------------------------------------------------------
1 | def even_odd(*args):
2 | args, even_or_odd = args[:-1], args[-1]
3 |
4 | if even_or_odd == "even":
5 | return [num for num in args if num % 2 == 0]
6 |
7 | elif even_or_odd == "odd":
8 | return [num for num in args if num % 2 != 0]
9 |
10 |
11 | ''' TESTS '''
12 | # print(even_odd(1, 2, 3, 4, 5, 6, "even"))
13 | # print(even_odd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "odd"))
14 |
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Exercise/04. Numbers Filter.py:
--------------------------------------------------------------------------------
1 | def even_odd_filter(**kwargs):
2 |
3 | for key, values in kwargs.items():
4 |
5 | if key == "even":
6 | kwargs[key] = [num for num in values if num % 2 == 0]
7 |
8 | elif key == "odd":
9 | kwargs[key] = [num for num in values if num % 2 != 0]
10 |
11 | sorted_tuple = sorted(kwargs.items(), key=lambda x: -len(x[1]))
12 | sorted_dict = {item[0]: item[1] for item in sorted_tuple}
13 |
14 | return sorted_dict
15 |
16 |
17 | ''' TESTS '''
18 | # print(even_odd_filter(
19 | # odd=[1, 2, 3, 4, 10, 5],
20 | # even=[3, 4, 5, 7, 10, 2, 5, 5, 2],
21 | # ))
22 | # print(even_odd_filter(
23 | # odd=[2, 2, 30, 44, 10, 5],
24 | # ))
25 |
26 |
27 |
28 | # def even_odd_filter(**kwargs):
29 | # for key, numbers in kwargs.items():
30 | # if key == 'even':
31 | # kwargs[key] = [num for num in numbers if num % 2 == 0]
32 | #
33 | # elif key == 'odd':
34 | # kwargs[key] = [num for num in numbers if num % 2 != 0]
35 | #
36 | # return {key: numbers for key, numbers in sorted(kwargs.items(), key=lambda x: -len(x[1]))}
37 | #
38 | #
39 | # ''' TESTS '''
40 | # # print(even_odd_filter(
41 | # # odd=[1, 2, 3, 4, 10, 5],
42 | # # even=[3, 4, 5, 7, 10, 2, 5, 5, 2],
43 | # # ))
44 | # # print(even_odd_filter(
45 | # # odd=[2, 2, 30, 44, 10, 5],
46 | # # ))
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Exercise/05. Concatenate.py:
--------------------------------------------------------------------------------
1 | def concatenate(*args, **kwargs):
2 | message = ''.join(args)
3 |
4 | for old_str, new_str in kwargs.items():
5 | message = message.replace(old_str, new_str)
6 |
7 | return message
8 |
9 |
10 | ''' TESTS '''
11 | # print(concatenate("Soft", "UNI", "Is", "Grate", "!", UNI="Uni", Grate="Great"))
12 | # print(concatenate("I", " ", "Love", " ", "Cythons", C="P", s="", java='Java'))
13 |
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Exercise/06. Function Executor.py:
--------------------------------------------------------------------------------
1 | def func_executor(*args):
2 | function_results = []
3 |
4 | for function, elements in args:
5 | function_results.append(f"{function.__name__} - {function(*elements)}")
6 |
7 | return '\n'.join(function_results)
8 |
9 |
10 | """ ON ONE LINE!!! """
11 | # def func_executor(*args):return '\n'.join([f'{f.__name__} - {f(*fa)}' for f,fa in args])
12 |
13 |
14 |
15 | ''' TESTS '''
16 | # def sum_numbers(num1, num2):
17 | # return num1 + num2
18 |
19 |
20 | # def multiply_numbers(num1, num2):
21 | # return num1 * num2
22 |
23 |
24 | # print(func_executor(
25 | # (sum_numbers, (1, 2)),
26 | # (multiply_numbers, (2, 4))
27 | # ))
28 |
29 |
30 | # def make_upper(*strings):
31 | # result = tuple(s.upper() for s in strings)
32 | # return result
33 |
34 |
35 | # def make_lower(*strings):
36 | # result = tuple(s.lower() for s in strings)
37 | # return result
38 |
39 |
40 | # print(func_executor(
41 | # (make_upper, ("Python", "softUni")),
42 | # (make_lower, ("PyThOn",)),
43 | # ))
44 |
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Exercise/07. Grocery.py:
--------------------------------------------------------------------------------
1 | def grocery_store(**kwargs):
2 | products = sorted(kwargs.items(), key=lambda x: (-x[1], -len(x[0]), x[0]))
3 | return '\n'.join([f"{item[0]}: {item[1]}" for item in products])
4 |
5 |
6 | """ ON ONE LINE!!! """
7 | # def grocery_store(**kwargs): return '\n'.join([f"{item[0]}: {item[1]}" for item in sorted(kwargs.items(), key=lambda x: (-x[1], -len(x[0]), x[0]))])
8 |
9 |
10 |
11 |
12 | ''' TESTS '''
13 | # print(grocery_store(
14 | # bread=5,
15 | # pasta=12,
16 | # eggs=12,
17 | # ))
18 |
19 | # print(grocery_store(
20 | # bread=2,
21 | # pasta=2,
22 | # eggs=20,
23 | # carrot=1,
24 | # ))
25 |
26 |
27 |
28 |
29 |
30 | # def grocery_store(**kwargs):
31 | # '''
32 | #
33 | # The groceries should be sorted by their quantity in descending order.
34 | # If there are two or more products with the same quantity,
35 | # the groceries should be sorted by their name's length in descending order.
36 | # If there are two or more products with the same name's length,
37 | # the groceries should be sorted by their name in ascending order (alphabetically).
38 | #
39 | # '''
40 | #
41 | # string = ''
42 | #
43 | # for item, quantity in sorted(kwargs.items(), key=lambda x: (-x[1], -len(x[0]), x[0])):
44 | # string += f'{item}: {quantity}\n'
45 | #
46 | # return string
47 | #
48 | #
49 | # ''' TESTS '''
50 | # # print(grocery_store(
51 | # # bread=5,
52 | # # pasta=12,
53 | # # eggs=12,
54 | # # ))
55 | #
56 | # # print(grocery_store(
57 | # # bread=2,
58 | # # pasta=2,
59 | # # eggs=20,
60 | # # carrot=1,
61 | # # ))
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Exercise/08. Age Assignment.py:
--------------------------------------------------------------------------------
1 | def age_assignment(*args, **kwargs):
2 |
3 | people_ages = []
4 |
5 | for letter, ages in kwargs.items():
6 |
7 | for name in args:
8 | if name[0] == letter:
9 | people_ages.append(f"{name} is {ages} years old.")
10 |
11 | return '\n'.join(sorted(people_ages))
12 |
13 |
14 | ''' TESTS '''
15 | # print(age_assignment("Peter", "George", G=26, P=19))
16 | # print(age_assignment("Amy", "Bill", "Willy", W=36, A=22, B=61))
17 |
18 |
19 |
20 | # def age_assignment(*args, **kwargs):
21 | # age_dictionary = {}
22 | #
23 | # for letter in kwargs.keys():
24 | # for person in args:
25 | # if person[0] == letter:
26 | # age_dictionary[person] = kwargs[letter]
27 | #
28 | # return '\n'.join([f'{name} is {age} years old.' for name, age in sorted(age_dictionary.items())])
29 | #
30 | #
31 | # ''' TESTS '''
32 | # # print(age_assignment("Peter", "George", G=26, P=19))
33 | # # print(age_assignment("Amy", "Bill", "Willy", W=36, A=22, B=61))
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Exercise/09. Recursion Palindrome.py:
--------------------------------------------------------------------------------
1 | def palindrome(word, index):
2 |
3 | if index == len(word) // 2:
4 | return f"{word} is a palindrome"
5 |
6 | if word[index] == word[-index - 1]:
7 | return palindrome(word, index + 1)
8 |
9 | else:
10 | return f"{word} is not a palindrome"
11 |
12 |
13 | ''' TESTS '''
14 | # print(palindrome("abcba", 0))
15 | # print(palindrome("peter", 0))
16 |
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Exercise/10. Fill the Box.py:
--------------------------------------------------------------------------------
1 | def fill_the_box(*args):
2 | height, length, width, *data = args
3 | size_of_the_box = height * length * width
4 | no_free_space = 0
5 |
6 | for symbol in data:
7 |
8 | if symbol == "Finish":
9 | break
10 |
11 | if size_of_the_box - symbol <= 0:
12 | symbol -= size_of_the_box
13 | size_of_the_box = 0
14 |
15 | if size_of_the_box > 0:
16 | size_of_the_box -= symbol
17 |
18 | else:
19 | no_free_space += symbol
20 |
21 | if size_of_the_box > 0:
22 | return f"There is free space in the box. You could put {size_of_the_box} more cubes."
23 |
24 | return f"No more free space! You have {no_free_space} more cubes."
25 |
26 |
27 | ''' TESTS '''
28 | # print(fill_the_box(2, 8, 2, 2, 1, 7, 3, 1, 5, "Finish"))
29 | # print(fill_the_box(5, 5, 2, 40, 11, 7, 3, 1, 5, "Finish"))
30 | # print(fill_the_box(10, 10, 10, 40, "Finish", 2, 15, 30))
31 |
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Exercise/11. Math Operations.py:
--------------------------------------------------------------------------------
1 | def math_operations(*args, **kwargs):
2 | result, pos = "", 1
3 |
4 | for num in args:
5 |
6 | if pos == 1:
7 | kwargs["a"] += num
8 |
9 | elif pos == 4:
10 | kwargs["m"] *= num
11 |
12 | elif pos == 2:
13 | kwargs["s"] -= num
14 |
15 | elif pos == 3:
16 |
17 | if num != 0:
18 | kwargs["d"] /= num
19 |
20 | pos += 1
21 |
22 | if pos > 4:
23 | pos = 1
24 |
25 | for key, value in sorted(kwargs.items(), key=lambda x: (-x[1], x[0])):
26 | result += f"{key}: {value:.1f}\n"
27 |
28 | return result
29 |
30 |
31 | ''' TESTS '''
32 | # print(math_operations(2.1, 12.56, 0.0, -3.899, 6.0, -20.65, a=1, s=7, d=33, m=15))
33 | # print(math_operations(-1.0, 0.5, 1.6, 0.5, 6.1, -2.8, 80.0, a=0, s=(-2.3), d=0, m=0))
34 | # print(math_operations(6.0, a=0, s=0, d=5, m=0))
35 |
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Lab/01. Multiplication Function.py:
--------------------------------------------------------------------------------
1 | def multiply(*args):
2 | '''
3 | This is a simple multiplication function that
4 | gets multiple elements and returns their multiplication sum
5 | '''
6 |
7 | result = 1 # result is set to one, because we do multiplication, and anything multiplied by 0 equals 0.
8 |
9 | for item in args:
10 |
11 | if type(item) is int:
12 |
13 | result *= item
14 |
15 | return result
16 |
17 |
18 | ''' No string tests '''
19 |
20 | # print(multiply(1, 4, 5))
21 | # print(multiply(4, 5, 6, 1, 3))
22 | # print(multiply(2, 0, 1000, 5000))
23 |
24 | ''' String tests '''
25 |
26 | # print(multiply(1, "Henry", 45))
27 | # print(multiply("First", "class"))
28 | # print(multiply())
29 |
30 |
31 |
32 | # def multiply(*args):
33 | # result = args[0]
34 | # for num in args[1:]:
35 | # result *= num
36 | # return result
37 | #
38 | #
39 | # ''' TESTS '''
40 | # # print(multiply(1, 4, 5))
41 | # # print(multiply(4, 5, 6, 1, 3))
42 | # # print(multiply(2, 0, 1000, 5000))
43 |
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Lab/02. Person Info.py:
--------------------------------------------------------------------------------
1 | def get_info(name, town, age, **kwargs):
2 | return f"This is {name} from {town} and he is {age} years old"
3 |
4 |
5 | # print(get_info(**{"name": "George", "town": "Sofia", "age": 20}))
6 |
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Lab/03. Cheese Showcase.py:
--------------------------------------------------------------------------------
1 | def sorting_cheeses(**kwargs):
2 |
3 | '''
4 |
5 | The function receives a dictionary with cheeses as keys and lists of pieces as values.
6 | We should return the cheeses and their pieces' as quantities sorted by the number of pieces
7 | of a cheese kind in descending order. If two or more cheeses have the same number of pieces,
8 | we should sort them by their names in ascending order (alphabetically).
9 | For each kind of cheese, we return their pieces quantities in descending order.
10 |
11 | '''
12 |
13 | sorted_cheeses = sorted(kwargs.items(), key=lambda x: (-len(x[1]), x[0]))
14 |
15 | cheeses = []
16 |
17 | for cheese, pieces_count in sorted_cheeses:
18 | cheeses.append(cheese)
19 | quantities = sorted(pieces_count, reverse=True)
20 | cheeses += quantities
21 |
22 | return '\n'.join([str(cheese) for cheese in cheeses])
23 |
24 |
25 | # print('---- Documentation ----')
26 | # print(sorting_cheeses.__doc__)
27 | # print()
28 | # print('---- Tests ----')
29 | # print()
30 | # print(
31 | # sorting_cheeses(
32 | # Parmesan=[102, 120, 135],
33 | # Camembert=[100, 100, 105, 500, 430],
34 | # Mozzarella=[50, 125],
35 | # )
36 | # )
37 | # print()
38 | # print(
39 | # sorting_cheeses(
40 | # Parmigiano=[165, 215],
41 | # Feta=[150, 515],
42 | # Brie=[150, 125]
43 | # )
44 | # )
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Lab/04. Rectangle.py:
--------------------------------------------------------------------------------
1 | def rectangle(length, width):
2 | if type(length) is not int or type(width) is not int:
3 | return "Enter valid values!"
4 |
5 | def area():
6 | return length * width
7 |
8 | def perimeter():
9 | return length * 2 + width * 2
10 |
11 | return f"Rectangle area: {area()}\nRectangle perimeter: {perimeter()}"
12 |
13 |
14 | # print(rectangle(2, 10))
15 | # print(rectangle('2', 10))
--------------------------------------------------------------------------------
/Advanced/3.Functions Advanced/Functions Advanced - Lab/06. Recursive Power.py:
--------------------------------------------------------------------------------
1 | def recursive_power(number, power):
2 | if power == 1:
3 | return number
4 | return number * recursive_power(number, power - 1)
5 |
6 |
7 | ''' --- Tests --- '''
8 | # print(recursive_power(2, 10))
9 | # print(recursive_power(10, 100))
10 |
11 |
12 |
13 | ''' ANOTHER WAY '''
14 | # def recursive_power(number, power):
15 | # if power == 0:
16 | # return 1
17 | # return number * recursive_power(number, power - 1)
18 |
19 |
20 |
21 | # ''' Without recurse '''
22 | # def recursive_power(number, power):
23 | # return number ** power
24 |
25 |
26 | # ''' --- Tests --- '''
27 | # print(recursive_power(2, 10))
28 | # print(recursive_power(10, 100))
--------------------------------------------------------------------------------
/Advanced/4.Error Handling/Error Handling - Exercise/01. Numbers Dictionary.py:
--------------------------------------------------------------------------------
1 | numbers_dictionary = {}
2 |
3 | line = input()
4 |
5 | while line != "Search":
6 | try:
7 |
8 | number_as_string = line
9 | number = int(input())
10 | numbers_dictionary[number_as_string] = number
11 |
12 | except ValueError:
13 | print("The variable number must be an integer")
14 |
15 | line = input()
16 |
17 | line = input()
18 |
19 | while line != "Remove":
20 | try:
21 |
22 | searched = line
23 | print(numbers_dictionary[searched])
24 |
25 | except KeyError:
26 | print("Number does not exist in dictionary" )
27 |
28 | line = input()
29 |
30 | line = input()
31 |
32 | while line != "End":
33 | try:
34 |
35 | searched = line
36 | del numbers_dictionary[searched]
37 |
38 | except KeyError:
39 | print("Number does not exist in dictionary")
40 |
41 | line = input()
42 |
43 | print(numbers_dictionary)
44 |
45 |
46 |
47 | ''' Error Code '''
48 | # numbers_dictionary = {}
49 | #
50 | # line = input()
51 | #
52 | # while line != "Search":
53 | # number_as_string = line
54 | # number = int(input())
55 | # numbers_dictionary[number_as_string] = number
56 | #
57 | # line = input()
58 | #
59 | # while line != "Remove":
60 | # searched = line
61 | # print(numbers_dictionary[searched])
62 | #
63 | # line = input()
64 | #
65 | # while line != "End":
66 | # searched = line
67 | # del numbers_dictionary[searched]
68 | #
69 | # print(numbers_dictionary)
--------------------------------------------------------------------------------
/Advanced/4.Error Handling/Error Handling - Exercise/02. Email Validator.py:
--------------------------------------------------------------------------------
1 | class NameTooShortError(Exception):
2 | """ Name less than or equal to 4 characters"""
3 | pass
4 |
5 |
6 | class MustContainAtSymbolError(Exception):
7 | ''' Email does not have @ '''
8 | pass
9 |
10 |
11 | class InvalidDomainError(Exception):
12 | ''' the domain is different than .com, .org... '''
13 | pass
14 |
15 |
16 | email = input()
17 | while email != "End":
18 | good_email = True
19 |
20 | if '@' in email:
21 | if len(email.split('@')[0]) <= 4:
22 | good_email = False
23 | raise NameTooShortError("Name must be more than 4 characters")
24 |
25 | else:
26 | good_email = False
27 | raise MustContainAtSymbolError("Email must contain @")
28 |
29 | if email.split('.')[-1] not in ['com', 'bg', 'org', 'net']:
30 | good_email = False
31 | raise InvalidDomainError("Domain must be one of the following: .com, .bg, .org, .net")
32 |
33 | if good_email:
34 | print("Email is valid")
35 |
36 | email = input()
--------------------------------------------------------------------------------
/Advanced/4.Error Handling/Error Handling - Lab/01. So Many Exceptions.py:
--------------------------------------------------------------------------------
1 | numbers_list = input().split(", ")
2 | result = 1
3 |
4 | for i in range(len(numbers_list)):
5 | number = int(numbers_list[i])
6 | if number <= 5:
7 | result *= number
8 | elif 5 < number <= 10:
9 | result /= number
10 |
11 | print(result)
12 |
13 |
14 | ''' Error Code '''
15 | # numbers_list = int(input()).split(", ")
16 | # result = 1
17 | #
18 | # for i in range(numbers_list):
19 | # number = numbers_list[i + 1]
20 | # if number <= 5
21 | # result *= number
22 | # elif 5 < number <= 10:
23 | # result /= number
24 | #
25 | # print(total)
26 |
27 |
28 |
29 |
30 |
31 |
32 | ''' OLD LAB '''
33 | # numbers_list = input().split(", ")
34 | # result = 1
35 | #
36 | # for index in range(len(numbers_list)):
37 | # number = int(numbers_list[index])
38 | # if number <= 5:
39 | # result *= number
40 | # elif 5 < number <= 10:
41 | # result /= number
42 | #
43 | # print(result)
44 | #
45 | #
46 | # ''' Error Code '''
47 | # # numbers_list = input().split(", ")
48 | # # result = 0
49 | # #
50 | # # for i in range(numbers_list):
51 | # # number = numbers_list[i + 1]
52 | # # if number < 5:
53 | # # result *= number
54 | # # elif number > 5 and number > 10:
55 | # # result /= number
56 | # #
57 | # # print(result)
--------------------------------------------------------------------------------
/Advanced/4.Error Handling/Error Handling - Lab/02. Repeat Text.py:
--------------------------------------------------------------------------------
1 | try:
2 |
3 | text = input()
4 | times = int(input())
5 | print(text * times)
6 |
7 | except ValueError:
8 | print("Variable times must be an integer")
--------------------------------------------------------------------------------
/Advanced/4.Error Handling/Error Handling - Lab/03. Value Cannot Be Negative.py:
--------------------------------------------------------------------------------
1 | class ValueCannotBeNegative(Exception):
2 | pass
3 |
4 |
5 | for _ in range(5):
6 | num = int(input())
7 | if num < 0:
8 | raise ValueCannotBeNegative
9 |
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/01. Even Lines/01. Even Lines.py:
--------------------------------------------------------------------------------
1 | def read_text():
2 |
3 | try:
4 |
5 | file = open("text.txt", "r")
6 | lines = [line for line in file] # Getting every line on different index
7 | file.close()
8 | return lines
9 |
10 | except FileNotFoundError:
11 | raise FileNotFoundError("File not found")
12 |
13 |
14 | def get_even_lines(text):
15 | even_lines = []
16 | for line in range(len(text)):
17 | if line % 2 == 0:
18 | even_lines.append(text[line]) # getting only the lines at even indexes
19 | return even_lines
20 |
21 |
22 | def change_symbol(text):
23 | change_symbols = {"-", ",", ".", "!", "?"} # symbols that must be changed to @
24 |
25 | for line in range(len(text)):
26 | for char in range(len(text[line])):
27 | if text[line][char] in change_symbols:
28 | text[line] = text[line][0:char] + '@' + text[line][char+1:]
29 |
30 |
31 | def print_result(text):
32 | for line in text:
33 | sentence = line.split()[::-1] # reversing the result, without reversing the words.
34 | # Example:
35 | # >>> line = 'some text'
36 | # >>> line[::-1] -> 'txet emos'
37 | # >>> line.split()[::-1] -> ['text', 'some']
38 | # >>> ' '.join(line) -> 'text some'
39 | print(' '.join(sentence))
40 |
41 |
42 | text = read_text()
43 | even_lines = get_even_lines(text)
44 |
45 | if __name__ == '__main__':
46 | change_symbol(even_lines)
47 | print_result(even_lines)
48 |
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/01. Even Lines/text.txt:
--------------------------------------------------------------------------------
1 | -I was quick to judge him, but it wasn't his fault.
2 | -Is this some kind of joke?! Is it?
3 | -Quick, hide here. It is safer.
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/02. Line Numbers/02. Line Numbers.py:
--------------------------------------------------------------------------------
1 | def read_text():
2 |
3 | try:
4 |
5 | file = open("text.txt", "r")
6 | lines = [line for line in file] # getting every line from the text
7 | file.close()
8 |
9 | except FileNotFoundError:
10 | raise FileNotFoundError("File not found")
11 |
12 | for line in range(len(lines)):
13 |
14 | letters = 0
15 | punctuation_marks = 0
16 |
17 | for character in range(len(lines[line])):
18 |
19 | char = lines[line][character]
20 |
21 | if 65 <= ord(char) <= 90 or 97 <= ord(char) <= 122: # if char is letter
22 | letters += 1
23 |
24 | elif 33 <= ord(char) <= 47 or 58 <= ord(char) <= 64: # if char is punctuation mark
25 | punctuation_marks += 1
26 |
27 | if lines[line][-1] == '\n': # if the sentence ends with '\n' which stands for new line.
28 | lines[line] = lines[line][:-1] # We remove it, because otherwise it would give us wrong output
29 |
30 | lines[line] = f"Line {line+1}: {lines[line]} ({letters})({punctuation_marks})\n"
31 |
32 | return lines
33 |
34 |
35 | def output_txt(text):
36 |
37 | file = open("output.txt", "w") # create for writing
38 | [file.write(line) for line in text] # write the output in
39 | file.close() # close for writing
40 |
41 | file = open("output.txt", "r") # open for reading
42 | output = ''.join([line for line in file]) # read every line from the text
43 | file.close() # close file for reading
44 |
45 | return output
46 |
47 |
48 | text = read_text()
49 | print(output_txt(text))
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/02. Line Numbers/text.txt:
--------------------------------------------------------------------------------
1 | -I was quick to judge him, but it wasn't his fault.
2 | -Is this some kind of joke?! Is it?
3 | -Quick, hide here. It is safer.
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/04. Directory Traversal/04. Directory Traversal.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 |
4 | def get_files():
5 |
6 | if os.path.exists("directory/report.txt"): # Making sure, on second run, the report won't count itself
7 | os.remove("directory/report.txt")
8 |
9 | if os.path.exists("report.txt"): # Making sure, on second run, the report won't count itself
10 | os.remove("report.txt")
11 |
12 | path = "directory" # path
13 | files = os.listdir(path) # files in path/directory
14 |
15 | return files
16 |
17 |
18 | def sort_files(files):
19 |
20 | # sort files and extensions
21 | extensions = set()
22 | for file_extension in files:
23 | extension = file_extension.split(".")[-1] # extension. Example: html
24 | extensions.add(f".{extension}") # extension with dot. Example: .html
25 |
26 | sorted_files = sorted(files) # -> list
27 | sorted_extensions = sorted(extensions) # -> list
28 |
29 | # create report.txt
30 | file1 = open("report.txt", "a+") # creating report 1
31 | file2 = open("directory/report.txt", "a+") # creating report 2
32 |
33 | # combine file with extension
34 | for extension in sorted_extensions:
35 | file1.write(f"{extension}\n")
36 | file2.write(f"{extension}\n")
37 |
38 | for file in sorted_files:
39 | if extension in file:
40 | file1.write(f"- - - {file}\n")
41 | file2.write(f"- - - {file}\n")
42 |
43 | # closing opened files
44 | file1.close()
45 | file2.close()
46 |
47 | return "The result from the program is saved in report.txt"
48 |
49 |
50 | files = get_files()
51 | print(sort_files(files))
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/04. Directory Traversal/directory/demo.pptx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/5.File Handling/File Handling - Exercise/04. Directory Traversal/directory/demo.pptx
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/04. Directory Traversal/directory/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | You're in my world now
6 |
7 |
8 |
9 |
10 |
Click Me
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/04. Directory Traversal/directory/index.js:
--------------------------------------------------------------------------------
1 | function ChangeColor() {
2 | document.getElementById("main").style.color = "purple";
3 | }
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/04. Directory Traversal/directory/log.txt:
--------------------------------------------------------------------------------
1 | log _> pip install ME
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/04. Directory Traversal/directory/my_personal_favorite.py:
--------------------------------------------------------------------------------
1 | "HEllO WORLD!"
2 | print("Please give me good grade!")
3 | print("Love <3 :)")
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/04. Directory Traversal/directory/notes.txt:
--------------------------------------------------------------------------------
1 | # create a directory with files
2 |
3 | 2nd. # Make code :)
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/04. Directory Traversal/directory/program.py:
--------------------------------------------------------------------------------
1 | print("I'm a Python Program")
2 | print("It's nice to meet you!")
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Exercise/04. Directory Traversal/directory/python.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 | from time import sleep
3 |
4 | rows, columns = 10, 3
5 | snake = "Python"
6 |
7 | while True:
8 |
9 | index_snake = 0
10 |
11 | for row in range(rows):
12 |
13 | result = deque()
14 |
15 | for col in range(columns):
16 |
17 | if index_snake == len(snake):
18 | index_snake = 0
19 |
20 | if row % 2 == 0:
21 | result.append(snake[index_snake])
22 |
23 | else:
24 | result.appendleft(snake[index_snake])
25 |
26 | index_snake += 1
27 |
28 | print("".join(result))
29 | sleep(0.1)
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Lab/01. File Opener/01. File Opener.py:
--------------------------------------------------------------------------------
1 | try:
2 |
3 | file = open("text.txt", 'r')
4 | print("File found")
5 |
6 | except FileNotFoundError:
7 | print("File not found")
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Lab/01. File Opener/text.txt:
--------------------------------------------------------------------------------
1 | This is some random line
2 | This is the second line
3 | And this is the third one
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Lab/02. File Reader/02. File Reader.py:
--------------------------------------------------------------------------------
1 | try:
2 |
3 | file = open("numbers.txt")
4 | print(sum([int(num) for num in file]))
5 |
6 | except ValueError:
7 | print("String cannot be summed")
8 |
9 | except FileNotFoundError:
10 | print("File not found")
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Lab/02. File Reader/numbers.txt:
--------------------------------------------------------------------------------
1 | 1
2 | 2
3 | 3
4 | 4
5 | 5
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Lab/03. File Writer/03. File Writer.py:
--------------------------------------------------------------------------------
1 | with open("my_first_file.txt", "w") as file:
2 | file.write("I just created my first file!")
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Lab/03. File Writer/my_first_file.txt:
--------------------------------------------------------------------------------
1 | # This file does not exist, it is created by the code.
2 |
3 | I just created my first file!
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Lab/04. File Delete/04. File Delete.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | try:
4 | os.remove("my_first_file.txt")
5 | except FileNotFoundError:
6 | print("File already deleted!")
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Lab/04. File Delete/my_first_file.txt:
--------------------------------------------------------------------------------
1 | I just created my first file!
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Lab/05. Word Count/05. Word Count.py:
--------------------------------------------------------------------------------
1 | words = list([word.lower().split() for word in open("words.txt")][0])
2 |
3 | words_count = {}
4 |
5 | file = open("text.txt", "w")
6 |
7 | line = input()
8 | while line:
9 | file.write(f"{line.lower()}\n")
10 | line = input()
11 |
12 | file.close()
13 |
14 | text = list([word for word in open("text.txt", "r")])
15 |
16 | for word in words:
17 |
18 | alts = [f'{word}.', f'{word},', f'-{word}', f'-{word},', f'-{word}.']
19 |
20 | for sentence in text:
21 |
22 | if word in sentence.split() or alts[0] in sentence.split() or alts[1] in sentence.split() or alts[2] in \
23 | sentence.split() or alts[3] in sentence.split() or alts[4] in sentence.split():
24 |
25 | if word not in words_count:
26 |
27 | words_count[word] = sentence.split().count(word) + sentence.count(alts[0]) + \
28 | sentence.count(alts[1]) + sentence.count(alts[2]) + sentence.count(alts[3]) + \
29 | sentence.count(alts[4])
30 | continue
31 | words_count[word] += sentence.split().count(word) + sentence.count(alts[0]) + \
32 | sentence.count(alts[1]) + sentence.count(alts[4])
33 |
34 | sorted_result = sorted(words_count.items(), key=lambda x: -x[1])
35 |
36 | result = open("result.txt", "w")
37 |
38 | for word, count in sorted_result:
39 | result.write(f"{word} - {count}\n")
40 |
41 | result.close()
42 |
43 | show_result = list([word for word in open("result.txt", "r")])
44 |
45 | print(''.join(show_result))
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Lab/05. Word Count/result.txt:
--------------------------------------------------------------------------------
1 | # This file does not exist, it is created by the program.
2 |
3 |
4 | is - 3
5 | quick - 2
6 | fault - 1
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Lab/05. Word Count/text.txt:
--------------------------------------------------------------------------------
1 | # This file does not exist, it is created by the program.
2 |
3 |
4 |
5 | -i was quick to judge him, but it wasn't his fault.
6 | -is this some kind of joke?! is it?
7 | -quick, hide here�it is safer.
8 |
--------------------------------------------------------------------------------
/Advanced/5.File Handling/File Handling - Lab/05. Word Count/words.txt:
--------------------------------------------------------------------------------
1 | quick is fault
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/__pycache__/authentication.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/NEW/__pycache__/authentication.cpython-39.pyc
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/__pycache__/buying_page.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/NEW/__pycache__/buying_page.cpython-39.pyc
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/__pycache__/canvas.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/NEW/__pycache__/canvas.cpython-39.pyc
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/__pycache__/helpers.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/NEW/__pycache__/helpers.cpython-39.pyc
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/buying_page.py:
--------------------------------------------------------------------------------
1 | from json import load, dump
2 | from tkinter import Button
3 | from PIL import Image, ImageTk
4 | from canvas import frame, root
5 | from helpers import clean_screen
6 |
7 |
8 | def display_products():
9 | clean_screen()
10 | display_stock()
11 |
12 |
13 | def display_stock():
14 | global info
15 |
16 | with open("db/products_data.json", "r") as stock:
17 | info = load(stock)
18 |
19 | x, y = 150, 50
20 |
21 | for item_name, item_info in info.items():
22 | item_img = ImageTk.PhotoImage(Image.open(item_info["image"]))
23 | images.append(item_img)
24 |
25 | frame.create_text(x, y, text=item_name, font=("Comic Sans MS", 15))
26 | frame.create_image(x, y + 100, image=item_img)
27 |
28 | if item_info["quantity"] > 0:
29 | color = "green"
30 | text = f"In stock: {item_info['quantity']}"
31 |
32 | item_btn = Button(
33 | root,
34 | text="Buy",
35 | font=("Comic Sans MS", 12),
36 | bg="green",
37 | fg="white",
38 | width=5,
39 | command=lambda x=item_name: buy_product(x),
40 | )
41 |
42 | frame.create_window(x, y + 230, window=item_btn)
43 | else:
44 | color = "red"
45 | text = "Out of stock"
46 |
47 | frame.create_text(x, y + 180, text=text, font=("Comic Sans MS", 12), fill=color)
48 |
49 | x += 200
50 |
51 | if x > 550:
52 | x = 150
53 | y += 230
54 |
55 |
56 | def buy_product(product):
57 | info[product]["quantity"] -= 1
58 |
59 | with open("db/products_data.json", "w") as stock:
60 | dump(info, stock)
61 |
62 | display_products()
63 |
64 |
65 | images = []
66 | info = {}
67 |
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/canvas.py:
--------------------------------------------------------------------------------
1 | from tkinter import Tk, Canvas
2 |
3 |
4 | def create_root():
5 | root = Tk()
6 |
7 | root.title("GUI Shop")
8 | root.resizable(False, False)
9 | root.geometry("700x600")
10 |
11 | return root
12 |
13 |
14 | def create_frame():
15 | frame = Canvas(root, width=700, height=700)
16 | frame.grid(row=0, column=0)
17 |
18 | return frame
19 |
20 |
21 | root = create_root()
22 | frame = create_frame()
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/db/products_data.json:
--------------------------------------------------------------------------------
1 | {"puma blue t-shirt": {"quantity": 2, "image": "images/blue_t_shirt.png"}, "nike blue t-shirt": {"quantity": 13, "image": "images/blue_t_shirt.png"}, "jeans": {"quantity": 5, "image": "images/black_jeans.png"}, "shoes": {"quantity": 14, "image": "images/shoes.png"}}
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/db/users_information.txt:
--------------------------------------------------------------------------------
1 | {"first_name": "Dimitar", "last_name": "Dimitrov", "username": "MitkoVtori", "password": "a1fe8f79a121256842e7aaef2ab1e339a553a74fe05834ca081259cf66ac5fb5"}
2 | {"first_name": "Gogo", "last_name": "gogo", "username": "xx", "password": "2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881"}
3 |
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/helpers.py:
--------------------------------------------------------------------------------
1 | from hashlib import sha256
2 | from canvas import frame
3 |
4 |
5 | def clean_screen():
6 | frame.delete("all")
7 |
8 |
9 | def get_password_hash(password):
10 | hash_object = sha256(password.encode())
11 |
12 | return str(hash_object.hexdigest())
13 |
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/images/black_jeans.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/NEW/images/black_jeans.png
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/images/blue_t_shirt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/NEW/images/blue_t_shirt.png
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/images/shoes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/NEW/images/shoes.png
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/NEW/main.py:
--------------------------------------------------------------------------------
1 | from authentication import render_entry
2 | from canvas import root
3 |
4 |
5 | if __name__ == '__main__':
6 | render_entry()
7 | root.mainloop()
8 |
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/__pycache__/authentication.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/OLD/__pycache__/authentication.cpython-39.pyc
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/__pycache__/canvas.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/OLD/__pycache__/canvas.cpython-39.pyc
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/__pycache__/helpers.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/OLD/__pycache__/helpers.cpython-39.pyc
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/__pycache__/products.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/OLD/__pycache__/products.cpython-39.pyc
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/canvas.py:
--------------------------------------------------------------------------------
1 | from tkinter import *
2 |
3 |
4 | def create_app():
5 | tk = Tk()
6 | tk.geometry("1000x800+0+0")
7 | tk.title("GUI Product shop")
8 | return tk
9 |
10 |
11 | tk = create_app()
12 |
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/databases/current_user.txt:
--------------------------------------------------------------------------------
1 | Goshko
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/databases/products.txt:
--------------------------------------------------------------------------------
1 | {"id": 1, "name": "vscode premium", "img_path": "vscode.png", "count": 6}
2 | {"id": 2, "name": "bubble tree", "img_path": "tree.png", "count": 9}
3 |
4 | {"id": 3, "name": "LinkedIn premium", "img_path": "linkedIn.png", "count": 35}
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/databases/user_credentials_db.txt:
--------------------------------------------------------------------------------
1 | Goshko, Dimitrov
2 | Mitko, Mitkov
3 | Mitev, Mitev1
4 |
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/databases/users.txt:
--------------------------------------------------------------------------------
1 | {"username": "Goshko", "password": "Dimitrov", "first_name": "gosheto@gmail.bg", "last_name": "Gosheto123", "products": [1, 1, 2, 3, 2, 1, 2, 1, 3]}
2 | {"username": "Mitko", "password": "Mitkov", "first_name": "mitko@gmail.abv", "last_name": "somepassword123", "products": []}
3 | {"username": "Mitev", "password": "Mitev1", "first_name": "Mitko", "last_name": "Mitkov", "products": []}
4 |
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/helpers.py:
--------------------------------------------------------------------------------
1 | from canvas import tk
2 |
3 |
4 | def clean_screen():
5 | for el in tk.grid_slaves():
6 | el.destroy()
7 |
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/images/linkedIn.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/OLD/images/linkedIn.png
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/images/tree.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/OLD/images/tree.png
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/images/vscode.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Exercise/OLD/images/vscode.png
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Exercise/OLD/main.py:
--------------------------------------------------------------------------------
1 | from authentication import render_main_enter_screen
2 | from canvas import tk
3 | from products import render_products
4 |
5 |
6 | if __name__ == '__main__':
7 | render_main_enter_screen()
8 | tk.mainloop()
9 |
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Lab/01. Calculate Logarithm.py:
--------------------------------------------------------------------------------
1 | from math import log
2 |
3 | number = int(input())
4 | base = input()
5 |
6 | if base == "natural":
7 | print(f"{log(number):.2f}")
8 |
9 | else:
10 | print(f"{log(number, int(base)):.2f}")
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Lab/02. ASCII Art.py:
--------------------------------------------------------------------------------
1 | from pyfiglet import figlet_format
2 |
3 | message = input()
4 |
5 | print(figlet_format(message))
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Lab/03. Triangle.py:
--------------------------------------------------------------------------------
1 | from custom_module.triangle import triangle
2 |
3 | number = int(input())
4 | triangle(number)
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Lab/04. Mathematical Operations.py:
--------------------------------------------------------------------------------
1 | from custom_module.math_operations import *
2 |
3 | first_number, sign, second_number = input().split()
4 | first_number, second_number = float(first_number), int(second_number)
5 |
6 | operations = {
7 | "/": divide,
8 | "*": multiply,
9 | "-": subtract,
10 | "+": add,
11 | "^": raise_numbers
12 | }
13 |
14 | print(operations[sign](first_number, second_number))
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Lab/05. Fibonacci Sequence.py:
--------------------------------------------------------------------------------
1 | from custom_module.fibonacci_sequence import create_sequence, locate
2 |
3 | operations = {
4 | "Create": create_sequence,
5 | "Locate": locate
6 | }
7 |
8 | command = input()
9 | while command != "Stop":
10 |
11 | operation, *rest = command.split()
12 | print(operations[operation](int(rest[-1])))
13 |
14 | command = input()
15 |
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Lab/custom_module/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Advanced/7.Modules/Modules - Lab/custom_module/__init__.py
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Lab/custom_module/fibonacci_sequence.py:
--------------------------------------------------------------------------------
1 | sequence = [0, 1]
2 |
3 |
4 | def create_sequence(number):
5 | global sequence
6 |
7 | if number == 0:
8 | sequence = []
9 |
10 | elif number == 1:
11 | sequence = [0]
12 |
13 | else:
14 |
15 | sequence = [0, 1]
16 |
17 | for _ in range(2, number):
18 | sequence.append(sequence[-1] + sequence[-2])
19 |
20 | return ' '.join([str(num) for num in sequence])
21 |
22 |
23 | def locate(x):
24 |
25 | if x in sequence:
26 | return f"The number - {x} is at index {sequence.index(x)}"
27 | return f"The number {x} is not in the sequence"
28 |
29 |
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Lab/custom_module/math_operations.py:
--------------------------------------------------------------------------------
1 | def divide(first_num, second_num):
2 | return f"{first_num / second_num:.2f}"
3 |
4 |
5 | def multiply(first_num, second_num):
6 | return f"{first_num * second_num:.2f}"
7 |
8 |
9 | def subtract(first_num, second_num):
10 | return f"{first_num - second_num:.2f}"
11 |
12 |
13 | def add(first_num, second_num):
14 | return f"{first_num + second_num:.2f}"
15 |
16 |
17 | def raise_numbers(first_num, second_num):
18 | return f"{first_num ** second_num:.2f}"
19 |
20 |
--------------------------------------------------------------------------------
/Advanced/7.Modules/Modules - Lab/custom_module/triangle.py:
--------------------------------------------------------------------------------
1 | def triangle(number):
2 | for row in range(1, number + 2):
3 | result = []
4 |
5 | for num in range(1, row):
6 | result.append(str(num))
7 |
8 | print(' '.join(result))
9 |
10 | for row in range(number, 0, -1):
11 | result = []
12 |
13 | for num in range(1, row):
14 | result.append(str(num))
15 |
16 | print(' '.join(result))
--------------------------------------------------------------------------------
/Errors.py:
--------------------------------------------------------------------------------
1 | class TooManyInvalidTriesError(Exception):
2 | pass
3 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(1) Basic Syntax, Conditional Statement and Loops/10. Mutate Strings.py:
--------------------------------------------------------------------------------
1 | first_string = input()
2 | second_string = input()
3 | last_string = first_string
4 | for symbol in range(len(second_string)):
5 | left_string = second_string[:symbol + 1]
6 | right_string = first_string[symbol + 1:]
7 | curr_word = left_string + right_string
8 | if curr_word == last_string:
9 | continue
10 | print(curr_word)
11 | last_string = curr_word
12 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(1) Basic Syntax, Conditional Statement and Loops/11. Easter Bread.py:
--------------------------------------------------------------------------------
1 | budget = float(input())
2 | flour_1kg = float(input())
3 | one_pack_eggs = flour_1kg * 0.75
4 | milk = ((flour_1kg * 0.25) + flour_1kg) * 0.25
5 | total = flour_1kg + one_pack_eggs + milk
6 | curr_bread_cnt = 0
7 | colored_eggs = 0
8 |
9 | while budget >= total:
10 | curr_bread_cnt += 1
11 | budget -= total
12 | colored_eggs += 3
13 | if curr_bread_cnt % 3 == 0:
14 | colored_eggs -= (curr_bread_cnt - 2)
15 |
16 | print(f"You made {curr_bread_cnt} loaves of Easter bread! Now you have {colored_eggs} eggs and {budget:.2f}BGN left.")
17 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(1) Basic Syntax, Conditional Statement and Loops/12. Christmas Spirit.py:
--------------------------------------------------------------------------------
1 | quantity = int(input())
2 | days = int(input())
3 |
4 | ornament_set = 2
5 | tree_skirt = 5
6 | tree_garlands = 3
7 | tree_lights = 15
8 |
9 | christmas_spirit = 0
10 | budget = 0
11 |
12 | for day in range(1, days + 1):
13 | if day % 11 == 0:
14 | quantity += 2
15 |
16 | if day % 10 == 0:
17 | christmas_spirit -= 20
18 | budget += tree_skirt + tree_lights + tree_garlands
19 |
20 | if day == days:
21 | christmas_spirit -= 30
22 |
23 | if day % 5 == 0:
24 | christmas_spirit += 17
25 | budget += tree_lights * quantity
26 |
27 | if day % 15 == 0:
28 | christmas_spirit += 30 # fifth day with garlands
29 |
30 | if day % 3 == 0:
31 | christmas_spirit += 13
32 | budget += (tree_garlands + tree_skirt) * quantity
33 |
34 | if day % 2 == 0:
35 | christmas_spirit += 5
36 | budget += ornament_set * quantity
37 |
38 | print(f"Total cost: {budget}")
39 | print(f"Total spirit: {christmas_spirit}")
40 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(2) Data Types and Variables/08. Party Profit.py:
--------------------------------------------------------------------------------
1 | companions = int(input())
2 | days_adventure = int(input())
3 | coins = 0
4 |
5 | for day in range(1, days_adventure + 1):
6 | # Every 10th (tenth) day at the start of the day, 2 (two) of your companions leave.
7 | if day % 10 == 0:
8 | companions -= 2
9 | # Every 15th (fifteenth) day 5 (five) new companions are joined at the beginning of the day
10 | if day % 15 == 0:
11 | companions += 5
12 |
13 | # Every day, you earn 50 coins, but you also spend 2 coins per companion for food.
14 | coins += (50 - (2 * companions))
15 |
16 | # Every 3rd (third) day, you organize a motivational party, spending 3 coins per companion for drinking water.
17 | if day % 3 == 0:
18 | coins -= (3 * companions)
19 | # Every 5th (fifth) day, you slay a boss monster and gain 20 coins per companion.
20 | # But if you have a motivational party the same day, you spend additional 2 coins per companion.
21 | if day % 5 == 0:
22 |
23 | coins += (20 * companions)
24 |
25 | if day % 3 == 0:
26 | coins -= (2 * companions)
27 |
28 | coins_per_companion = int(coins / companions)
29 | print(f"{companions} companions received {coins_per_companion} coins each.")
30 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(2) Data Types and Variables/09. Snowballs.py:
--------------------------------------------------------------------------------
1 | # First we check how many snowballs we have.
2 | snowballs = int(input())
3 | max_snowball_weight = 0
4 | max_snowball_time = 0
5 | max_value = 0
6 | max_quality = 0
7 |
8 | # After that we check which is better.
9 | for snowball in range(snowballs):
10 | # Here we check the weight of the snowball.
11 | snowball_weight = int(input())
12 | # Here we check the time needed for the snowball to get to its target.
13 | snowball_time = int(input())
14 | # Here we check the quality of the snowball.
15 | quality = int(input())
16 | # Here we calculate its value by the following formula.
17 | value = (snowball_weight / snowball_time) ** quality
18 | # Here we record the weight, speed, quality and value of the best snowball.
19 | if value > max_value:
20 | max_snowball_weight = snowball_weight
21 | max_snowball_time = snowball_time
22 | max_value = value
23 | max_quality = quality
24 | # And finally, we print the record of the best snowball.
25 | print(f"{max_snowball_weight} : {max_snowball_time} = {max_value:.0f} ({max_quality})")
26 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(2) Data Types and Variables/10. Gladiator Expenses.py:
--------------------------------------------------------------------------------
1 | # We have a fighter, here we see how much lost fights he has.
2 | lost_fights_count = int(input())
3 | helmet_price = float(input())
4 | sword_price = float(input())
5 | shield_price = float(input())
6 | armor_price = float(input())
7 | # Here we count how many times he broke his shield.
8 | shield_broken = 0
9 | # These are our equipment costs.
10 | expenses = 0
11 |
12 | for lost in range(1, lost_fights_count + 1):
13 | # Every second lost game, his helmet is broken.
14 | if lost % 2 == 0:
15 | expenses += helmet_price
16 |
17 | # Every third lost game, his sword is broken.
18 | if lost % 3 == 0:
19 | expenses += sword_price
20 |
21 | # When both his sword and helmet are broken in the same lost fight, his shield also breaks.
22 | if lost % 2 == 0 and lost % 3 == 0:
23 | shield_broken += 1
24 | expenses += shield_price
25 |
26 | # Every second time his shield brakes, his armor also needs to be repaired.
27 | if shield_broken % 2 == 0:
28 | expenses += armor_price
29 |
30 | # Finally, we print the expenses.
31 | print(f"Gladiator expenses: {expenses:.2f} aureus")
32 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(3) Lists Basics/07. Easter Gifts.py:
--------------------------------------------------------------------------------
1 | gifts = input().split(' ')
2 |
3 | command = input().split(' ')
4 | while command[0] != 'No' and command[1] != 'Money':
5 | index = 0
6 | if command[0] == 'OutOfStock':
7 | gift = command[1]
8 | gifts = list(map(lambda lst: lst.replace(gift, "None"), gifts))
9 |
10 | elif command[0] == 'Required':
11 | index = int(command[2])
12 | if 0 < index < len(gifts):
13 | gifts[index] = command[1]
14 |
15 | elif command[0] == 'JustInCase':
16 | gifts[-1] = command[1]
17 |
18 | command = input().split(' ')
19 |
20 | while 'None' in gifts:
21 | gifts.remove('None')
22 |
23 | for i in gifts:
24 | print(i, end=' ')
25 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(3) Lists Basics/08. Seize the Fire.py:
--------------------------------------------------------------------------------
1 | fires = input().split("#")
2 | water = int(input())
3 |
4 | effort = 0
5 | total_fire = 0
6 | put_out_cells = []
7 |
8 | print("Cells:")
9 |
10 | for fire in fires:
11 | args = fire.split(" = ")
12 | fire_type = args[0]
13 | level = int(args[1])
14 | valid = False
15 |
16 | if water < level:
17 | continue
18 |
19 | if fire_type == 'High':
20 | if 81 <= level <= 125:
21 | valid = True
22 | elif fire_type == 'Medium':
23 | if 51 <= level <= 80:
24 | valid = True
25 | elif fire_type == 'Low':
26 | if 1 <= level <= 50:
27 | valid = True
28 |
29 | if valid:
30 | put_out_cells.append(level)
31 | water -= level
32 | effort += level * 0.25
33 | total_fire += level
34 |
35 |
36 | for cell in put_out_cells:
37 | print(f' - {cell}')
38 |
39 | print(f'Effort: {effort:.2f}')
40 | print(f'Total Fire: {total_fire}')
41 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(3) Lists Basics/09. Hello, France.py:
--------------------------------------------------------------------------------
1 | items = input().split("|")
2 | budget = float(input())
3 | bought = list()
4 | profit = 0
5 |
6 | for item in items:
7 | indx = item.split('->')
8 | clothes = indx[0]
9 | price = float(indx[1])
10 |
11 | accepted = False
12 |
13 | if price > budget:
14 | continue
15 |
16 | if clothes == 'Clothes':
17 | if price <= 50.00:
18 | budget -= price
19 | accepted = True
20 | elif clothes == 'Shoes':
21 | if price <= 35.00:
22 | budget -= price
23 | accepted = True
24 | elif clothes == 'Accessories':
25 | if price <= 20.50:
26 | budget -= price
27 | accepted = True
28 | if accepted:
29 | res = float("{:.2f}".format(price * 1.40))
30 | bought.append(price * 1.40)
31 | profit += (price * 1.40) - price
32 |
33 | for elem in bought:
34 | budget += elem
35 |
36 |
37 | def l_to_s(s):
38 | string_one = ''
39 | for element in s:
40 | string_one += "{:.2f}".format(element) + " "
41 | return string_one
42 |
43 |
44 | print(l_to_s(bought))
45 | print(f'Profit: {profit:.2f}')
46 |
47 | if budget >= 150:
48 | print('Hello, France!')
49 | else:
50 | print('Not enough money.')
51 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(3) Lists Basics/10. Bread Factory/10. Bread Factory.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | entrance = input().split("|")
4 |
5 | energy = 100
6 | coins = 100
7 |
8 | for event in entrance:
9 | split = event.split("-")
10 |
11 | if split[0] == "rest":
12 | energy_from = int(split[1])
13 |
14 | if 100 - energy < energy_from:
15 | energy_from = 100 - energy
16 |
17 | energy += energy_from
18 | print(f"You gained {energy_from} energy.")
19 | print(f"Current energy: {energy}.")
20 | elif split[0] == "order":
21 | earn = int(split[1])
22 |
23 | if energy >= 30:
24 | coins += earn
25 | energy -= 30
26 | print(f"You earned {earn} coins.")
27 | else:
28 | energy += 50
29 | print("You had to rest!")
30 | else:
31 | expense = int(split[1])
32 | if coins >= expense:
33 | print(f"You bought {str(split[0])}.")
34 | coins -= expense
35 | else:
36 | print(f"Closed! Cannot afford {str(split[0])}.")
37 | sys.exit()
38 |
39 | print("Day completed!")
40 | print(f"Coins: {coins}")
41 | print(f"Energy: {energy}")
42 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(3) Lists Basics/10. Bread Factory/fails.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Fundamentals/(A) Not Included In Final Score - Exercise/(3) Lists Basics/10. Bread Factory/fails.png
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(4) Functions/11. Loading Bar.py:
--------------------------------------------------------------------------------
1 | def loading_bar(percent):
2 | if percent == 100:
3 | return f"100% Complete!\n[{'%' * 10}]"
4 | return f"{percent}% [{'%' * (percent // 10)}{'.' * (10 - percent // 10)}]\nStill loading..."
5 |
6 |
7 | loading_percent = int(input())
8 | print(loading_bar(loading_percent))
9 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(4) Functions/12. Factorial Division.py:
--------------------------------------------------------------------------------
1 | def factorial_division(first: int, second: int):
2 | for factorial in range(1, first):
3 | first *= factorial
4 | for factorial in range(1, second):
5 | second *= factorial
6 | division = first / second
7 | return f'{division:.2f}'
8 |
9 |
10 | first_number = int(input())
11 | second_number = int(input())
12 | print(factorial_division(first_number, second_number))
13 |
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(5) Lists Advanced/09. Anonymous Threat.py:
--------------------------------------------------------------------------------
1 | def merge(virus, command):
2 |
3 | first_index = int(command[1])
4 | second_index = int(command[-1])
5 |
6 | if first_index < 0:
7 | first_index = 0
8 | if first_index < second_index:
9 | length = len(virus)
10 | if second_index >= length:
11 | second_index = length - 1
12 | for num in range(first_index, second_index):
13 | virus[first_index] += f"{virus.pop(first_index + 1)}"
14 |
15 |
16 | def divide(virus):
17 |
18 | first_index = int(command[1])
19 | second_index = int(command[-1])
20 |
21 | length = len(virus[first_index])
22 | space_between = length // second_index
23 | string_to_change = virus.pop(first_index)
24 | result = []
25 | for end in range(second_index - 1):
26 | result.append(string_to_change[:space_between])
27 | string_to_change = string_to_change[space_between:]
28 | result.append(string_to_change)
29 | for end in result[::-1]:
30 | virus.insert(first_index, end)
31 |
32 |
33 | strings = input().split(' ')
34 | while True:
35 | command = input().split(' ')
36 |
37 | if command[0] == '3:1':
38 | break
39 |
40 | if command[0] == "merge":
41 | merge(strings, command)
42 |
43 | elif command[0] == 'divide':
44 | divide(strings)
45 |
46 | print(' '.join(strings))
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(5) Lists Advanced/10. Pokemon Don't Go.py:
--------------------------------------------------------------------------------
1 | distances = [int(number) for number in input().split(' ')]
2 |
3 | sum_removed_numbers = 0
4 |
5 | while len(distances) != 0:
6 |
7 | index = int(input())
8 |
9 | current_num = 0
10 |
11 | if 0 <= index < len(distances):
12 | current_num = distances.pop(index)
13 |
14 | elif 0 > index:
15 | current_num = distances[0]
16 | distances[0] = distances[-1]
17 |
18 | else:
19 | current_num = distances[-1]
20 | distances[-1] = distances[0]
21 |
22 | sum_removed_numbers += current_num
23 |
24 | for current_index, current_number in enumerate(distances):
25 | if current_number <= current_num:
26 | distances[current_index] += current_num
27 | else:
28 | distances[current_index] -= current_num
29 |
30 | print(sum_removed_numbers)
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(6) Objects and Classes/08. Vehicle.py:
--------------------------------------------------------------------------------
1 | class Vehicle:
2 | def __init__(self, type, model, price, owner=None):
3 | self.type = type
4 | self.model = model
5 | self.price = price
6 | self.owner = owner
7 |
8 | def buy(self, money, owner):
9 | if self.price <= money and self.owner is None:
10 | self.owner = owner
11 | return f"Successfully bought a {self.type}. Change: {(money - self.price):.2f}"
12 | elif self.price > money:
13 | return "Sorry, not enough money"
14 | elif self.owner is not None:
15 | return "Car already sold"
16 |
17 | def sell(self):
18 | if self.owner is not None:
19 | self.owner = None
20 | else:
21 | return "Vehicle has no owner"
22 |
23 | def __repr__(self):
24 | if self.owner is None:
25 | return f"{self.model} {self.type} is on sale: {self.price}"
26 | return f"{self.model} {self.type} is owned by: {self.owner}"
27 |
28 |
29 | vehicle_type = "car"
30 | model = "BMW"
31 | price = 30000
32 | vehicle = Vehicle(vehicle_type, model, price)
33 | print(vehicle.buy(15000, "Peter"))
34 | print(vehicle.buy(35000, "George"))
35 | print(vehicle)
36 | vehicle.sell()
37 | print(vehicle)
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(6) Objects and Classes/09. Movie.py:
--------------------------------------------------------------------------------
1 | class Movie:
2 | __watched_movies = 0
3 |
4 | def __init__(self, name, director, watched=False):
5 | self.name = name
6 | self.director = director
7 | self.watched = watched
8 |
9 | def change_name(self, new_name):
10 | self.name = new_name
11 |
12 | def change_director(self, new_director):
13 | self.director = new_director
14 |
15 | def watch(self):
16 | if not self.watched:
17 | self.watched = True
18 | Movie.__watched_movies += 1
19 |
20 | def __repr__(self):
21 | return f"Movie name: {self.name}; Movie director: {self.director}. Total watched movies: {Movie.__watched_movies}"
22 |
23 |
24 | first_movie = Movie("Inception", "Christopher Nolan")
25 | second_movie = Movie("The Matrix", "The Wachowskis")
26 | third_movie = Movie("The Predator", "Shane Black")
27 | first_movie.change_director("Me")
28 | third_movie.change_name("My Movie")
29 | first_movie.watch()
30 | third_movie.watch()
31 | first_movie.watch()
32 | print(first_movie)
33 | print(second_movie)
34 | print(third_movie)
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(7) Dictionaries/11. Force Book.py:
--------------------------------------------------------------------------------
1 | force_dictionary = {}
2 |
3 |
4 | def add_user(name, side):
5 | for users in force_dictionary.values():
6 | if name in users:
7 | return
8 | force_dictionary[side] = force_dictionary.get(side, []) + [name]
9 |
10 |
11 | def switch_side(side, name):
12 | for sides, users in force_dictionary.items():
13 | if name in users:
14 | force_dictionary[sides].remove(name)
15 | break
16 | force_dictionary[side] = force_dictionary.get(side, []) + [name]
17 | print(f"{name} joins the {side} side!")
18 |
19 |
20 | command = input()
21 |
22 | while command != "Lumpawaroo":
23 | if "|" in command:
24 | side, name = command.split(" | ")
25 | add_user(name, side)
26 | elif "->" in command:
27 | side, name = command.split(" -> ")
28 | switch_side(name, side)
29 |
30 | command = input()
31 |
32 | for side, members in force_dictionary.items():
33 | if members:
34 | print(f"Side: {side}, Members: {len(members)}")
35 | for user in members:
36 | print(f"! {user}")
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(7) Dictionaries/12. SoftUni Exam Results.py:
--------------------------------------------------------------------------------
1 | student_grades = {}
2 | languages_dictionary = {}
3 |
4 |
5 | def max_grade(name, curr_grade):
6 | if name in student_grades:
7 | if curr_grade >= student_grades[name]:
8 | student_grades[name] = curr_grade
9 | elif name not in student_grades:
10 | student_grades[name] = curr_grade
11 |
12 |
13 | def banned(name):
14 | if name in student_grades:
15 | del student_grades[name]
16 |
17 |
18 | def submissions(used_language):
19 | if used_language in languages_dictionary:
20 | languages_dictionary[used_language] += 1
21 | return
22 | languages_dictionary[used_language] = 1
23 |
24 |
25 | while True:
26 | command = input()
27 |
28 | if command == 'exam finished':
29 | break
30 |
31 | indices = command.split('-')
32 |
33 | if indices[1] == 'banned':
34 | banned(indices[0])
35 | continue
36 |
37 | username, language, grade = command.split('-')
38 | grade = int(grade)
39 |
40 | max_grade(username, grade)
41 | submissions(language)
42 |
43 | print('Results:')
44 | for student, grade in student_grades.items():
45 | print(student, '|', grade)
46 | print('Submissions:')
47 | for curr_language, submissions in languages_dictionary.items():
48 | print(curr_language, '-', submissions)
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(8) Text Processing/08. Letters Change Numbers.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | main_string = re.sub("\s+", " ", input()).split()
4 | total = 0
5 | for string in main_string:
6 | numbers = int(string[1:-1])
7 | if string[0].isupper():
8 | first_result = numbers / ((ord(string[0].lower())) - 96)
9 | else:
10 | first_result = numbers * ((ord(string[0].lower())) - 96)
11 |
12 | if string[-1].isupper():
13 | second_result = first_result - ((ord(string[-1].lower())) - 96)
14 | else:
15 | second_result = first_result + ((ord(string[-1].lower())) - 96)
16 | total += second_result
17 |
18 | print(f"{total:.2f}")
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(8) Text Processing/09. Rage Quit.py:
--------------------------------------------------------------------------------
1 | main_string = input()
2 |
3 | current_result, result_show, number = "", "", "",
4 |
5 | for index, symbols in enumerate(main_string):
6 | if not symbols.isdigit():
7 | current_result += symbols
8 | elif symbols.isdigit():
9 | number += symbols
10 | if index + 1 < len(main_string):
11 | if main_string[index + 1].isdigit():
12 | continue
13 | result_show += int(number) * current_result
14 | current_result, number = "", ""
15 |
16 | result_show = result_show.upper()
17 | print(f"Unique symbols used: {len(set(result_show))}")
18 | print(result_show)
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(8) Text Processing/10. Winning Ticket.py:
--------------------------------------------------------------------------------
1 | tickets_sting = input().split(", ")
2 |
3 | symbols = ['@', '#', '$', '^']
4 |
5 |
6 | def check_next(symbol, first, second):
7 | back = 6
8 | for i in range(7, 11):
9 | if (i * symbol) in first and (i * symbol) in second:
10 | back += 1
11 | return back
12 |
13 |
14 | for ticket_characters in tickets_sting:
15 | price_find = False
16 | jackpot_find = False
17 | ticket_characters = ticket_characters.replace(" ", "")
18 | if len(ticket_characters) == 20:
19 | how_long = int(len(ticket_characters) / 2)
20 | left_side = ticket_characters[:how_long]
21 | right_side = ticket_characters[how_long:]
22 | for index, symbol in enumerate(symbols):
23 | if 10 * symbol in left_side and 10 * symbol in right_side:
24 | print(f'ticket "{ticket_characters}" - 10{symbols[index]} Jackpot!')
25 | jackpot_find = True
26 | break
27 | elif 6 * symbol in left_side and 6 * symbol in right_side:
28 | symbol_type = symbols[index]
29 | total = check_next(symbol_type, left_side, right_side)
30 | price_find = True
31 | break
32 | if price_find:
33 | print(f'ticket "{ticket_characters}" - {total}{symbol_type}')
34 | elif not jackpot_find and not price_find:
35 | print(f'ticket "{ticket_characters}" - no match')
36 | else:
37 | print("invalid ticket")
--------------------------------------------------------------------------------
/Fundamentals/(A) Not Included In Final Score - Exercise/(9) Regular Expressions/06. Extract the Links.py:
--------------------------------------------------------------------------------
1 | import re
2 | pattern = r'www\.[a-zA-Z0-9-\.]+\.[a-z]+'
3 | while True:
4 | string = input()
5 | if not string:
6 | break
7 | valid_domain = re.findall(pattern, string)
8 | if valid_domain:
9 | print('\n'.join(valid_domain))
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Esercise/01. Jenny's Secret Message.py:
--------------------------------------------------------------------------------
1 | name = input()
2 |
3 | if name == "Johnny":
4 | print("Hello, my love!")
5 | else:
6 | print(f"Hello, {name}!")
7 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Esercise/02. Drink something.py:
--------------------------------------------------------------------------------
1 | age = int(input())
2 |
3 | if age <= 14:
4 | print('drink toddy')
5 | elif age <= 18:
6 | print('drink coke')
7 | elif age <= 21:
8 | print('drink beer')
9 | else:
10 | print("drink whisky")
11 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Esercise/03. Chat Codes.py:
--------------------------------------------------------------------------------
1 | lines = int(input())
2 |
3 | for codes in range(lines):
4 | code = int(input())
5 | if code == 88:
6 | print("Hello")
7 | if code == 86:
8 | print("How are you?")
9 | if code < 88 and code != 86:
10 | print("GREAT!")
11 | if code > 88:
12 | print("Bye.")
13 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Esercise/04. Maximum Multiple.py:
--------------------------------------------------------------------------------
1 | divisior = int(input())
2 | boundary = int(input())
3 | current_number = boundary
4 |
5 | for curr_num in range(boundary, divisior, - 1):
6 | if 0 < current_num <= boundary and current_number % divisior == 0:
7 | print(current_number)
8 | break
9 | current_number -= 1
10 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Esercise/05. Orders.py:
--------------------------------------------------------------------------------
1 | total_price = 0
2 | number_of_orders = int(input())
3 |
4 | for orders in range(number_of_orders):
5 | price_per_capsule = float(input())
6 | days = int(input())
7 | capsule_per_day = int(input())
8 | price = capsule_per_day * days * price_per_capsule
9 | if 0.01 <= price_per_capsule <= 100.00 and 1 <= days <= 31 and 1 <= capsule_per_day <= 2000:
10 | total_price += price
11 | print(f"The price for the coffee is: ${price:.2f}")
12 | print(f"Total: ${total_price:.2f}")
13 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Esercise/06. String Pureness.py:
--------------------------------------------------------------------------------
1 | lines = int(input())
2 |
3 | for strings in range(lines):
4 | string = str(input())
5 | if ',' in string or '.' in string or '_' in string:
6 | print(f"{string} is not pure!")
7 | else:
8 | print(f"{string} is pure.")
9 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Esercise/07. Double Char.py:
--------------------------------------------------------------------------------
1 | word = input()
2 | while word != "End":
3 | if word != "SoftUni":
4 | for char in word:
5 | print(char * 2, end='')
6 | print()
7 | word = input()
8 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Esercise/08. How Much Coffee Do You Need.py:
--------------------------------------------------------------------------------
1 | coffee = 0
2 | lower_case = ["dog", "cat", "movie", "coding"]
3 | upper_case = str(lower_case).upper()
4 | command = str(input())
5 | while command != "END":
6 | if command in lower_case:
7 | coffee += 1
8 | elif command in upper_case:
9 | coffee += 2
10 |
11 | command = str(input())
12 |
13 | if coffee > 5:
14 | print("You need extra sleep")
15 | else:
16 | print(coffee)
17 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Esercise/09. Sorting Hat.py:
--------------------------------------------------------------------------------
1 | name = input()
2 | voldemort = False
3 |
4 | while name != "Welcome!":
5 | if name == "Voldemort":
6 | voldemort = True
7 | print("You must not speak of that name!")
8 | break
9 | elif len(name) < 5:
10 | print(f"{name} goes to Gryffindor.")
11 | elif len(name) == 5:
12 | print(f"{name} goes to Slytherin.")
13 | elif len(name) == 6:
14 | print(f"{name} goes to Ravenclaw.")
15 | else:
16 | print(f"{name} goes to Hufflepuff.")
17 |
18 | name = input()
19 |
20 | if not voldemort:
21 | print("Welcome to Hogwarts.")
22 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Lab/01. Number Definer.py:
--------------------------------------------------------------------------------
1 | number = float(input())
2 |
3 | if number == 0:
4 | print("zero")
5 | elif 0 > number >= - 1:
6 | print("small negative")
7 | elif number <= - 1000000:
8 | print("large negative")
9 | elif 1000000 > number > 1:
10 | print("positive")
11 | elif number >= 1000000:
12 | print("large positive")
13 | elif 1 > number > 0:
14 | print("small positive")
15 | else:
16 | print("negative")
17 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Lab/02. Largest Of Three Numbers.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | max_number = -sys.maxsize
4 |
5 | for largest in range(3):
6 | number = float(input())
7 |
8 | if number > max_number:
9 | max_number = number
10 | print(f"{max_number:.0f}")
11 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Lab/03. Word Reverse.py:
--------------------------------------------------------------------------------
1 | word = input()
2 |
3 | reverse_word = ''
4 |
5 | for reverse in range(len(word) - 1, -1, -1):
6 | reverse_word += word[reverse]
7 | print(reverse_word)
8 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Lab/04. Even Numbers.py:
--------------------------------------------------------------------------------
1 | lines = int(input())
2 |
3 | for numbers in range(lines):
4 | number = int(input())
5 | if number % 2 != 0:
6 | print(f"{number} is odd!")
7 | break
8 |
9 | else:
10 | print("All numbers are even.")
11 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Lab/05. Number Between 1 and 100.py:
--------------------------------------------------------------------------------
1 | num = float(input())
2 | while num < 1 or num > 100:
3 | num = float(input())
4 |
5 | print(f"The number {num} is between 1 and 100")
6 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Lab/06. Shopping.py:
--------------------------------------------------------------------------------
1 | curr_money = 0
2 | budget = int(input())
3 | money_spend = input()
4 |
5 | while money_spend != "End":
6 | curr_money += int(money_spend)
7 |
8 | if curr_money > budget:
9 | print("You went in overdraft!")
10 | break
11 | money_spend = input()
12 | else:
13 | print("You bought everything needed.")
14 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/Basic Syntax, Conditional Statements and Loops-Lab/07. Patterns.py:
--------------------------------------------------------------------------------
1 | num = int(input())
2 |
3 | for start_stars in range(1, num + 1):
4 | print(start_stars * '*')
5 |
6 | for end_stars in range(num - 1, 0, - 1):
7 | print(end_stars * '*')
8 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/More Exercise/01. Find the largest.py:
--------------------------------------------------------------------------------
1 | number = list(input())
2 | number.sort(reverse=True)
3 | print(''.join(number))
4 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/More Exercise/02. Find the capitals.py:
--------------------------------------------------------------------------------
1 | word = input()
2 | list_capitals = []
3 | # Making this for loop so I don't have to write all the capital letters
4 | for capitals in range(65, 90 + 1):
5 | list_capitals.append(chr(capitals))
6 | indices = []
7 | for index, value in enumerate(word):
8 | if value in list_capitals:
9 | indices.append(index)
10 | print(indices)
11 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/More Exercise/03. Wolf in Sheep's clothing.py:
--------------------------------------------------------------------------------
1 | animal = list(input().split(", "))
2 |
3 | if animal[-1] == "wolf":
4 | print("Please go away and stop eating my sheep")
5 | else:
6 | if "wolf" in animal:
7 | animal.reverse()
8 | for index, value in enumerate(animal):
9 | if value == "wolf":
10 | print(f"Oi! Sheep number {index}! You are about to be eaten by a wolf!")
11 | else:
12 | pass
13 |
--------------------------------------------------------------------------------
/Fundamentals/(B) Basic Syntax, Conditional Statements and Loops/More Exercise/04. Sum of beach #on 2 lines!#.py:
--------------------------------------------------------------------------------
1 | word = input().lower()
2 | print(word.count('sand') + word.count("water") + word.count("fish") + word.count("sun"))
3 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Exercise/01. Integer operations.py:
--------------------------------------------------------------------------------
1 | first_num = int(input())
2 | second_num = int(input())
3 | third_num = int(input())
4 | fourth_num = int(input())
5 |
6 | sum_numbers = int(((first_num + second_num) / third_num)) * fourth_num
7 |
8 | print(sum_numbers)
9 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Exercise/02. Chars to String.py:
--------------------------------------------------------------------------------
1 | string = ''
2 |
3 | for char in range(3):
4 | character = input()
5 | string += character
6 |
7 | print(string)
8 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Exercise/03. Elevator.py:
--------------------------------------------------------------------------------
1 | from math import ceil
2 |
3 | people = int(input())
4 | capacity = int(input())
5 |
6 | if capacity >= 1:
7 | courses = ceil(people/capacity)
8 | print(courses)
9 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Exercise/04. Sum of Chars.py:
--------------------------------------------------------------------------------
1 | lines = int(input())
2 | sum_chars = 0
3 |
4 | for characters in range(lines):
5 | char = ord(input())
6 | sum_chars += char
7 |
8 | print(f"The sum equals: {sum_chars}")
9 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Exercise/05. Print Part of the ASCII Table.py:
--------------------------------------------------------------------------------
1 | first_char = int(input())
2 | last_char = int(input())
3 |
4 | for char in range(first_char, last_char + 1):
5 | print(chr(char), end=' ')
6 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Exercise/06. Triples of Latin Letters.py:
--------------------------------------------------------------------------------
1 | number_of_letters = int(input())
2 |
3 | for first_char in range(number_of_letters):
4 | for second_char in range(number_of_letters):
5 | for third_char in range(number_of_letters):
6 | print(f"{chr(97 + first_char)}{chr(97 + second_char)}{chr(97 + third_char)}")
7 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Exercise/07. Water Overflow.py:
--------------------------------------------------------------------------------
1 | lines = int(input())
2 | tub_capacity = 255 # Liters
3 | total_water = 0 # Liters
4 |
5 | for capacity in range(lines):
6 | water = float(input())
7 |
8 | if water <= tub_capacity:
9 | tub_capacity -= water
10 | total_water += water
11 |
12 | else:
13 | print("Insufficient capacity!")
14 |
15 | print(f"{total_water:.0f}")
16 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Lab/01. Concat Names.py:
--------------------------------------------------------------------------------
1 | first_person = input()
2 | second_person = input()
3 | delimiter = input()
4 |
5 | print(f'{first_person}{delimiter}{second_person}')
6 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Lab/02. Centuries to Minutes.py:
--------------------------------------------------------------------------------
1 | centuries = int(input())
2 | years = centuries * 100
3 | days = int(years * 365.2422)
4 | hours = days * 24
5 | minutes = hours * 60
6 |
7 | print(f"{centuries} centuries = {years} years = {days} days = {hours} hours = {minutes} minutes")
8 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Lab/03. Special Numbers.py:
--------------------------------------------------------------------------------
1 | number = int(input())
2 |
3 | for num in range(1, number + 1):
4 | sum_digits = 0
5 | digits = num
6 | while digits > 0:
7 | sum_digits += digits % 10
8 | digits = int(digits / 10)
9 | if sum_digits == 5 or sum_digits == 7 or sum_digits == 11:
10 | print(f'{num} -> True')
11 | else:
12 | print(f"{num} -> False")
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Lab/04. Convert Meters to Kilometers.py:
--------------------------------------------------------------------------------
1 | meters = int(input())
2 | kilometers = meters / 1000
3 |
4 | print(f'{kilometers:.2f}')
5 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Lab/05. Pounds to Dollars.py:
--------------------------------------------------------------------------------
1 | british_pounds = int(input())
2 | dollars = british_pounds * 1.31
3 |
4 | print(f'{dollars:.3f}')
5 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/Data Types and Variables - Lab/06. Next Happy Year.py:
--------------------------------------------------------------------------------
1 | year = int(input())
2 | happy_year = False
3 |
4 | while not happy_year:
5 | year += 1
6 | set_year = set()
7 |
8 | for years in range(len(str(year))):
9 | set_year.add(str(year)[years])
10 |
11 | happy_year = len(set_year) == len(str(year))
12 |
13 | print(year)
14 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/More Exercise/(1) Conditions.docx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/Fundamentals/(C) Data Types and Variables/More Exercise/(1) Conditions.docx
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/More Exercise/01. Exchange Integers.py:
--------------------------------------------------------------------------------
1 | a = input()
2 | b = input()
3 | print(f'''
4 | Before:
5 | a = {a}
6 | b = {b}
7 | After:
8 | a = {b}
9 | b = {a}
10 | ''')
11 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/More Exercise/02. Prime Number Checker.py:
--------------------------------------------------------------------------------
1 | number = int(input())
2 | divider = 0
3 | for num in range(number):
4 | divider += 1
5 | if 1 < divider < number and number % divider == 0:
6 | print('False')
7 | break
8 | else:
9 | print('True')
10 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/More Exercise/03. Decrypting Messages.py:
--------------------------------------------------------------------------------
1 | key = int(input())
2 | lines = int(input())
3 | string = ''
4 |
5 | for word in range(lines):
6 | letter = ord(str(input())) + key
7 | string += chr(letter)
8 |
9 | print(string)
10 |
--------------------------------------------------------------------------------
/Fundamentals/(C) Data Types and Variables/More Exercise/04. Balanced Brackets.py:
--------------------------------------------------------------------------------
1 | lines = int(input())
2 | balanced = 0
3 | last_bracket = ''
4 | for brackets in range(lines):
5 | string = input()
6 | if string == "(":
7 | balanced += 1
8 | last_bracket = "("
9 | if balanced > 1:
10 | print("UNBALANCED")
11 | exit()
12 | elif string == ")":
13 | balanced -= 1
14 | last_bracket = ")"
15 | if balanced == 0 and last_bracket != "(":
16 | print("BALANCED")
17 | else:
18 | print("UNBALANCED")
19 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/Lists Basics - Exercise/01. Invert Values.py:
--------------------------------------------------------------------------------
1 | string = input().split(' ')
2 | invert_values = []
3 |
4 | for number in string:
5 | invert_values.append(-int(number))
6 | print(invert_values)
7 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/Lists Basics - Exercise/02. Multiples List.py:
--------------------------------------------------------------------------------
1 | first_number = int(input())
2 | first_number_cnt = first_number
3 | second_number = int(input())
4 | list_numbers = []
5 |
6 | for multiply in range(1, second_number + 1):
7 | list_numbers.append(first_number_cnt)
8 | # We use the first_number_cnt because for example, if first_number = 2,
9 | # and we add first_number to first_number it will become 4, and after that instead of 4 + 2 we'll have 4 + 4 and that gives us wrong information.
10 | first_number_cnt += first_number
11 |
12 | print(list_numbers)
13 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/Lists Basics - Exercise/03. Football Cards.py:
--------------------------------------------------------------------------------
1 | team_a = ["A-1", "A-2", "A-3", "A-4", "A-5", "A-6", "A-7", "A-8", "A-9", "A-10", "A-11"]
2 | team_b = ["B-1", "B-2", "B-3", "B-4", "B-5", "B-6", "B-7", "B-8", "B-9", "B-10", "B-11"]
3 | kicked_players = input().split()
4 |
5 | for player in kicked_players:
6 | if player in team_a:
7 | team_a.remove(player)
8 | elif player in team_b:
9 | team_b.remove(player)
10 |
11 | if len(team_a) < 7 or len(team_b) < 7:
12 | print(f"Team A - {len(team_a)}; Team B - {len(team_b)}")
13 | print("Game was terminated")
14 | break
15 |
16 | else:
17 | print(f"Team A - {len(team_a)}; Team B - {len(team_b)}")
18 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/Lists Basics - Exercise/04. Number Beggars.py:
--------------------------------------------------------------------------------
1 | string = input().split(", ")
2 | beggars = int(input())
3 | final_list = []
4 | counter = 0
5 |
6 | my_list = []
7 | for curr_index in string:
8 | my_list.append(int(curr_index))
9 |
10 | while counter < beggars:
11 | beggars_sum = 0
12 |
13 | for curr_index in range(counter, len(string), beggars):
14 | beggars_sum += my_list[curr_index]
15 | counter += 1
16 | final_list.append(beggars_sum)
17 |
18 | print(final_list)
19 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/Lists Basics - Exercise/05. Faro Shuffle.py:
--------------------------------------------------------------------------------
1 | string = input().split()
2 | number = int(input())
3 |
4 | for shuffle in range(number):
5 | final_list = []
6 | middle_of_string = len(string) // 2
7 | left_part = string[0:middle_of_string]
8 | right_part = string[middle_of_string::]
9 |
10 | for index in range(len(left_part)):
11 | final_list.append(left_part[index])
12 | final_list.append(right_part[index])
13 | string = final_list
14 |
15 | print(string)
16 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/Lists Basics - Exercise/06. Survival of The Biggest.py:
--------------------------------------------------------------------------------
1 | list_numbers = input().split()
2 | big_numbers = []
3 |
4 | for number in list_numbers:
5 | big_numbers.append(int(number))
6 |
7 | remover = int(input())
8 |
9 | for removing in range(remover):
10 | big_numbers.remove(min(big_numbers))
11 |
12 | print(*nums, sep=', ')
13 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/Lists Basics - Lab/01. Strange Zoo.py:
--------------------------------------------------------------------------------
1 | tail = input()
2 | body = input()
3 | head = input()
4 |
5 | list = [head, body, tail]
6 |
7 | print(list)
8 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/Lists Basics - Lab/02. Courses.py:
--------------------------------------------------------------------------------
1 | number_courses = int(input())
2 | # EMPTY LIST:
3 | courses = list() # or []
4 |
5 | for course in range(number_courses):
6 | curr_course = input()
7 | courses.append(curr_course) # adding the course to the list
8 | print(courses)
9 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/Lists Basics - Lab/03. List Statistics.py:
--------------------------------------------------------------------------------
1 | lines = int(input())
2 | list_positives = []
3 | list_negatives = []
4 |
5 | for number in range(lines):
6 | num = int(input())
7 | if num < 0:
8 | list_negatives.append(num)
9 | else:
10 | list_positives.append(num)
11 |
12 | print(list_positives)
13 | print(list_negatives)
14 | print(f"Count of positives: {len(list_positives)}")
15 | print(f"Sum of negatives: {sum(list_negatives)}")
16 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/Lists Basics - Lab/04. Search.py:
--------------------------------------------------------------------------------
1 | number = int(input())
2 | key = input()
3 | list_all = []
4 | filtered_list = []
5 |
6 | for word in range(number):
7 | string = input()
8 | list_all.append(string)
9 | if key in string:
10 | filtered_list.append(string)
11 |
12 | print(list_all)
13 | print(filtered_list)
14 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/Lists Basics - Lab/05. Numbers Filter.py:
--------------------------------------------------------------------------------
1 | lines = int(input())
2 | command_even = "even"
3 | command_odd = "odd"
4 | command_positive = "positive"
5 | command_negative = "negative"
6 | my_list = []
7 | filtered_numbers = []
8 |
9 | for num in range(lines):
10 | curr_num = int(input())
11 | my_list.append(curr_num)
12 |
13 | command = input()
14 |
15 | for number in my_list:
16 | filtered_command = (
17 | (command == command_even and number % 2 == 0) or
18 | (command == command_odd and number % 2 != 0) or
19 | (command == command_positive and number >= 0) or
20 | (command == command_negative and number < 0)
21 | )
22 |
23 | if filtered_command:
24 | filtered_numbers.append(number)
25 |
26 | print(filtered_numbers)
27 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/More Exercise/01. Zeros to Back.py:
--------------------------------------------------------------------------------
1 | list_numbers = input().split(', ')
2 | zero_cnt = 0
3 | final_list = []
4 |
5 | for numbers in list_numbers:
6 | if numbers != '0':
7 | final_list.append(int(numbers))
8 | continue
9 | zero_cnt += 1
10 |
11 | for zeros in range(zero_cnt):
12 | final_list.append(0)
13 | print(final_list)
14 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/More Exercise/02. Messaging.py:
--------------------------------------------------------------------------------
1 | list_numbers = input().split(' ')
2 | message = input()
3 | message_list = []
4 |
5 | for numbers in list_numbers:
6 | current_sum = 0
7 | for integer_numbers in numbers:
8 | current_sum += int(integer_numbers)
9 |
10 | current_sum %= len(message)
11 |
12 | message_list.append(message[current_sum])
13 | message = message.replace(message[current_sum], '', 1)
14 |
15 | print(''.join(message_list))
16 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/More Exercise/03. Car Race.py:
--------------------------------------------------------------------------------
1 | numbers = list(map(int, input().split(' ')))
2 | time_left_needed = 0
3 | time_right_needed = 0
4 | finish_line = len(numbers) // 2 + 1
5 | left_racer = numbers[:finish_line - 1]
6 | right_racer = numbers[finish_line:][::-1]
7 |
8 | for first_racer_time in left_racer:
9 | time_left_needed += first_racer_time
10 | if first_racer_time == 0:
11 | time_left_needed *= 0.80
12 |
13 | for second_racer_time in right_racer:
14 | time_right_needed += second_racer_time
15 | if second_racer_time == 0:
16 | time_right_needed *= 0.80
17 |
18 | # This if is not needed or in the condition. That's why I'll # it but if you want you can use it.
19 | # if time_left_needed == time_right_needed:
20 | # print(f"It's DRAW! Total time: {time_left_needed:.1f}")
21 | if time_left_needed < time_right_needed:
22 | print(f"The winner is left with total time: {time_left_needed:.1f}")
23 | else:
24 | print(f"The winner is right with total time: {time_right_needed:.1f}")
25 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/More Exercise/04. Josephus Permutation.py:
--------------------------------------------------------------------------------
1 | people = input().split(' ')
2 | kills = int(input())
3 | executed = []
4 | counter = 0
5 | current_index = 0
6 |
7 | while len(people) > 0:
8 | counter += 1
9 |
10 | if counter % kills == 0:
11 | executed.append(people.pop(current_index))
12 | else:
13 | current_index += 1
14 |
15 | if current_index >= len(people):
16 | current_index = 0
17 |
18 | print(str(executed).replace(' ', '').replace('\'', ''))
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/More Exercise/05. Tic-Tac-Toe/05. Tic-Tac-Toe solved with current knowledge.py:
--------------------------------------------------------------------------------
1 | first_row = input().split()
2 | second_row = input().split()
3 | third_row = input().split()
4 |
5 | player = 1
6 | name_player = "First"
7 | found = False
8 |
9 | while player < 3:
10 | player = str(player)
11 | line = [player, player, player]
12 | if line == first_row or second_row == line or third_row == line: # rows check
13 | found = True
14 | for column in range(0, 3):
15 | if first_row[column] == player and second_row[column] == player and third_row[column] == player: # columns check
16 | found = True
17 | if first_row[0] == player and second_row[1] == player and third_row[2] == player: # left diagonal
18 | found = True
19 | elif first_row[2] == player and second_row[1] == player and third_row[0] == player: # right diagonal
20 | found = True
21 | if found:
22 | print(f"{name_player} player won")
23 | break
24 | player = int(player) + 1
25 | name_player = "Second"
26 | else:
27 | print("Draw!")
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/More Exercise/05. Tic-Tac-Toe/05. Tic-Tac-Toe solved with functions and loops.py:
--------------------------------------------------------------------------------
1 | def check_win(board, player):
2 | # check rows
3 | for rows in range(3):
4 | row = board[rows]
5 | if row.count(player) == 3:
6 | return True
7 |
8 | # check columns
9 | for columns in range(3):
10 | column = [row[columns] for row in board]
11 | if column.count(player) == 3:
12 | return True
13 |
14 | # check diagonals
15 | primary_diagonal = [board[diagonal][diagonal] for diagonal in range(3)]
16 | if primary_diagonal.count(player) == 3:
17 | return True
18 |
19 | secondary_diagonal = [board[secondary_diagonal][len(board) - secondary_diagonal - 1] for secondary_diagonal
20 | in range(3)]
21 | if secondary_diagonal.count(player) == 3:
22 | return True
23 |
24 |
25 | board = []
26 | for winner in range(3):
27 | board.append(input().split())
28 |
29 | if check_win(board, "1"):
30 | print("First player won")
31 | elif check_win(board, "2"):
32 | print("Second player won")
33 | else:
34 | print("Draw!")
35 |
--------------------------------------------------------------------------------
/Fundamentals/(D) Lists Basics/More Exercise/05. Tic-Tac-Toe/05. Tic-Tac-Toe solved with if-elif-else.py:
--------------------------------------------------------------------------------
1 | first_line = input().split(' ')
2 | second_line = input().split(' ')
3 | third_line = input().split(' ')
4 |
5 | if first_line[0] == '1' and first_line[1] == '1' and first_line[2] == '1' or second_line[0] == '1' \
6 | and second_line[1] == '1' and second_line[2] == '1' or third_line[0] == '1' and third_line[1] == '1' and third_line[2] == '1':
7 | print('First player won')
8 | elif first_line[0] == '2' and first_line[1] == '2' and first_line[2] == '2' or second_line[0] == '2' \
9 | and second_line[1] == '2' and second_line[2] == '2' or third_line[0] == '2' and third_line[1] == '2' \
10 | and third_line[2] == '2':
11 | print('Second player won')
12 | elif first_line[0] == '1' and second_line[0] == '1' and third_line[0] == '1' or first_line[1] == '1' \
13 | and second_line[1] == '1' and third_line[1] == '1' or first_line[2] == '1' and second_line[2] == '1' \
14 | and third_line[2] == '1':
15 | print('First player won')
16 | elif first_line[0] == '2' and second_line[0] == '2' and third_line[0] == '2' or first_line[1] == '2' \
17 | and second_line[1] == '2' and third_line[1] == '2' or first_line[2] == '2' and second_line[2] == '2' \
18 | and third_line[2] == '2':
19 | print('Second player won')
20 | elif first_line[0] == '1' and second_line[1] == '1' and third_line[2] == '1' or \
21 | first_line[2] == '1' and second_line[1] == '1' and third_line[0] == '1':
22 | print('First player won')
23 | elif first_line[0] == '2' and second_line[1] == '2' and third_line[2] == '2' or \
24 | first_line[2] == '2' and second_line[1] == '2' and third_line[0] == '2':
25 | print('Second player won')
26 | else:
27 | print("Draw!")
28 |
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Exercise/01. Which Are In.py:
--------------------------------------------------------------------------------
1 | first_sequence = input().split(", ")
2 | second_sequence = input().split(", ")
3 | substrings = []
4 | for first_word in first_sequence:
5 | for second_word in second_sequence:
6 | if first_word in second_word:
7 | substrings.append(first_word)
8 | break
9 | print(substrings)
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Exercise/02. Next Version.py:
--------------------------------------------------------------------------------
1 | current_version = list(map(int, input().split('.')))
2 |
3 | new_version = current_version
4 |
5 | for index in range(len(new_version) - 1, - 1, - 1):
6 | new_version[index] += 1
7 | if new_version[index] > 9:
8 | new_version[index] = 0
9 | if index + 1 < 0:
10 | new_version[index + 1] += 1
11 | continue
12 |
13 | break
14 |
15 | new_version = [str(new) for new in new_version]
16 | print('.'.join(new_version))
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Exercise/03. Word Filter.py:
--------------------------------------------------------------------------------
1 | words = input().split(' ')
2 | words_list = [word for word in words if len(word) % 2 == 0]
3 | print('\n'.join(words_list))
4 |
5 |
6 | # print('\n'.join([word for word in input().split(' ') if len(word) % 2 == 0]))
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Exercise/04. Number Classification.py:
--------------------------------------------------------------------------------
1 | def positive(numbers):
2 | positive_numbers = [str(num) for num in numbers if num >= 0]
3 | return f"Positive: {', '.join(positive_numbers)}"
4 |
5 |
6 | def negative(numbers):
7 | negative_numbers = [str(num) for num in numbers if num < 0]
8 | return f"Negative: {', '.join(negative_numbers)}"
9 |
10 |
11 | def even(numbers):
12 | even_numbers = [str(num) for num in numbers if num % 2 == 0]
13 | return f"Even: {', '.join(even_numbers)}"
14 |
15 |
16 | def odd(numbers):
17 | odd_numbers = [str(num) for num in numbers if num % 2 != 0]
18 | return f"Odd: {', '.join(odd_numbers)}"
19 |
20 |
21 | list_numbers = list(map(int, input().split(', ')))
22 | print(positive(list_numbers))
23 | print(negative(list_numbers))
24 | print(even(list_numbers))
25 | print(odd(list_numbers))
26 |
27 |
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Exercise/05. Office Chairs.py:
--------------------------------------------------------------------------------
1 | rooms = int(input())
2 |
3 | chairs_list = [0] * rooms
4 |
5 | total_free_chairs = 0
6 |
7 | for current_room in range(rooms):
8 | chairs = input().split(' ')
9 | chairs_needed = int(chairs[-1]) - len(chairs[0])
10 | chairs_list[current_room] += chairs_needed
11 |
12 | if chairs_list[current_room] > 0:
13 | print(f"{chairs_list[current_room]} more chairs needed in room {current_room + 1}")
14 |
15 | if chairs_list[current_room] < 0:
16 | total_free_chairs += abs(chairs_list[current_room])
17 | chairs_list[current_room] = 0
18 |
19 | if sum(chairs_list) == 0:
20 | print(f"Game On, {total_free_chairs} free chairs left")
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Exercise/06. Electron Distribution.py:
--------------------------------------------------------------------------------
1 | electrons = int(input())
2 |
3 | shells = []
4 | index = 0
5 | while electrons > 0:
6 | index += 1
7 | max_electrons = 2 * (index * index)
8 |
9 | if max_electrons > electrons:
10 | shells.append(electrons)
11 | electrons = 0
12 | break
13 |
14 | shells.append(max_electrons)
15 | electrons -= max_electrons
16 |
17 | print(shells)
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Exercise/07. Group of 10's.py:
--------------------------------------------------------------------------------
1 | numbers = list(map(int, input().split(', ')))
2 |
3 | for group in range(1, 11):
4 | if len(numbers) == 0:
5 | break
6 | group_list = [num for num in numbers if num <= (group * 10)]
7 | numbers = [num for num in numbers if num not in group_list]
8 | print(f"Group of {group}0's: {group_list}")
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Exercise/08. Decipher This!.py:
--------------------------------------------------------------------------------
1 | sentence = input().split(' ')
2 |
3 | number = ''
4 | for index, word in enumerate(sentence):
5 |
6 | letter = ''
7 |
8 | for symbol in word:
9 |
10 | if symbol.isdigit():
11 | number += symbol
12 | continue
13 |
14 | letter += symbol
15 |
16 | number = int(number)
17 | number = chr(number)
18 | current_word = number + letter
19 | sentence[index] = current_word
20 |
21 | word = sentence[index]
22 | word = [char for char in word]
23 | word[1], word[-1] = word[-1], word[1]
24 | word = ''.join(word)
25 | sentence[index] = word
26 |
27 | number = ''
28 |
29 | print(*sentence)
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Lab/01. No Vowels.py:
--------------------------------------------------------------------------------
1 | word = input()
2 | list_vowels = ["a", "o", "u", "e", "i"]
3 | filtered = [index for index in word if index.lower() not in list_vowels]
4 | print(''.join(filtered))
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Lab/02. Trains.py:
--------------------------------------------------------------------------------
1 | train = int(input())
2 | wagons = [0] * train
3 |
4 | while True:
5 | command = input().split(' ')
6 |
7 | if command[0] == 'End':
8 | break
9 |
10 | index = int(command[1])
11 | people = int(command[-1])
12 |
13 | if command[0] == 'add':
14 | wagons[-1] += index
15 |
16 | if command[0] == 'insert':
17 | wagons[index] += people
18 |
19 | if command[0] == 'leave':
20 | wagons[index] -= people
21 |
22 | print(wagons)
23 |
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Lab/03. To-do List.py:
--------------------------------------------------------------------------------
1 | todo_list = []
2 | ten_list = []
3 |
4 | while True:
5 | command = input()
6 |
7 | if command == "End":
8 | break
9 |
10 | ten = command.split('-')
11 |
12 | if ten[0] == '10':
13 | ten_list.append(ten[1])
14 | continue
15 |
16 | todo_list.append(command)
17 |
18 | todo_list = sorted(todo_list)
19 | to_do_list = [to_do.split('-')[1] for to_do in todo_list]
20 | todo_final_list = [*to_do_list, *[ten_list[tens] for tens in range(len(ten_list))]]
21 |
22 | print(todo_final_list)
23 |
24 |
25 |
26 |
27 | # todo_list = []
28 | # ten_list = []
29 | #
30 | # while True:
31 | # todo = input()
32 | #
33 | # if todo == "End":
34 | # break
35 | #
36 | # if todo.split('-')[0] == '10':
37 | # todo = todo.split('-')
38 | # ten_list.append(todo[1])
39 | # continue
40 | #
41 | # todo_list.append(todo)
42 | #
43 | # todo_list = sorted(todo_list)
44 | # todo_final_list = []
45 | #
46 | # for index in range(len(todo_list)):
47 | # to_do = todo_list[index].split('-')
48 | # todo_final_list.append(to_do[1])
49 | #
50 | # for tens in range(len(ten_list)):
51 | # todo_final_list.append(ten_list[tens])
52 | #
53 | # print(todo_final_list)
54 |
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Lab/04. Palindrome String.py:
--------------------------------------------------------------------------------
1 | words = input().split(' ')
2 | palindrome = input()
3 | palindromes_list = [word for word in words if word == word[::-1]]
4 |
5 | found_palindromes = [word for word in words if word == palindrome]
6 | palindrome_counter = len(found_palindromes)
7 |
8 | print(palindromes_list)
9 | print(f"Found palindrome {palindrome_counter} times")
10 |
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Lab/05. Sorting Names.py:
--------------------------------------------------------------------------------
1 | names = input().split(', ')
2 | sorted_names = sorted(names, key=lambda item: (-len(item), item))
3 | print(sorted_names)
4 |
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Lab/06. Even Numbers.py:
--------------------------------------------------------------------------------
1 | list_numbers = list(map(int, input().split(', ')))
2 | even_numbers = [index for index in range(len(list_numbers)) if list_numbers[index] % 2 == 0]
3 | print(even_numbers)
4 |
5 |
6 | # list_numbers = list(map(int, input().split(', ')))
7 | # print([index for index in range(len(list_numbers)) if list_numbers[index] % 2 == 0])
8 |
9 |
10 | # numbers = input().split(', ')
11 | # even_numbers = [index for index in range(len(numbers)) if int(numbers[index]) % 2 == 0]
12 | # print(even_numbers)
13 |
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/Lists Advanced - Lab/07. The Office.py:
--------------------------------------------------------------------------------
1 | employee = list(map(int, input().split(' ')))
2 | factor = int(input())
3 | employee = [factor * employee[index] for index in range(len(employee))]
4 | happy_office = list(filter(lambda x: x >= sum(employee) / len(employee), employee))
5 |
6 | if len(happy_office) >= len(employee) / 2:
7 | print(f"Score: {len(happy_office)}/{len(employee)}. Employees are happy!")
8 | else:
9 | print(f"Score: {len(happy_office)}/{len(employee)}. Employees are not happy!")
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/More Exercise/01. Social Distribution.py:
--------------------------------------------------------------------------------
1 | population = list(map(int, input().split(', ')))
2 | minimum_wealth = int(input())
3 |
4 | for index, wealth in enumerate(population):
5 | if wealth < minimum_wealth:
6 | max_population = population.index(max(population))
7 | needed_wealth = minimum_wealth - wealth
8 | population[max_population] -= needed_wealth
9 | population[index] += needed_wealth
10 |
11 | has_needed_wealth = [0 for wealth in population if wealth >= minimum_wealth]
12 |
13 | if len(has_needed_wealth) == len(population):
14 | print(population)
15 | else:
16 | print("No equal distribution possible")
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/More Exercise/02. Take_Skip Rope.py:
--------------------------------------------------------------------------------
1 | string = input()
2 |
3 | numbers = []
4 | letters = ''
5 | take_list = []
6 | skip_list = []
7 |
8 | final_string = ''
9 |
10 | for character in string:
11 | if character.isdigit():
12 | numbers.append(int(character))
13 | else:
14 | letters += character
15 |
16 | for index, num in enumerate(numbers):
17 | if index % 2 == 0:
18 | take_list.append(num)
19 | else:
20 | skip_list.append(num)
21 |
22 | for take, skip in zip(take_list, skip_list):
23 | if take == 0:
24 | letters = letters[skip:]
25 | elif take != 0:
26 | final_string = final_string + letters[:take]
27 | letters = letters[skip + take:]
28 |
29 | print(final_string)
30 |
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/More Exercise/03. Kate's Way Out.py:
--------------------------------------------------------------------------------
1 | def correct_lab_bounds(row, col):
2 | if row < 0 or col < 0 or row >= len(lab_list) or col >= len(lab_list[0]):
3 | return True
4 |
5 |
6 | def check_wall(row, col):
7 | if lab_list[row][col] in "#v":
8 | return True
9 |
10 |
11 | def find_exit(row, col):
12 | if row == 0 or row == len(lab_list) - 1 or col == 0 or col == len(lab_list[0]):
13 | return True
14 |
15 |
16 | def find_starting_point():
17 | for pos_row, row in enumerate(lab_list):
18 | for pos_col, col in enumerate(row):
19 | if col == "k":
20 | return pos_row, pos_col
21 |
22 |
23 | def find_the_lab_path(row, col, lab):
24 | if correct_lab_bounds(row, col) or check_wall(row, col):
25 | return
26 |
27 | steps.append(1)
28 |
29 | if find_exit(row, col):
30 | max_len_path.append(sum(steps))
31 |
32 | lab[row][col] = "v"
33 | find_the_lab_path(row, col + 1, lab) # check right
34 | find_the_lab_path(row, col - 1, lab) # check left
35 | find_the_lab_path(row + 1, col, lab) # check up
36 | find_the_lab_path(row - 1, col, lab) # check down
37 | lab[row][col] = " "
38 |
39 | steps.pop()
40 |
41 |
42 | rows = int(input())
43 | lab_list = []
44 | steps = []
45 | max_len_path = []
46 | for curr_lab in range(rows):
47 | lab_list.append(list(input()))
48 | cols = len(lab_list[0])
49 | start_row, start_col = find_starting_point()
50 |
51 | find_the_lab_path(start_row, start_col, lab_list)
52 |
53 | if max_len_path:
54 | print(f"Kate got out in {max(max_len_path)} moves")
55 | else:
56 | print("Kate cannot get out")
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/More Exercise/04. Battle Ships.py:
--------------------------------------------------------------------------------
1 | rows = int(input())
2 | ships_list = []
3 |
4 | for current_row in range(rows):
5 | ships = input().split(' ')
6 | ships_list.append(ships)
7 | attacked_squares = input().split(' ')
8 |
9 | destroyed_counter = 0
10 | for attack in attacked_squares:
11 | current_attack = attack.split('-')
12 | row = int(current_attack[0])
13 | col = int(current_attack[1])
14 |
15 | current_ship = ships_list[row]
16 | curr_ship = int(current_ship[col])
17 |
18 | if curr_ship > 0:
19 | curr_ship -= 1
20 | if curr_ship == 0:
21 | destroyed_counter += 1
22 |
23 | current_ship[col] = str(curr_ship)
24 | ships_list[row] = current_ship
25 |
26 | print(destroyed_counter)
--------------------------------------------------------------------------------
/Fundamentals/(F) Lists Advanced/More Exercise/05. Dots.py:
--------------------------------------------------------------------------------
1 | def correct_lab_bounds(row, col):
2 | if row < 0 or col < 0 or row >= len(lab) or col >= len(lab[0]):
3 | return True
4 |
5 |
6 | def check_wall(row, col):
7 | if lab[row][col] in "-–":
8 | return True
9 |
10 |
11 | def check_already_visit(row, col):
12 | if lab[row][col] == "v":
13 | return True
14 |
15 |
16 | def find_exit(row, col):
17 | if lab[row][col] == ".":
18 | return True
19 |
20 |
21 | def find_the_lab_path(row, col, lab):
22 | if correct_lab_bounds(row, col) or check_wall(row, col) or check_already_visit(row, col):
23 | return
24 |
25 | path_steps.append(1)
26 |
27 | if find_exit(row, col):
28 | max_connected_points.append(sum(path_steps))
29 |
30 | lab[row][col] = "v"
31 | find_the_lab_path(row, col + 1, lab) # check right
32 | find_the_lab_path(row, col - 1, lab) # check left
33 | find_the_lab_path(row + 1, col, lab) # check up
34 | find_the_lab_path(row - 1, col, lab) # check down
35 |
36 |
37 | row = int(input())
38 | lab = []
39 | max_connected_points = [0]
40 | for curr_row in range(row):
41 | lab.append(list(input().split()))
42 |
43 | range_of_col = len(lab[0])
44 |
45 | for row in range(len(lab)):
46 | for col in range(range_of_col):
47 | path_steps = []
48 | if not check_wall(row, col):
49 | find_the_lab_path(row, col, lab)
50 |
51 |
52 | print(max(max_connected_points))
--------------------------------------------------------------------------------
/Fundamentals/(I) Objects and Classes/Objects and Classes - Exercise/01. Storage.py:
--------------------------------------------------------------------------------
1 | class Storage:
2 | def __init__(self, capacity):
3 | self.capacity = capacity
4 | self.storage = []
5 |
6 | def add_product(self, product):
7 | if self.capacity > len(self.storage):
8 | self.storage.append(product)
9 |
10 | def get_products(self):
11 | return self.storage
12 |
13 |
14 | storage = Storage(4)
15 | storage.add_product("apple")
16 | storage.add_product("banana")
17 | storage.add_product("potato")
18 | storage.add_product("tomato")
19 | storage.add_product("bread")
20 | print(storage.get_products())
21 |
--------------------------------------------------------------------------------
/Fundamentals/(I) Objects and Classes/Objects and Classes - Exercise/02. Weapon.py:
--------------------------------------------------------------------------------
1 | class Weapon:
2 | def __init__(self, number_of_bullets):
3 | self.bullets = number_of_bullets
4 |
5 | def shoot(self):
6 | if self.bullets:
7 | self.bullets -= 1
8 | return 'shooting...'
9 | else:
10 | return "no bullets left"
11 |
12 | def __repr__(self):
13 | return f"Remaining bullets: {self.bullets}"
14 |
15 |
16 | weapon = Weapon(5)
17 | print(weapon.shoot())
18 | print(weapon.shoot())
19 | print(weapon)
20 | print(weapon.shoot())
21 | print(weapon.shoot())
22 | print(weapon.shoot())
23 | print(weapon.shoot())
24 | print(weapon)
--------------------------------------------------------------------------------
/Fundamentals/(I) Objects and Classes/Objects and Classes - Exercise/03. Catalogue.py:
--------------------------------------------------------------------------------
1 | class Catalogue:
2 | def __init__(self, name):
3 | self.name = name
4 | self.products = []
5 |
6 | def add_product(self, product_name):
7 | self.products.append(product_name)
8 |
9 | def get_by_letter(self, first_letter):
10 | return [product for product in self.products if product[0].lower() == first_letter.lower()]
11 |
12 | def __repr__(self):
13 | string = f'Items in the {self.name} catalogue:\n'
14 | return string + '\n'.join(sorted(self.products))
15 |
16 |
17 | catalogue = Catalogue("Furniture")
18 | catalogue.add_product("Sofa")
19 | catalogue.add_product("Mirror")
20 | catalogue.add_product("Desk")
21 | catalogue.add_product("Chair")
22 | catalogue.add_product("Carpet")
23 | print(catalogue.get_by_letter("C"))
24 | print(catalogue)
--------------------------------------------------------------------------------
/Fundamentals/(I) Objects and Classes/Objects and Classes - Exercise/04. Town.py:
--------------------------------------------------------------------------------
1 | class Town:
2 | def __init__(self, name, latitude="0°N", longitude="0°E"):
3 | self.name = name
4 | self.latitude = latitude
5 | self.longitude = longitude
6 |
7 | def set_latitude(self, latitude):
8 | self.latitude = latitude
9 |
10 | def set_longitude(self, longitude):
11 | self.longitude = longitude
12 |
13 | def __repr__(self):
14 | return f"Town: {self.name} | Latitude: {self.latitude} | Longitude: {self.longitude}"
15 |
16 |
17 | town = Town("Sofia")
18 | town.set_latitude("42° 41\' 51.04\" N")
19 | town.set_longitude("23° 19\' 26.94\" E")
20 | print(town)
--------------------------------------------------------------------------------
/Fundamentals/(I) Objects and Classes/Objects and Classes - Exercise/05. Class.py:
--------------------------------------------------------------------------------
1 | class Class:
2 | __students_count = 22
3 |
4 | def __init__(self, name):
5 | self.name = name
6 | self.students = []
7 | self.grades = []
8 | self.average_grade = 0
9 |
10 | def add_student(self, name, grade):
11 | if len(self.students) < Class.__students_count:
12 | self.students.append(name)
13 | self.grades.append(grade)
14 | self.average_grade = sum(self.grades) / len(self.grades)
15 |
16 | def get_average_grade(self):
17 | return self.average_grade
18 |
19 | def __repr__(self):
20 | return f"The students in {self.name}: {', '.join(self.students)}. Average grade: {self.average_grade:.2f}"
21 |
22 |
23 | a_class = Class("11B")
24 | a_class.add_student("Peter", 4.80)
25 | a_class.add_student("George", 6.00)
26 | a_class.add_student("Amy", 3.50)
27 | print(a_class)
--------------------------------------------------------------------------------
/Fundamentals/(I) Objects and Classes/Objects and Classes - Exercise/06. Inventory.py:
--------------------------------------------------------------------------------
1 | class Inventory:
2 | def __init__(self, __capacity: int):
3 | self.__capacity = __capacity
4 | self.left_capacity = __capacity
5 | self.items = []
6 |
7 | def add_item(self, item: str):
8 | if len(self.items) < self.__capacity:
9 | self.left_capacity -= 1
10 | self.items.append(item)
11 | else:
12 | return "not enough room in the inventory"
13 |
14 | def get_capacity(self):
15 | return self.__capacity
16 |
17 | def __repr__(self):
18 | return f"Items: {', '.join(self.items)}.\nCapacity left: {self.left_capacity}"
19 |
20 |
21 | inventory = Inventory(2)
22 | inventory.add_item("potion")
23 | inventory.add_item("sword")
24 | print(inventory.add_item("bottle"))
25 | print(inventory.get_capacity())
26 | print(inventory)
--------------------------------------------------------------------------------
/Fundamentals/(I) Objects and Classes/Objects and Classes - Exercise/07. Articles.py:
--------------------------------------------------------------------------------
1 | class Article:
2 | def __init__(self, title, content, author):
3 | self.title = title
4 | self.content = content
5 | self.author = author
6 |
7 | def edit(self, new_content):
8 | self.content = new_content
9 |
10 | def change_author(self, new_author):
11 | self.author = new_author
12 |
13 | def rename(self, new_title):
14 | self.title = new_title
15 |
16 | def __repr__(self):
17 | return f"{self.title} - {self.content}: {self.author}"
18 |
19 |
20 | article = Article(
21 | "Highest Recorded Temperature",
22 | "Temperatures across Europe are unprecedented, according to scientists.",
23 | "Ben Turner"
24 | )
25 | article.edit(
26 | "Syracuse, a city on the coast of the Italian island of Sicily, registered temperatures of 48.8 degrees Celsius"
27 | )
28 | article.rename(
29 | "Temperature in Italy"
30 | )
31 | article.change_author(
32 | "B. T."
33 | )
34 | print(article)
--------------------------------------------------------------------------------
/Fundamentals/(I) Objects and Classes/Objects and Classes - Lab/01. Comment.py:
--------------------------------------------------------------------------------
1 | class Comment:
2 | def __init__(self, username, content, likes=0):
3 | self.username = username
4 | self.content = content
5 | self.likes = likes
6 |
7 |
8 | comment = Comment('user1', 'I like this book')
9 | print(comment.username)
10 | print(comment.content)
11 | print(comment.likes)
12 |
--------------------------------------------------------------------------------
/Fundamentals/(I) Objects and Classes/Objects and Classes - Lab/02. Party.py:
--------------------------------------------------------------------------------
1 | class Party:
2 | def __init__(self):
3 | self.people = []
4 |
5 |
6 | party = Party()
7 |
8 | name = input()
9 | while name != 'End':
10 | party.people.append(name)
11 | name = input()
12 |
13 | print(f"Going: {', '.join(party.people)}")
14 | print(f"Total: {len(party.people)}")
--------------------------------------------------------------------------------
/Fundamentals/(I) Objects and Classes/Objects and Classes - Lab/03. Email.py:
--------------------------------------------------------------------------------
1 | class Email:
2 | def __init__(self, sender, receiver, content):
3 | self.is_sent = False
4 | self.sender = sender
5 | self.receiver = receiver
6 | self.content = content
7 |
8 | def send(self):
9 | self.is_sent = True
10 |
11 | def get_info(self):
12 | return f"{self.sender} says to {self.receiver}: {self.content}. Sent: {self.is_sent}"
13 |
14 |
15 | emails = []
16 | line = input()
17 | while line != "Stop":
18 | email = line.split(' ')
19 | from_person = email[0]
20 | to_person = email[1]
21 | message = email[2]
22 | current_email = Email(from_person, to_person, message)
23 | emails.append(current_email)
24 |
25 | line = input()
26 |
27 | indices = list(map(int, input().split(', ')))
28 |
29 | for index in indices:
30 | emails[index].send()
31 |
32 | for email in emails:
33 | print(email.get_info())
--------------------------------------------------------------------------------
/Fundamentals/(I) Objects and Classes/Objects and Classes - Lab/04. Zoo.py:
--------------------------------------------------------------------------------
1 | class Zoo:
2 | __animals = 0
3 |
4 | def __init__(self, name):
5 | self.zoo_name = name
6 | self.mammals = []
7 | self.fishes = []
8 | self.birds = []
9 |
10 | def add_animals(self, species, name):
11 | if 'mammal' == species:
12 | self.mammals.append(name)
13 | elif "fish" == species:
14 | self.fishes.append(name)
15 | elif "bird" == species:
16 | self.birds.append(name)
17 |
18 | Zoo.__animals += 1
19 |
20 | def get_info(self, species):
21 | curr_list = []
22 | if species == "mammal":
23 | curr_list = self.mammals
24 | species = "Mammals"
25 | elif species == "fish":
26 | curr_list = self.fishes
27 | species = "Fishes"
28 | elif species == "bird":
29 | curr_list = self.birds
30 | species = "Birds"
31 | return f"{species} in {self.zoo_name}: {', '.join(curr_list)}\nTotal animals: {Zoo.__animals}"
32 |
33 |
34 | zoo_name = input()
35 | zoo = Zoo(zoo_name)
36 |
37 | lines = int(input())
38 | for animal in range(lines):
39 | current_animal = input().split(' ')
40 | animal_species = current_animal[0]
41 | animal_name = current_animal[1]
42 | zoo.add_animals(animal_species, animal_name)
43 |
44 | info = input()
45 | print(zoo.get_info(info))
--------------------------------------------------------------------------------
/Fundamentals/(I) Objects and Classes/Objects and Classes - Lab/05. Circle.py:
--------------------------------------------------------------------------------
1 | class Circle:
2 | __py = 3.14
3 |
4 | def __init__(self, diameter):
5 | self.diameter = diameter
6 | self.radius = diameter / 2
7 |
8 | def calculate_circumference(self):
9 | return Circle.__py * self.diameter
10 |
11 | def calculate_area(self):
12 | return Circle.__py * self.radius * self.radius
13 |
14 | def calculate_area_of_sector(self, angle):
15 | return (angle / 360) * Circle.__py * self.radius * self.radius
16 |
17 |
18 | circle = Circle(10)
19 | angle = 5
20 |
21 | print(f"{circle.calculate_circumference():.2f}")
22 | print(f"{circle.calculate_area():.2f}")
23 | print(f"{circle.calculate_area_of_sector(angle):.2f}")
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Exercise/01. Count Chars in a String.py:
--------------------------------------------------------------------------------
1 | words = input().split(" ")
2 | characters_dictionary = {}
3 | for index in range(len(words)):
4 | for char in words[index]:
5 | if char in characters_dictionary:
6 | characters_dictionary[char] += 1
7 | elif char not in characters_dictionary:
8 | characters_dictionary[char] = 1
9 |
10 | for character, value in characters_dictionary.items():
11 | print(f"{character} -> {value}")
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Exercise/02. A Miner Task.py:
--------------------------------------------------------------------------------
1 | miner_dictionary = {}
2 | while True:
3 | resource = input()
4 |
5 | if resource == "stop":
6 | break
7 |
8 | quantity = int(input())
9 |
10 | if resource in miner_dictionary:
11 | miner_dictionary[resource] += quantity
12 |
13 | elif resource not in miner_dictionary:
14 | miner_dictionary[resource] = quantity
15 |
16 |
17 | for item, quantity in miner_dictionary.items():
18 | print(f'{item} -> {quantity}')
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Exercise/03. Capitals.py:
--------------------------------------------------------------------------------
1 | countries = input().split(', ')
2 | cities = input().split(', ')
3 | country_capitals = dict(zip(countries, cities))
4 | for country, city in country_capitals.items():
5 | print(f"{country} -> {city}")
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Exercise/04. Phonebook.py:
--------------------------------------------------------------------------------
1 | phonebook = {}
2 | while True:
3 | command = input()
4 |
5 | if command.isdigit():
6 | break
7 |
8 | name, number = command.split('-')
9 |
10 | phonebook[name] = number
11 |
12 | for contact in range(int(command)):
13 | contact_name = input()
14 | if contact_name not in phonebook:
15 | print(f'Contact {contact_name} does not exist.')
16 | elif contact_name in phonebook:
17 | print(f'{contact_name} -> {phonebook[contact_name]}')
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Exercise/06. Orders.py:
--------------------------------------------------------------------------------
1 | products = {}
2 | while True:
3 | command = input()
4 |
5 | if command == 'buy':
6 | break
7 |
8 | name, price, quantity = command.split(' ')
9 | price, quantity = float(price), int(quantity)
10 |
11 | quantity_left = 0
12 | if name not in products:
13 | products[name] = {}
14 | products[name][price] = 0
15 | else:
16 | quantity_left = list(products[name].values())
17 | quantity_left = quantity_left[0]
18 | products[name].clear()
19 | products[name] = {}
20 | products[name][price] = 0
21 |
22 | products[name][price] += quantity + quantity_left
23 |
24 | for item in products:
25 | for key, value in products[item].items():
26 | result = key * value
27 | print(f"{item} -> {result:.2f}")
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Exercise/07. SoftUni Parking.py:
--------------------------------------------------------------------------------
1 | users = int(input())
2 | parking_lot = {}
3 | for user in range(users):
4 | command = input().split(' ')
5 | if command[0] == 'register':
6 | name = command[1]
7 | license_plate_number = command[2]
8 | if name in parking_lot:
9 | print(f'ERROR: already registered with plate number {license_plate_number}')
10 | continue
11 | parking_lot[name] = license_plate_number
12 | print(f"{name} registered {license_plate_number} successfully")
13 | elif command[0] == 'unregister':
14 | username = command[1]
15 | if username not in parking_lot:
16 | print(f'ERROR: user {username} not found')
17 | continue
18 | del parking_lot[username]
19 | print(f"{username} unregistered successfully")
20 |
21 | for user, license_plate in parking_lot.items():
22 | print(user, '=>', license_plate)
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Exercise/08. Courses.py:
--------------------------------------------------------------------------------
1 | courses = {}
2 | command = input()
3 | while command != 'end':
4 | course, name = command.split(' : ')
5 |
6 | if course not in courses:
7 | courses[course] = [name]
8 |
9 | elif course in courses:
10 | courses[course].append(name)
11 |
12 | command = input()
13 |
14 | for course, students in courses.items():
15 | print(f"{course}: {len(students)}")
16 | print('--', '\n-- '.join(students))
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Exercise/09. Student Academy.py:
--------------------------------------------------------------------------------
1 | students = int(input())
2 | students_grades = {}
3 | for current_student in range(students):
4 | student_name = input()
5 | grade = float(input())
6 | if student_name not in students_grades:
7 | students_grades[student_name] = grade
8 | elif student_name in students_grades:
9 | list_grades = [students_grades[student_name], grade]
10 | students_grades[student_name] = list_grades
11 |
12 | for student, grades in students_grades.items():
13 | if type(grades) == list:
14 | average_grade = sum(grades) / len(grades)
15 | else:
16 | average_grade = grades
17 | if average_grade >= 4.5:
18 | print(student, f'-> {average_grade:.2f}')
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Exercise/10. Company Users.py:
--------------------------------------------------------------------------------
1 | companies = {}
2 | command = input()
3 | while command != 'End':
4 | company, id = command.split(' -> ')
5 |
6 | if company not in companies:
7 | companies[company] = [id]
8 |
9 | elif company in companies and id not in companies[company]:
10 | companies[company].append(id)
11 |
12 | command = input()
13 |
14 | for company, employee_ids in companies.items():
15 | print(company)
16 | print('--', '\n-- '.join(employee_ids))
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Lab/01. Bakery.py:
--------------------------------------------------------------------------------
1 | bakery = input().split(' ')
2 | bakery_stock = {}
3 |
4 | for index in range(0, len(bakery), 2):
5 | bakery_stock[bakery[index]] = int(bakery[index + 1])
6 |
7 | print(bakery_stock)
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Lab/02. Stock.py:
--------------------------------------------------------------------------------
1 | elements = input().split(' ')
2 | stock = {}
3 |
4 | for index in range(0, len(elements), 2):
5 | stock[elements[index]] = int(elements[index + 1])
6 |
7 | searching_products = input().split(' ')
8 |
9 | for curr_product in searching_products:
10 | if curr_product in stock:
11 | print(f"We have {stock[curr_product]} of {curr_product} left")
12 | else:
13 | print(f"Sorry, we don't have {curr_product}")
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Lab/03. Statistics.py:
--------------------------------------------------------------------------------
1 | products = {}
2 | total_products = 0
3 | total_quantity = 0
4 | command = input()
5 | while command != "statistics":
6 | product = command.split(": ")
7 | if product[0] in products:
8 | products[product[0]] += int(product[1])
9 | else:
10 | products[product[0]] = int(product[1])
11 | total_products += 1
12 |
13 | total_quantity += int(product[1])
14 |
15 | command = input()
16 |
17 | print(f"Products in stock:")
18 | for (product, quantity) in products.items():
19 | print(f"- {product}: {quantity}")
20 | print(f"Total Products: {total_products}")
21 | print(f"Total Quantity: {total_quantity}")
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Lab/04. Students.py:
--------------------------------------------------------------------------------
1 | student_information = input()
2 | students = {}
3 |
4 | while not students.get(student_information):
5 | student_information = student_information.split(":")
6 | name = student_information[0]
7 | id = student_information[1]
8 | course = student_information[-1]
9 |
10 | if course not in students:
11 | students[course] = {}
12 | students[course][name] = id
13 | student_information = input()
14 | student_information = student_information.replace("_", " ")
15 |
16 | for key, value in students[student_information].items():
17 | print(f"{key} - {value}")
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Lab/05. ASCII Values.py:
--------------------------------------------------------------------------------
1 | ascii_value = {char: ord(char) for char in input().split(", ")}
2 | print(ascii_value)
3 |
4 |
5 | # print({char: ord(char) for char in input().split(", ")})
6 |
7 |
8 | # characters = input().split(", ")
9 | #
10 | # letters = {}
11 | #
12 | # for letter in characters:
13 | # letters[letter] = ord(letter)
14 | #
15 | # print(letters)
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Lab/06. Odd Occurrences.py:
--------------------------------------------------------------------------------
1 | sequence = input().split(' ')
2 |
3 | final_dic = {}
4 | for element in sequence:
5 | counter = 0
6 | word = element.lower()
7 | for curr_element in sequence:
8 | if curr_element.lower() == word:
9 | counter += 1
10 | if counter % 2 != 0:
11 | final_dic[element.lower()] = element
12 |
13 | print(' '.join(final_dic))
14 |
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/Dictionaries - Lab/07. Word Synonyms.py:
--------------------------------------------------------------------------------
1 | word_synonyms = {}
2 | words = int(input())
3 |
4 | for synonyms in range(words):
5 | word = input()
6 | synonym = input()
7 | if word not in word_synonyms:
8 | word_synonyms[word] = []
9 | word_synonyms[word].append(synonym)
10 | else:
11 | word_synonyms[word].append(synonym)
12 |
13 | for word, synonym in word_synonyms.items():
14 | print(f"{word} - ", end="")
15 | print(*synonym, sep=", ")
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/More Exercise/02. Judge.py:
--------------------------------------------------------------------------------
1 | command = input()
2 |
3 | students_dictionary = {"user": {}, "contest": {}}
4 | user_d = "user"
5 | contest_d = "contest"
6 |
7 | while command != "no more time":
8 | user_name, contest, points = command.split(" -> ")
9 | points = int(points)
10 | if contest not in students_dictionary[contest_d]:
11 | students_dictionary[contest_d][contest] = {}
12 |
13 | if user_name not in students_dictionary[contest_d][contest]:
14 | students_dictionary[contest_d][contest][user_name] = 0
15 |
16 | if user_name not in students_dictionary[user_d]:
17 | students_dictionary[user_d][user_name] = 0
18 |
19 | if user_name in students_dictionary[user_d] and students_dictionary[user_d][user_name] == points:
20 | students_dictionary[user_d][user_name] += points
21 |
22 | if students_dictionary[contest_d][contest][user_name] < points:
23 | students_dictionary[user_d][user_name] += points - students_dictionary[contest_d][contest][user_name]
24 | students_dictionary[contest_d][contest][user_name] = points
25 |
26 | command = input()
27 |
28 |
29 | def show_result():
30 | for contest in students_dictionary[contest_d]:
31 | print(f"{contest}: {len(students_dictionary[contest_d][contest])} participants")
32 | for pos, (name, points) in enumerate(
33 | sorted(students_dictionary[contest_d][contest].items(), key=lambda item: (-item[1], item[0])), 1):
34 | print(f"{pos}. {name} <::> {points}")
35 | print("Individual standings:")
36 | for pos, (name, points) in enumerate(
37 | sorted(students_dictionary[user_d].items(), key=lambda item: (-item[1], item[0])), 1):
38 | print(f"{pos}. {name} -> {points}")
39 |
40 |
41 | show_result()
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/More Exercise/03. MOBA Challenger.py:
--------------------------------------------------------------------------------
1 | command_input = input()
2 |
3 | player_info = {}
4 | best_players = []
5 |
6 |
7 | def duel_players(name_one, name_two):
8 | if (name_one and name_two) in player_info:
9 | for p_one in player_info[name_one]:
10 | if p_one in player_info[name_two]:
11 | total_pl_one = sum(player_info[name_one].values())
12 | total_pl_two = sum(player_info[name_two].values())
13 | if total_pl_one > total_pl_two:
14 | del player_info[name_two]
15 | elif total_pl_one < total_pl_two:
16 | del player_info[name_one]
17 | break
18 |
19 |
20 | def adding_players_roles(player, position, skill):
21 | if player not in player_info:
22 | player_info[player] = {}
23 | if position not in player_info[player]:
24 | player_info[player][position] = 0
25 | if player_info[player][position] < skill:
26 | player_info[player][position] = skill
27 |
28 |
29 | while command_input != "Season end":
30 | if " vs " in command_input:
31 | command_input = command_input.split(" vs ")
32 | duel_players(command_input[0], command_input[-1])
33 | else:
34 | command_input = command_input.split(" -> ")
35 | adding_players_roles(command_input[0], command_input[1], int(command_input[-1]))
36 | command_input = input()
37 |
38 |
39 | def show_result():
40 | for p_name in player_info:
41 | best_players.append({"name": p_name, "total_score": sum(player_info[p_name].values())})
42 | for show in sorted(best_players, key=lambda item: (-item["total_score"], item["name"])):
43 | print(f"{show['name']}: {show['total_score']} skill")
44 | for pos, skill in sorted(player_info[show['name']].items(), key=lambda item: (-item[1], item[0])):
45 | print(f"- {pos} <::> {skill}")
46 |
47 |
48 | show_result()
--------------------------------------------------------------------------------
/Fundamentals/(J) Dictionaries/More Exercise/04. Show White.py:
--------------------------------------------------------------------------------
1 | dwarf_input = input()
2 |
3 | dwarf_info = {}
4 | result_list = []
5 | name_d = "name"
6 | hat_d = "hat"
7 | physic_d = "physic"
8 | hat_len = "hat len"
9 | while dwarf_input != "Once upon a time":
10 | dwarf_input = dwarf_input.split(" <:> ")
11 | dwarf_name = dwarf_input[0]
12 | dwarf_hat_color = dwarf_input[1]
13 | dwarf_physics = int(dwarf_input[-1])
14 | if dwarf_hat_color not in dwarf_info:
15 | dwarf_info[dwarf_hat_color] = {}
16 | if dwarf_name not in dwarf_info[dwarf_hat_color]:
17 | dwarf_info[dwarf_hat_color][dwarf_name] = 0
18 | if dwarf_info[dwarf_hat_color][dwarf_name] < dwarf_physics:
19 | dwarf_info[dwarf_hat_color][dwarf_name] = dwarf_physics
20 | dwarf_input = input()
21 |
22 |
23 | def show_result():
24 | for hat in dwarf_info:
25 | for name, physic in dwarf_info[hat].items():
26 | result_list.append({hat_len: len(dwarf_info[hat]), name_d: name, physic_d: physic, hat_d: hat})
27 | for show in sorted(result_list, key=lambda item: (-item[physic_d], -item[hat_len])):
28 | print(f"({show[hat_d]}) {show[name_d]} <-> {show[physic_d]}")
29 |
30 |
31 | show_result()
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - Exercise/01. Valid Usernames.py:
--------------------------------------------------------------------------------
1 | def valid_username(username):
2 | allowed_symbols = ['_', '-']
3 | if 3 <= len(username) <= 16:
4 | for character in username:
5 | if character.isalnum() or character in allowed_symbols:
6 | continue
7 | return
8 | else:
9 | return
10 | print(username)
11 |
12 |
13 | list_usernames = input().split(', ')
14 | while len(list_usernames):
15 | name = list_usernames[0]
16 | valid_username(name)
17 | list_usernames.pop(0)
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - Exercise/02. Character Multiplier.py:
--------------------------------------------------------------------------------
1 | def characters_multiply(first_string, second_string):
2 | first_string = [ord(num) for num in first_string]
3 | second_string = [ord(num) for num in second_string]
4 | first_string_len = len(first_string)
5 | second_string_len = len(second_string)
6 | if first_string_len > second_string_len:
7 | for index in range(first_string_len - second_string_len):
8 | second_string.append(1)
9 | elif first_string_len < second_string_len:
10 | for index in range(second_string_len - first_string_len):
11 | first_string.append(1)
12 | print(sum([first_string[index] * second_string[index] for index in range(len(first_string))]))
13 |
14 |
15 | string_one, string_two = input().split()
16 | characters_multiply(string_one, string_two)
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - Exercise/03. Extract File.py:
--------------------------------------------------------------------------------
1 | file, file_extension = input().split(".")
2 | file_name = file.split('\\')[-1]
3 | print("File name:", file_name)
4 | print("File extension:", file_extension)
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - Exercise/04. Caesar Cipher.py:
--------------------------------------------------------------------------------
1 | def caesar_cipher(string):
2 | result = ''
3 | for char in string:
4 | result += chr(ord(char) + 3)
5 | return result
6 |
7 |
8 | string = input()
9 | print(caesar_cipher(string))
10 |
11 |
12 | # print("".join([chr(ord(letter) + 3) for letter in input()]))
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - Exercise/05. Emoticon Finder.py:
--------------------------------------------------------------------------------
1 | def emoticon_finder(string):
2 | for index, char in enumerate(string):
3 | if char == ':':
4 | print(f'{char}{string[index + 1]}')
5 |
6 |
7 | string = input()
8 | emoticon_finder(string)
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - Exercise/06. Replace Repeating Chars.py:
--------------------------------------------------------------------------------
1 | def replace_repeating_characters(string):
2 | for index, char in enumerate(string):
3 | try:
4 | if string[index + 1] != char:
5 | print(char, end='')
6 | except IndexError:
7 | print(char, end='')
8 |
9 |
10 | string = input()
11 | replace_repeating_characters(string)
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - Exercise/07. String Explosion.py:
--------------------------------------------------------------------------------
1 | def string_explosion(string):
2 | result = ''
3 | what_left = 0
4 | for letter in string:
5 | if len(letter) > 1 and any(map(str.isdigit, letter)):
6 | what_left += (int(letter[0]) - 1)
7 | if what_left >= len(letter):
8 | result += ">"
9 | else:
10 | result += ">" + letter[1 + what_left:]
11 | what_left = 0
12 | elif len(letter) == 1 and letter.isdigit():
13 | if int(letter) > 1:
14 | what_left += (int(letter) - 1)
15 | result += ">"
16 | else:
17 | result += letter
18 |
19 | return result
20 |
21 |
22 | string = input().split(">")
23 | print(string_explosion(string))
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - Lab/01. Reverse Strings.py:
--------------------------------------------------------------------------------
1 | def reverse_string(string: str):
2 | reversed_string = string[::-1]
3 | return f'{string} = {reversed_string}'
4 |
5 |
6 | string = input()
7 | while string != "end":
8 | print(reverse_string(string))
9 | string = input()
10 |
11 |
12 | # string = input()
13 | # while string != "end":
14 | # print(string, '=', string[::-1])
15 | # string = input()
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - Lab/02. Repeat Strings.py:
--------------------------------------------------------------------------------
1 | def repeat_string(strings):
2 | for word in strings:
3 | length_word = len(word)
4 | print(word * length_word, end='')
5 |
6 |
7 | strings = input().split(' ')
8 | repeat_string(strings)
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - Lab/03. Substring.py:
--------------------------------------------------------------------------------
1 | def substring(remove_string, main_string):
2 | final_string = main_string
3 | while remove_string in final_string:
4 | final_string = final_string.replace(remove_string, '')
5 |
6 | return final_string
7 |
8 |
9 | first_string = input()
10 | second_string = input()
11 | print(substring(first_string, second_string))
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - Lab/04. Text Filter.py:
--------------------------------------------------------------------------------
1 | def text_filter(filter_words, string):
2 | for banned_word in filter_words:
3 | asterisks = '*' * len(banned_word)
4 | string = string.replace(banned_word, asterisks)
5 |
6 | return string
7 |
8 |
9 | banned_words = input().split(', ')
10 | string = input()
11 |
12 | print(text_filter(banned_words, string))
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - Lab/05. Digits, Letters and Other.py:
--------------------------------------------------------------------------------
1 | def digits_letters_characters(string):
2 | letters = ''
3 | digits = ''
4 | characters = ''
5 | for character in string:
6 | if character.isalpha():
7 | letters += character
8 | elif character.isdigit():
9 | digits += character
10 | else:
11 | characters += character
12 | return f'{digits}\n{letters}\n{characters}'
13 |
14 |
15 | string = input()
16 | print(digits_letters_characters(string))
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - More Exercise/01. Extract Person Information.py:
--------------------------------------------------------------------------------
1 | def extract_information(string):
2 | name = ''
3 | age = ''
4 | for index, char in enumerate(string):
5 | if char == '@':
6 | while True:
7 | index += 1
8 |
9 | if string[index] == '|':
10 | break
11 |
12 | name += string[index]
13 | elif char == '#':
14 | while True:
15 | index += 1
16 |
17 | if string[index] == '*':
18 | break
19 |
20 | age += string[index]
21 |
22 | return f'{name} is {age} years old.'
23 |
24 |
25 | string_lines = int(input())
26 |
27 | for person_information in range(string_lines):
28 | information = input()
29 | print(extract_information(information))
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - More Exercise/02. ASCII Sumator.py:
--------------------------------------------------------------------------------
1 | def ascii_sumator(first_char, second_char, sequence):
2 | starting_character = ord(first_char)
3 | ending_character = ord(second_char)
4 | sum_characters = 0
5 | for char in sequence:
6 | number = ord(char)
7 | if starting_character < number < ending_character:
8 | sum_characters += number
9 |
10 | return sum_characters
11 |
12 |
13 | start_char = input()
14 | end_char = input()
15 | string = input()
16 | print(ascii_sumator(start_char, end_char, string))
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - More Exercise/03. Treasure Finder.py:
--------------------------------------------------------------------------------
1 | secret_key = [int(x) for x in input().split()]
2 | secret_msg = input()
3 |
4 | how_long = len(secret_key)
5 | while secret_msg != "find":
6 | secret_text = "".join([chr(ord(secret_msg[i]) - secret_key[i % how_long]) for i in range(len(secret_msg))])
7 | item = secret_text.split("&")[-2]
8 | location = secret_text.split("<")[-1][:-1]
9 | print(f"Found {item} at {location}")
10 | secret_msg = input()
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - More Exercise/04. Morse Code Translator.py:
--------------------------------------------------------------------------------
1 | def translator(dictionary, string):
2 | message = ''
3 | for letter in string:
4 | for ltr in letter.split(" "):
5 | if ltr != '':
6 | message += dictionary[ltr]
7 | message += " "
8 |
9 | return message
10 |
11 |
12 | morse_code = {'..-.': 'F', '-..-': 'X',
13 | '.--.': 'P', '-': 'T', '..---': '2',
14 | '....-': '4', '-----': '0', '--...': '7',
15 | '...-': 'V', '-.-.': 'C', '.': 'E', '.---': 'J',
16 | '---': 'O', '-.-': 'K', '----.': '9', '..': 'I',
17 | '.-..': 'L', '.....': '5', '...--': '3', '-.--': 'Y',
18 | '-....': '6', '.--': 'W', '....': 'H', '-.': 'N', '.-.': 'R',
19 | '-...': 'B', '---..': '8', '--..': 'Z', '-..': 'D', '--.-': 'Q',
20 | '--.': 'G', '--': 'M', '..-': 'U', '.-': 'A', '...': 'S', '.----': '1'}
21 |
22 | words = input().split(" | ")
23 | print(translator(morse_code, words))
--------------------------------------------------------------------------------
/Fundamentals/(K) Text Processing/Text Processing - More Exercise/05. HTML.py:
--------------------------------------------------------------------------------
1 | title = input()
2 | content = input()
3 | print(f"""
4 |
5 | {title}
6 |
7 |
8 | {content}
9 |
10 | """, end='')
11 | comment = input()
12 | while comment != "end of comments":
13 | print('')
14 | print(comment)
15 | print('
')
16 | comment = input()
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - Exercise/01. Capture the Numbers.py:
--------------------------------------------------------------------------------
1 | import re
2 | pattern = r'\d+'
3 | digits = []
4 | while True:
5 | string = input()
6 | if string:
7 | numbers = re.findall(pattern, string)
8 | if numbers:
9 | digits.append(' '.join(numbers))
10 | continue
11 | break
12 |
13 | print(' '.join(digits))
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - Exercise/02. Find Variable Names in Sentences.py:
--------------------------------------------------------------------------------
1 | import re
2 | pattern = r'\b_(?P[A-Za-z0-9]+\b)'
3 | strings = input()
4 | variables = re.findall(pattern, strings)
5 | print(','.join(variables))
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - Exercise/03. Find Occurrences of Word in Sentence.py:
--------------------------------------------------------------------------------
1 | import re
2 | string = input().lower()
3 | word = input().lower()
4 | pattern = fr'({word})\b'
5 | matches = re.findall(pattern, string)
6 | print(len(matches))
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - Exercise/04. Extract Emails.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | string = input()
4 | pattern = r'\s(([a-z0-9]+[a-z0-9\.\-\_]*)@[a-z\-]+(\.[a-z]+)+)\b'
5 | emails = re.findall(pattern, string)
6 | for email in emails:
7 | print(email[0])
8 |
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - Exercise/05. Furniture.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | main_string = input()
4 |
5 | pattern = re.compile(
6 | r">>(?P[A-Za-z]+)<<(?P[0-9]+[\.0-9]*)!(?P[0-9]+)")
7 |
8 | total_money_spend = 0
9 | print("Bought furniture:")
10 | while main_string != "Purchase":
11 | result = re.finditer(pattern, main_string)
12 | for show in result:
13 | total_money_spend += float(show["price"]) * float(show["quantity"])
14 | print(show["furniture_name"])
15 | main_string = input()
16 |
17 | print(f"Total money spend: {total_money_spend:.2f}")
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - Lab/01. Match Full Name.py:
--------------------------------------------------------------------------------
1 | import re
2 | names = input()
3 | regex = r'\b[A-Z][a-z]+ [A-Z][a-z]+\b'
4 | matches = re.findall(regex, names)
5 | print(' '.join(matches))
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - Lab/02. Match Phone Number.py:
--------------------------------------------------------------------------------
1 | import re
2 | phone_numbers = input()
3 | regex = r'(\+359 2 [0-9]{3} [0-9]{4}|\+359-2-[0-9]{3}-[0-9]{4})\b'
4 | matches = re.findall(regex, phone_numbers)
5 | print(', '.join(matches))
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - Lab/03. Match Dates.py:
--------------------------------------------------------------------------------
1 | import re
2 | dates = input()
3 | regex = r'(?P\d{2})([\/.-])(?P[A-Z][a-z]{2})\2([0-9]{4})\b'
4 | matches = re.findall(regex, dates)
5 | for match in matches:
6 | print(f'Day: {match[0]}, Month: {match[2]}, Year: {match[3]}')
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - Lab/04. Match Numbers.py:
--------------------------------------------------------------------------------
1 | import re
2 | pattern = r"(^|(?<=\s))-?([0]|[1-9][0-9]*)(\.\d+)?($|(?=\s))"
3 | text = input()
4 | matches = re.finditer(pattern, text)
5 | for match in matches:
6 | print(match.group(), end=' ')
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - More Exercise/01. Race.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | name_of_participants = {name.replace(" ", ""): 0 for name in input().split(",")}
4 | racer_code = input()
5 | letters_d = re.compile(r"([A-Za-z])")
6 | numbers_d = re.compile(r"([0-9])")
7 | while racer_code != "end of race":
8 | find_name = "".join(re.findall(letters_d, racer_code))
9 | find_numbers = sum(int(num) for num in re.findall(numbers_d, racer_code))
10 | if find_name in name_of_participants.keys():
11 | name_of_participants[find_name] += find_numbers
12 | racer_code = input()
13 |
14 | name_of_participants = sorted(name_of_participants.items(), key=lambda x: -x[1])
15 |
16 | print(f"1st place: {name_of_participants[0][0]}")
17 | print(f"2nd place: {name_of_participants[1][0]}")
18 | print(f"3rd place: {name_of_participants[2][0]}")
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - More Exercise/02. SoftUni Bar Income.py:
--------------------------------------------------------------------------------
1 | import re
2 | total_income = 0
3 | pattern = re.compile(
4 | r"(%)(?P[A-Z][a-z]+)\1([^\|\$\%\.]*)"
5 | r"<(?P[\w]+)>([^\|\$\%\.]*)"
6 | r"\|(?P[\d]+)\|([^\|\$\%\.]*)"
7 | r"(?P[1-9]+[.0-9]*)\$")
8 |
9 |
10 | data_input = input()
11 |
12 | while data_input != "end of shift":
13 | result = re.finditer(pattern, data_input)
14 | for show in result:
15 | current_price = float(show["count"]) * float(show["price"])
16 | print(f"{show['customer']}: {show['product']} - {current_price:.2f}")
17 | total_income += current_price
18 | data_input = input()
19 |
20 | print(f"Total income: {total_income:.2f}")
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - More Exercise/03. Star Enigma.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | number_of_messages = int(input())
4 |
5 | planets_info = {"Attacked": [], "Destroyed": [], "A": "Attacked", "D": "Destroyed"}
6 | pattern = re.compile(r"@(?P[A-Za-z]+)([^\@\-\!\:\>]*)"
7 | r":(?P[0-9]+)([^\@\-\!\:\>]*)"
8 | r"(\!)(?P[AD])\5([^\@\-\!\:\>]*)"
9 | r"->(?P[0-9]+)")
10 |
11 | for msg in range(number_of_messages):
12 | current_msg = input()
13 | code_decrypt = sum(current_msg.lower().count(char) for char in "star")
14 | decode_msg = "".join(chr(ord(char) - code_decrypt) for char in current_msg)
15 | result = re.finditer(pattern, decode_msg)
16 | for show in result:
17 | planets_info[planets_info[show["attack_type"]]].append(show["planet_name"])
18 |
19 | for type_attack in list(planets_info.keys())[:2]:
20 | planet_count = len(planets_info[type_attack])
21 | print(f"{type_attack} planets: {planet_count}")
22 | if planet_count:
23 | for planet in sorted(planets_info[type_attack]):
24 | print(f"-> {planet}")
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - More Exercise/04. Nether Realms.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | demons = re.split(", *", input())
4 | demon_book = {}
5 |
6 | demon_health_pattern = r'[^\d\+\-*\/\.]'
7 | demon_damage_pattern = r'(?:\+|-)?[0-9]+(?:\.[0-9]+)?'
8 | demon_operators_pattern = r'[*\/]'
9 |
10 | for demon in demons:
11 | demon = demon.strip()
12 | demon_health = re.findall(demon_health_pattern, demon)
13 | demon_book[demon] = []
14 | demon_book[demon].append(sum(ord(match) for match in demon_health))
15 |
16 | demon_damage = re.finditer(demon_damage_pattern, demon)
17 | operators = re.findall(demon_operators_pattern, demon)
18 | current_demon_damage = 0
19 |
20 | for value in demon_damage:
21 | current_demon_damage += float(value.group(0))
22 |
23 | for operator in operators:
24 | if operator == '*':
25 | current_demon_damage *= 2
26 | elif operator == '/':
27 | current_demon_damage /= 2
28 |
29 | demon_book[demon].append(current_demon_damage)
30 |
31 | for demon, qualities in sorted(demon_book.items()):
32 | print(f'{demon} - {qualities[0]} health, {qualities[1]:.2f} damage')
--------------------------------------------------------------------------------
/Fundamentals/(L) Regular Expressions/Regular Expressions - More Exercise/05. HTML Parser.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | text = input()
4 |
5 | pattern_title = r"(?:)(?P.+)(?:)"
6 | pattern_body = r"(?:)(?P.+)(?:)"
7 | title = re.search(pattern_title, text).group("title")
8 | body = re.search(pattern_body, text).group("body")
9 | title = re.sub(r"[ ]+", " ", re.sub(r"\\n|\\t", "", re.sub(r"<[^>]*>", "", title)))
10 | body = re.sub(r"[ ]+", " ", re.sub(r"\\n|\\t", "", re.sub(r"<[^>]*>", "", body)))
11 | print(f"Title: {title}")
12 | print(f"Content: {body}")
--------------------------------------------------------------------------------
/__pycache__/Errors.cpython-310.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/__pycache__/Errors.cpython-310.pyc
--------------------------------------------------------------------------------
/__pycache__/Errors.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/__pycache__/Errors.cpython-39.pyc
--------------------------------------------------------------------------------
/__pycache__/file_manipulator.cpython-310.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/__pycache__/file_manipulator.cpython-310.pyc
--------------------------------------------------------------------------------
/__pycache__/file_manipulator.cpython-39.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/__pycache__/file_manipulator.cpython-39.pyc
--------------------------------------------------------------------------------
/softuni_exercise_solutions.app.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MitkoVtori/softuni_exercise_solutions/7d8c75ee065d4aff0010fa7c6b4dca9f24b9caeb/softuni_exercise_solutions.app.zip
--------------------------------------------------------------------------------