An open API service indexing awesome lists of open source software.

https://github.com/bregman-arie/python-exercises


https://github.com/bregman-arie/python-exercises

Last synced: 6 months ago
JSON representation

Awesome Lists containing this project

README

          

:information_source:  This repo contains questions and exercises to learn and practice Python

:bar_chart:  There are currently **231** exercises and questions

- [Exercises](#exercises)
- [Hello World](#hello-world)
- [Objects & Data Types](#objects--data-types)
- [Variables](#variables)
- [Booleans](#booleans)
- [Strings](#strings)
- [Numbers](#numbers)
- [Lists & Tuples](#lists--tuples)
- [Dictionaries](#dictionaries)
- [Loops](#loops)
- [Functions](#functions)
- [Classes](#classes)
- [OOP](#oop)
- [Magic Methods](#magic-methods)
- [Unit Testing](#unit-testing)
- [Exceptions](#exceptions)
- [Regex](#regex)
- [Files](#files)
- [Operating Systems](#operating-systems)
- [Improve the Code](#improve-the-code)
- [Type Hinting](#type-hinting)
- [Misc](#misc)
- [Questions](#questions)
- [Hello World](#hello-world-1)
- [Classes](#classes-1)
- [Strings](#strings-1)
- [Lists](#lists)

# Exercises


## Hello World

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Hello World! | [Exercise](exercises/hello_world/hello_world.md) | Solution](solutions/hello_world/hello_world.md | |
| Python Characteristics | [Exercise](exercises/hello_world/python_characteristics.md) | [Solution](solutions/hello_world/python_characteristics.md) | |
| What is the result? - Level 1 | [Exercise](exercises/hello_world/what_is_the_result_lvl_1.md) | [Solution](solutions/hello_world/what_is_the_result_lvl_1.md) | |
| What is the result? - Level 2 | [Exercise](exercises/hello_world/what_is_the_result_lvl_2.md) | | |


## Objects & Data Types

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Objects 101 | [Exercise](exercises/data_types/objects_101.md) | [Solution](solutions/data_types/objects_101.md) | |
| Data Types? I know a few | [Exercise](exercises/data_types/I_know_a_few.md) | [Solution](solutions/exceptions/I_know_a_few.md) | |
| Choose a Data Type - level 1 | [Exercise](exercises/data_types/choose_datatype_level_1.md) | [Solution](solutions/data_types/choose_datatype_level_1.md) | |
| Choose a Data Type - level 2 | [Exercise](exercises/data_types/choose_datatype_level_2.md) | [Solution](solutions/data_types/choose_datatype_level_2.md) | |
| Mutability | [Exercise](exercises/data_types/mutability.md) | [Solution](solutions/data_types/mutability.md) | |
| Strongly Typed | [Exercise](exercises/data_types/strongly_typed.md) | [Solution](solutions/data_types/strongly_typed.md) | |
| Object Creation | [Exercise](exercises/data_types/object_creation.md) | [Solution](solutions/data_types/object_creation.md) | |


## Variables

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Valid Names | [Exercise](exercises/variables/valid_names.md) | [Solution](solutions/variables/valid_names.md) | |
| Locations or Names | [Exercise](exercises/variables/locations_or_names.md) | [Solution](solutions/variables/locations_or_names.md) | |
| Types | [Exercise](exercises/variables/types.md) | [Solution](solutions/variables/types.md) | |
| Multiple Value Assignment | [Exercise](exercises/variables/multiple_value_assigment.md) | [Solution](solutions/variables/multiple_value_assigment.md) | |
| Copying Variables | [Exercise](exercises/variables/copying_variables.md) | [Solution](solutions/variables/copying_variables.md) | |
| Mutable Objects | [Exercise](exercises/variables/mutable_objects.md) | [Solution](solutions/variables/mutable_objects.md) | |


## Booleans

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| True or False? | [Exercise](exercises/booleans/true_or_false.md) | [Solution](solutions/booleans/true_or_false.md) | |
| Conversion | [Exercise](exercises/booleans/conversion.md) | [Solution](solutions/booleans/conversion.md) | |


## Strings

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| 22 times | [Exercise](exercises/hello_world/22_times.md) | | |
| Variables | [Exercise](exercises/strings/variables.md) | [Solution](solutions/strings/variables.md) | |
| What is the result? - Level 1 | [Exercise](exercises/strings/what_is_the_result_lvl_1.md) | [Solution](solutions/strings/what_is_the_result_lvl_1.md) | |
| What is the result? - Level 2 | [Exercise](exercises/strings/what_is_the_result_lvl_2.md) | [Solution](solutions/strings/what_is_the_result_lvl_2.md) | |
| Starts with a letter | [Exercise](exercises/strings/letter_start.md) | [Solution](solutions/strings/letter_start.md) | |
| Change Strings | [Exercise](exercises/strings/change_strings.md) | [Solution](solutions/strings/change_strings.md) | |
| All Digits | [Exercise](exercises/strings/all_digits.md) | [Solution](solutions/strings/all_digits.md) | |
| Removing Characters | [Exercise](exercises/strings/removing_characters.md) | [Solution](solutions/strings/removing_characters.md) | |
| Reverse a String | [Exercise](exercises/strings/reverse_string.md) | [Solution](solutions/strings/reverse_string.md) | |
| Compress Strings | [Exercise](exercises/strings/compress_strings.md) | | |
| Slicing - Level 1 | [Exercise](exercises/strings/slicing_lvl_1.md) | [Solution](solutions/strings/slicing_lvl_1.md) | |
| Slicing - Level 2 | [Exercise](exercises/strings/slicing_lvl_2.md) | [Solution](solutions/strings/slicing_lvl_2.md) | |
| Swap Case | [Exercise](exercises/swap_case/exercise.md) | [Solution](exercises/swap_case/solution.py) | HackerRank |
| Count Substring | [Exercise](exercises/count_substring/exercise.md) | [Solution](exercises/count_substring/solution.py) | HackerRank |
| Capitalize! | [Exercise](exercises/capitalize/exercise.md) | [Solution](exercises/capitalize/solution.py) | HackerRank |


## Numbers

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| What is the result? | [Exercise](exercises/numbers/what_is_the_result.md) | [Solution](solutions/numbers/what_is_the_result.md) | |
| Operations - Level 1 | [Exercise](exercises/numbers/operations_lvl_1.md) | [Solution](solutions/numbers/operations_lvl_1.md) | |
| Operations - Level 2 | [Exercise](exercises/numbers/operations_lvl_2.md) | [Solution](solutions/numbers/operations_lvl_2.md) | |
| Bases | [Exercise](exercises/numbers/bases.md) | [Solution](solutions/numbers/bases.md) | |
| Palindrome | [Exercise](exercises/numbers/palindrome.md) | [Solution](solutions/numbers/palindrome.md) | |


## Lists & Tuples

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Access List Items | [Exercise](exercises/hello_world/access_list_items.md) | [Solution](solutions/hello_world/access_list_items.md) | |
| Equal Lists | [Exercise](exercises/lists/equal_lists.md) | [Solution](solutions/lists/equal_lists.md) | |
| Length | [Exercise](exercises/hello_world/length.md) | | |
| Append & Insert | [Exercise](exercises/lists/append_and_insert.md) | [Solution](solutions/lists/append_and_insert.md) | |
| Min Max | [Exercise](exercises/lists/min_max.md) | [Solution](solutions/lists/min_max.md) | |
| Three Biggest Items | [Exercise](exercises/lists/three_biggest_items.md) | [Solution](solutions/lists/three_biggest_items.md) | |
| What is the result? - Level 1 | [Exercise](exercises/lists/what_is_the_result_lvl_1.md) | [Solution](solutions/lists/what_is_the_result_lvl_1.md) | |
| What is the result? - Level 2 | [Exercise](exercises/lists/what_is_the_result_lvl_2.md) | [Solution](solutions/lists/what_is_the_result_lvl_2.md) | |
| Running Sum | [Exercise](exercises/lists/running_sum/exercise.md) | [Solution](solutions/lists/running_sum/solution.py) | |
| Remove Duplicates from Sorted List | [Exercise](exercises/lists/remove_duplicates/exercise.md) | [Solution](exercises/lists/remove_duplicates/solution.py) | LeetCode |
| Find the Runner-Up Score! | [Exercise](exercises/lists/find_the_runner_up_score/exercise.md) | [Solution](solutions/lists/find_the_runner_up_score/solution.py) | HackerRank |
| Nested Lists | [Exercise](exercises/lists/nested_lists/exercise.md) | [Solution](solutions/lists/nested_lists/solution.py) | HackerRank |


## Dictionaries

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Facts Only | [Exercise](exercises/dicts/facts_only.md) | [Solution](solutions/dict/facts_only.md) | |


## Loops

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Break Out | [Exercise](exercises/loops/break_out.md) | [Solution](solutions/loops/break_out.md) | |
| Break Out 2 | [Exercise](exercises/loops/break_out.md) | [Solution](solutions/loops/break_out.md) | |
| Every character | [Exercise](exercises/loops/every_char.md) | [Solution](solutions/loops/every_char.md) | |
| Stream of Numbers | [Exercise](exercises/loops/numbers_stream.md) | [Solution](solutions/loops/numbers_stream.md) | |
| Refactor-1 | [Exercise](exercises/loops/refactor_1.md) | [Solution](solutions/loops/refactor_1.py) | |


## Functions

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| My First Function | [Exercise](exercises/functions/my_first_function.md) | [Solution](solutions/functions/my_first_function.md) | |
| Calculator | [Exercise](exercises/functions/calculator.md) | [Solution](solutions/functions/calculator.md) | |
| First Class Objects | [Exercise](exercises/functions/first_class_objects.md) | [Solution](solutions/functions/first_class_objects.md) | |


## Classes

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Classes 101 | [Exercise](exercises/classes/101.md) | [Solution](solutions/classes/101.md) | |
| Attributes | [Exercise](exercises/classes/attributes/exercise.md) | [Solution](exercises/classes/attributes/solution.md) | |
| Print Order | [Exercise](exercises/classes/print_order/exercise.md) | [Solution](exercises/classes/print_order/solution.md)


## OOP

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Inheritance | [Exercise](exercises/oop/inheritance.md) | [Solution](solutions/oop/inheritance.md) | |

## Magic Methods

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Length Magic Method | [Exercise](exercises/magic_methods/length.md) | | |

## Unit Testing

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Calculator Unit Tests | [Exercise](exercises/unit_testing/calculator.md) | [Solution](solutions/unit_testing/calculator.md) | |
| Fix Calculator Unit Tests | [Exercise](exercises/unit_testing/fix_calculator_tests.md) | | |

## Exceptions

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| What exception is raised? - Level 1 | [Exercise](exercises/exceptions/what_exception_is_raised_lvl_1.md) | [Solution](solutions/exceptions/what_exception_is_raised_lvl_1.md) | |
| What exception is raised? - Level 2 | [Exercise](exercises/exceptions/what_exception_is_raised_lvl_2.md) | [Solution](solutions/exceptions/what_exception_is_raised_lvl_2.md) | |
| Bound To It | [Exercise](exercises/exceptions/bound_to_it/exercise.md) | [Solution](exercises/exceptions/bound_to_it/solution.md)

## Regex

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Substitute Strings | [Exercise](exercises/regex/substitute_strings.md) | [Solution](solutions/exceptions/substitute_strings.md) | |

## Files

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Read a File | [Exercise](exercises/files/read_file.md) | | |
| Reverse a file | [Exercise](exercises/files/reverse_file.md) | | |
| Print specific line | [Exercise](exercises/files/print_specific_line.md) | | |

## Operating Systems

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| File exists | [Exercise](exercises/os/file_exists.md) | | |
| Print all the files in a directory | [Exercise](exercises/os/print_all_files_in_dir.md) | | |

## Improve the Code

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| If True | [Exercise](exercises/improve_the_code/if_true.md) | [Solution](solutions/improve_the_code/if_true.md) | |
| Walrus | [Exercise](exercises/improve_the_code/walrus.md) | [Solution](solutions/improve_the_code/walrus.md) | |
| Vowel Letters | [Exercise](exercises/improve_the_code/vowel_letters.md) | [Solution](solutions/improve_the_code/vowel_letters.md) | |

## Type Hinting

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Type Hinting Facts Only | [Exercise](exercises/type_hinting/facts_only.md) | [Solution](solutions/type_hinting/facts_only.md) | |
| Pros & Cons | [Exercise](exercises/type_hinting/pros_and_cons.md) | [Solution](solutions/type_hinting/pros_and_cons.md) | |
| Type Hinting 101 | [Exercise](exercises/type_hinting/type_hinting_101.md) | [Solution](solutions/type_hinting/type_hinting_101.md) | |
| Type Hinting 102 | [Exercise](exercises/type_hinting/type_hinting_102.md) | [Solution](solutions/type_hinting/type_hinting_102.md) | |

## Misc

|Name|Objective & Instructions|Solution|Comments|
|--------|--------|------|----|
| Random Number | [Exercise](exercises/misc/random_number.md) | | |
| Random Item | [Exercise](exercises/misc/random_item.md) | | |

## Lambda

|Name|Objective & Instructions|Solution||
|--------|--------|------|----|
| Multiply the arguments and return the result | [Exercise](exercises/Lambda/Exe1.md) | [Solution](solutions/lambda/soluntion1.md) | |
| Write a python program to generate a function to double a specified number. | [Exercise](exercises/Lambda/Exe2.md) | [Solution](solutions/lambda/solution2.md) | | |

# Questions


## Hello World

How to print "Hello World"?

`print("Hello World")`

How to print "Hello Amazing" and then print "World" on the same line? (to clarify, you should use two print statements)

```Python
print("Hello Amazing", end=" ")
print("World")
```

The following program reads two numbers from the user

```python
x = int(input())
y = int(input())
```

print the sum and the difference between the numbers

```python
print(x + y)
print(x - y)
```

## Conditionals

Read a number from the user and check whether it's even. If it's even, print "yay". If it's not, print "nay"

```python
x = int(input())

if x % 2 == 0:
print("yay")
else:
print("nay")
```

## Loops

given an integer (n) print all the numbers between 0 and n (including n)

```python
for i in range(n + 1):
print(i)
```

given an integer (n) print all the numbers between 0 and n (including n) that are even

```python
for i in range(n + 1):
if i % 2 == 0:
print(i)
```


## Classes

Define a class that does nothing

```python
class SomeClass:
pass
```

True or False? If c is an instance of a class, then in c.x = 1, x is a variable of the value 1

False. `x` is an attribute in the case `c.x = 1`

True or False? Every object in Python has attributes

True. You can think on attributes as private dictionaries but instead of accessing them with `[]` or `.get`, they are accessed by using a dot.

True or False? As opposed to variables, attributes can't contain any Python object, only several selected types

False. Like variables, attributes can contain any Python object.

## Strings

How to convert "2 0 1 7" to the list [2, 0, 1, 7]?

```python
[int(i) for in in "2 0 1 7".split()]
```

## Lists

How to remove duplicates from a given sorted list?

```python

```

#### Python - OOP

Explain inheritance and how to use it in Python

Explain and demonstrate class attributes & instance attributes

In the following block of code `x` is a class attribute while `self.y` is a instance attribute

```
class MyClass(object):
x = 1

def __init__(self, y):
self.y = y
```

#### Python - Exceptions

What is an error? What is an exception? What types of exceptions are you familiar with?

```
# Note that you generally don't need to know the compiling process but knowing where everything comes from
# and giving complete answers shows that you truly know what you are talking about.

Generally, every compiling process have a two steps.
- Analysis
- Code Generation.

Analysis can be broken into:
1. Lexical analysis (Tokenizes source code)
2. Syntactic analysis (Check whether the tokens are legal or not, tldr, if syntax is correct)

for i in 'foo'
^
SyntaxError: invalid syntax

We missed ':'

3. Semantic analysis (Contextual analysis, legal syntax can still trigger errors, did you try to divide by 0,
hash a mutable object or use an undeclared function?)

1/0
ZeroDivisionError: division by zero

These three analysis steps are the responsible for error handlings.

The second step would be responsible for errors, mostly syntax errors, the most common error.
The third step would be responsible for Exceptions.

As we have seen, Exceptions are semantic errors, there are many builtin Exceptions:

ImportError
ValueError
KeyError
FileNotFoundError
IndentationError
IndexError
...

You can also have user defined Exceptions that have to inherit from the `Exception` class, directly or indirectly.

Basic example:

class DividedBy2Error(Exception):
def __init__(self, message):
self.message = message

def division(dividend,divisor):
if divisor == 2:
raise DividedBy2Error('I dont want you to divide by 2!')
return dividend / divisor

division(100, 2)

>>> __main__.DividedBy2Error: I dont want you to divide by 2!
```

Explain Exception Handling and how to use it in Python

**Exceptions:** Errors detected during execution are called Exceptions.

**Handling Exception:** When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
Exceptions can be handled using `try` and `except` statement in python.

**Example:** Following example asks the user for input until a valid integer has been entered.
If user enter a non-integer value it will raise exception and using except it will catch that exception and ask the user to enter valid integer again.

```py
while True:
try:
a = int(input("please enter an integer value: "))
break
except ValueError:
print("Ops! Please enter a valid integer value.")

```

For more details about errors and exceptions follow this [https://docs.python.org/3/tutorial/errors.html](https://docs.python.org/3/tutorial/errors.html)

What is the result of running the following function?

```
def true_or_false():
try:
return True
finally:
return False
```


False

#### Python Built-in functions

Explain the following built-in functions (their purpose + use case example):

* repr
* any
* all

What is the difference between repr function and str?

What is the __call__ method?

It is used to emulate callable objects. It allows a class instance to be called as a function.

- Example code:

```
class Foo:
def __init__(self: object) -> None:
pass
def __call__(self: object) -> None:
print("Called!")

f = Foo()
f()
```

- Result:

```
Called!
```

Do classes has the __call__ method as well? What for?

What _ is used for in Python?

1. Translation lookup in i18n
2. Hold the result of the last executed expression or statement in the interactive interpreter.
3. As a general purpose "throwaway" variable name. For example: x, y, _ = get_data() (x and y are used but since we don't care about third variable, we "threw it away").

Explain what is GIL

Python Global Interpreter Lock (GIL) is a type of process lock which is used by python whenever it deals with processes. Generally, Python only uses only one thread to execute the set of written statements. This means that in python only one thread will be executed at a time

What is Lambda? How is it used?

A lambda expression is an 'anonymous' function, the difference from a normal defined function using the keyword `def`` is the syntax and usage.

The syntax is:

```lambda[parameters]: [expresion]```

**Examples:**

* A lambda function add 10 with any argument passed.

```py
x = lambda a: a + 10
print(x(10))
```

* An addition function

```py
addition = lambda x, y: x + y
print(addition(10, 20))
```

* Squaring function

```py
square = lambda x : x ** 2
print(square(5))
```
Generally it is considered a bad practice under PEP 8 to assign a lambda expresion, they are meant to be used as parameters and inside of other defined functions.

#### Properties

Are there private variables in Python? How would you make an attribute of a class, private?

Explain the following:

* getter
* setter
* deleter

Explain what is @property

How do you swap values between two variables?

```
x, y = y, x
```

Explain the following object's magic variables:

* __dict__


Write a function to return the sum of one or more numbers. The user will decide how many numbers to use

First you ask the user for the amount of numbers that will be use. Use a while loop that runs until amount_of_numbers becomes 0 through subtracting amount_of_numbers by one each loop. In the while loop you want ask the user for a number which will be added a variable each time the loop runs.

```
def return_sum():
amount_of_numbers = int(input("How many numbers? "))
total_sum = 0
while amount_of_numbers != 0:
num = int(input("Input a number. "))
total_sum += num
amount_of_numbers -= 1
return total_sum

```

Print the average of [2, 5, 6]. It should be rounded to 3 decimal places

```
li = [2, 5, 6]
print("{0:.3f}".format(sum(li)/len(li)))
```

#### Python - Lists

What is a tuple in Python? What is it used for?

A tuple is a built-in data type in Python. It's used for storing multiple items in a single variable.

List, like a tuple, is also used for storing multiple items. What is then, the difference between a tuple and a list?

List, as opposed to a tuple, is a mutable data type. It means we can modify it and at items to it.

How to add the number 2 to the list x = [1, 2, 3]

`x.append(2)`

How to get the last element of a list?

`some_list[-1]`

How to add the items of [1, 2, 3] to the list [4, 5, 6]?

x = [4, 5, 6]
x.extend([1, 2, 3])

Don't use `append` unless you would like the list as one item.

How to remove the first 3 items from a list?

`my_list[0:3] = []`

How to insert an item to the beginning of a list? What about two items?

- One item:

```
numbers = [1, 2, 3, 4, 5]
numbers.insert(0, 0)
print(numbers)
```

- Multiple items or list:

```
numbers_1 = [2, 3, 4, 5]
numbers_2 = [0, 1]
numbers_1 = numbers_2 + numbers_1
print(numbers_1)
```

How to sort list by the length of items?

```
sorted_li = sorted(li, key=len)
```

Or without creating a new list:

```
li.sort(key=len)
```

Do you know what is the difference between list.sort() and sorted(list)?

* sorted(list) will return a new list (original list doesn't change)
* list.sort() will return None but the list is change in-place

* sorted() works on any iterable (Dictionaries, Strings, ...)
* list.sort() is faster than sorted(list) in case of Lists

Convert every string to an integer: [['1', '2', '3'], ['4', '5', '6']]

```
nested_li = [['1', '2', '3'], ['4', '5', '6']]
[[int(x) for x in li] for li in nested_li]
```

How to merge two sorted lists into one sorted list?

```
sorted(li1 + li2)
```

Another way:

```
i, j = 0
merged_li = []

while i < len(li1) and j < len(li2):
if li1[i] < li2[j]:
merged_li.append(li1[i])
i += 1
else:
merged_li.append(li2[j])
j += 1

merged_li = merged_li + merged_li[i:] + merged_li[j:]
```

How to check if all the elements in a given lists are unique? so [1, 2, 3] is unique but [1, 1, 2, 3] is not unique because 1 exists twice

There are many ways of solving this problem:

# Note: :list and -> bool are just python typings, they are not needed for the correct execution of the algorithm.

Taking advantage of sets and len:

```
def is_unique(l:list) -> bool:
return len(set(l)) == len(l)
```

This one is can be seen used in other programming languages.

```
def is_unique2(l:list) -> bool:
seen = []

for i in l:
if i in seen:
return False
seen.append(i)
return True
```

Here we just count and make sure every element is just repeated once.

```
def is_unique3(l:list) -> bool:
for i in l:
if l.count(i) > 1:
return False
return True
```

This one might look more convulated but hey, one liners.

```
def is_unique4(l:list) -> bool:
return all(map(lambda x: l.count(x) < 2, l))
```

You have the following function

```
def my_func(li = []):
li.append("hmm")
print(li)
```

If we call it 3 times, what would be the result each call?

```
['hmm']
['hmm', 'hmm']
['hmm', 'hmm', 'hmm']
```

How to iterate over a list?

```
for item in some_list:
print(item)
```

How to iterate over a list with indexes?

```
for i, item in enumerate(some_list):
print(i)
```

How to start list iteration from 2nd index?

Using range like this

```
for i in range(1, len(some_list)):
some_list[i]
```

Another way is using slicing

```
for i in some_list[1:]:
```

How to iterate over a list in reverse order?

Method 1
```
for i in reversed(li):
...
```

Method 2
```
n = len(li) - 1
while n > 0:
...
n -= 1
```

Sort a list of lists by the second item of each nested list

```
li = [[1, 4], [2, 1], [3, 9], [4, 2], [4, 5]]

sorted(li, key=lambda l: l[1])
```

or

```
li.sort(key=lambda l: l[1)
```

Combine [1, 2, 3] and ['x', 'y', 'z'] so the result is [(1, 'x'), (2, 'y'), (3, 'z')]

```
nums = [1, 2, 3]
letters = ['x', 'y', 'z']

list(zip(nums, letters))
```

What is List Comprehension? Is it better than a typical loop? Why? Can you demonstrate how to use it?

From [Docs](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions): "List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.".

It's better because they're compact, faster and have better readability.

- For loop:

```
number_lists = [[1, 7, 3, 1], [13, 93, 23, 12], [123, 423, 456, 653, 124]]
odd_numbers = []
for number_list in number_lists:
for number in number_list:
if number % 2 == 0:
odd_numbers.append(number)
print(odd_numbers)
```

- List comprehesion:

```
number_lists = [[1, 7, 3, 1], [13, 93, 23, 12], [123, 423, 456, 653, 124]]
odd_numbers = [number for number_list in number_lists for number in number_list if number % 2 == 0]
print(odd_numbers)
```

You have the following list: [{'name': 'Mario', 'food': ['mushrooms', 'goombas']}, {'name': 'Luigi', 'food': ['mushrooms', 'turtles']}]
Extract all type of foods. Final output should be: {'mushrooms', 'goombas', 'turtles'}

```
brothers_menu = \
[{'name': 'Mario', 'food': ['mushrooms', 'goombas']}, {'name': 'Luigi', 'food': ['mushrooms', 'turtles']}]

# "Classic" Way
def get_food(brothers_menu) -> set:
temp = []

for brother in brothers_menu:
for food in brother['food']:
temp.append(food)

return set(temp)

# One liner way (Using list comprehension)
set([food for bro in x for food in bro['food']])
```

#### Python - Dictionaries

How to create a dictionary?

my_dict = dict(x=1, y=2)
OR
my_dict = {'x': 1, 'y': 2}
OR
my_dict = dict([('x', 1), ('y', 2)])

How to remove a key from a dictionary?

del my_dict['some_key']
you can also use `my_dict.pop('some_key')` which returns the value of the key.

How to sort a dictionary by values?

```
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
```

How to sort a dictionary by keys?

```
dict(sorted(some_dictionary.items()))
```

How to merge two dictionaries?

```
some_dict1.update(some_dict2)
```

Convert the string "a.b.c" to the dictionary {'a': {'b': {'c': 1}}}

```
output = {}
string = "a.b.c"
path = string.split('.')
target = reduce(lambda d, k: d.setdefault(k, {}), path[:-1], output)
target[path[-1]] = 1
print(output)
```

##### Common Algorithms Implementation

Can you implement "binary search" in Python?

[Solution](coding/python/binary_search.py)

#### Python Files

How to write to a file?

```
with open('file.txt', 'w') as file:
file.write("My insightful comment")
```

Sum all the integers in a given file

Print a random line of a given file

Print every 3rd line of a given file

Print the number of lines in a given file

Print the number of of words in a given file

Can you write a function which will print all the file in a given directory? including sub-directories

Write a dictionary (variable) to a file

```
import json

with open('file.json', 'w') as f:
f.write(json.dumps(dict_var))
```

#### Python OS

How to print current working directory?

import os

print(os.getcwd())

Given the path /dir1/dir2/file1 print the file name (file1)

import os

print(os.path.basename('/dir1/dir2/file1'))

# Another way
print(os.path.split('/dir1/dir2/file1')[1])

Given the path /dir1/dir2/file1

1. Print the path without the file name (/dir1/dir2)
2. Print the name of the directory where the file resides (dir2)

import os

## Part 1.
# os.path.dirname gives path removing the end component
dirpath = os.path.dirname('/dir1/dir2/file1')
print(dirpath)

## Part 2.
print(os.path.basename(dirpath))

How do you execute shell commands using Python?

How do you join path components? for example /home and luig will result in /home/luigi

How do you remove non-empty directory?

#### Python Regex

How do you perform regular expressions related operations in Python? (match patterns, substitute strings, etc.)

Using the re module

How to find all the IP addresses in a variable? How to find them in a file?

#### Python Strings

Find the first repeated character in a string

While you iterate through the characters, store them in a dictionary and check for every character whether it's already in the dictionary.

```
def firstRepeatedCharacter(str):
chars = {}
for ch in str:
if ch in chars:
return ch
else:
chars[ch] = 0
```

How to extract the unique characters from a string? for example given the input "itssssssameeeemarioooooo" the output will be "mrtisaoe"

```
x = "itssssssameeeemarioooooo"
y = ''.join(set(x))
```

Find all the permutations of a given string

```
def permute_string(string):

if len(string) == 1:
return [string]

permutations = []
for i in range(len(string)):
swaps = permute_string(string[:i] + string[(i+1):])
for swap in swaps:
permutations.append(string[i] + swap)

return permutations

print(permute_string("abc"))
```

Short way (but probably not acceptable in interviews):

```
from itertools import permutations

[''.join(p) for p in permutations("abc")]
```

Detailed answer can be found here: http://codingshell.com/python-all-string-permutations

How to check if a string contains a sub string?

Find the frequency of each character in string

Count the number of spaces in a string

You can use the "count" method like this:

```python

ImAString.count(" ")

```

Given a string, find the N most repeated words

Given the string (which represents a matrix) "1 2 3\n4 5 6\n7 8 9" create rows and colums variables (should contain integers, not strings)

What is the result of each of the following?

```
>> ', '.join(["One", "Two", "Three"])
>> " ".join("welladsadgadoneadsadga".split("adsadga")[:2])
>> "".join(["c", "t", "o", "a", "o", "q", "l"])[0::2]
```

```
>>> 'One, Two, Three'
>>> 'well done'
>>> 'cool'
```

If x = "pizza", what would be the result of x[::-1]?

It will reverse the string, so x would be equal to `azzip`.

Reverse each word in a string (while keeping the order)

What is the output of the following code: "".join(["a", "h", "m", "a", "h", "a", "n", "q", "r", "l", "o", "i", "f", "o", "o"])[2::3]

mario

#### Python Iterators

What is an iterator?

#### Python Misc

Explain data serialization and how do you perform it with Python

How do you handle argument parsing in Python?

What is a generator? Why using generators?

What would be the output of the following block?

```
for i in range(3, 3):
print(i)
```

No output :)

What is yeild? When would you use it?

Explain the following types of methods and how to use them:

* Static method
* Class method
* instance method

How to reverse a list?

How to combine list of strings into one string with spaces between the strings

You have the following list of nested lists: [['Mario', 90], ['Geralt', 82], ['Gordon', 88]] How to sort the list by the numbers in the nested lists?

One way is:

the_list.sort(key=lambda x: x[1])

Explain the following:

* zip()
* map()
* filter()

#### Python - Slicing

For the following slicing exercises, assume you have the following list: `my_list = [8, 2, 1, 10, 5, 4, 3, 9]`

What is the result of `my_list[0:4]`?

What is the result of `my_list[5:6]`?

What is the result of `my_list[5:5]`?

What is the result of `my_list[::-1]`?

What is the result of `my_list[::3]`?

What is the result of `my_list[2:]`?

What is the result of `my_list[:3]`?

#### Python Debugging

How do you debug Python code?

pdb :D

How to check how much time it took to execute a certain script or block of code?

What empty return returns?

Short answer is: It returns a None object.

We could go a bit deeper and explain the difference between

```
def a ():
return

>>> None
```

And

```
def a ():
pass

>>> None
```
Or we could be asked this as a following question, since they both give the same result.

We could use the dis module to see what's going on:

```
2 0 LOAD_CONST 0 (", line 2>)
2 LOAD_CONST 1 ('a')
4 MAKE_FUNCTION 0
6 STORE_NAME 0 (a)

5 8 LOAD_CONST 2 (", line 5>)
10 LOAD_CONST 3 ('b')
12 MAKE_FUNCTION 0
14 STORE_NAME 1 (b)
16 LOAD_CONST 4 (None)
18 RETURN_VALUE

Disassembly of ", line 2>:
3 0 LOAD_CONST 0 (None)
2 RETURN_VALUE

Disassembly of ", line 5>:
6 0 LOAD_CONST 0 (None)
2 RETURN_VALUE
```

An empty return is exactly the same as return None and functions without any explicit return
will always return None regardless of the operations, therefore

```
def sum(a, b):
global c
c = a + b

>>> None
```

How to improve the following block of code?

```
li = []
for i in range(1, 10):
li.append(i)
```

```
[i for i in range(1, 10)]
```

Given the following function

```
def is_int(num):
if isinstance(num, int):
print('Yes')
else:
print('No')
```
What would be the result of is_int(2) and is_int(False)?


#### Python - Linked List

Can you implement a linked list in Python?

The reason we need to implement in the first place, it's because a linked list isn't part of Python standard library.

To implement a linked list, we have to implement two structures: The linked list itself and a node which is used by the linked list.

Let's start with a node. A node has some value (the data it holds) and a pointer to the next node

```
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
```

Now the linked list. An empty linked list has nothing but an empty head.

```
class LinkedList(object):
def __init__(self):
self.head = None
```

Now we can start using the linked list

```
ll = Linkedlist()
ll.head = Node(1)
ll.head.next = Node(2)
ll.head.next.next = Node(3)
```

What we have is:

---- ----- ----
| 1 | -> | 2 | -> | 3 |
---- ----- -----

Usually, more methods are implemented, like a push_head() method where you insert a node at the beginning of the linked list

```
def push_head(self, value):
new_node = Node(value)
new_node.next = self.head
self.head = new_node
```

Add a method to the Linked List class to traverse (print every node's data) the linked list

def print_list(self):
node = self.head
while(node):
print(node.data)
node = node.next

Write a method to that will return a boolean based on whether there is a loop in a linked list or not

Let's use the Floyd's Cycle-Finding algorithm:

```
def loop_exists(self):
one_step_p = self.head
two_steps_p = self.head
while(one_step_p and two_steps_p and two_steps_p.next):
one_step_p = self.head.next
two_step_p = self.head.next.next
if (one_step_p == two_steps_p):
return True
return False
```

#### Python - Stack

Implement Stack in Python

#### Python Testing

What is your experience with writing tests in Python?

What is PEP8? Give an example of 3 style guidelines

PEP8 is a list of coding conventions and style guidelines for Python

5 style guidelines:

1. Limit all lines to a maximum of 79 characters.
2. Surround top-level function and class definitions with two blank lines.
3. Use commas when making a tuple of one element
4. Use spaces (and not tabs) for indentation
5. Use 4 spaces per indentation level

How to test if an exception was raised?

What assert does in Python?

Explain mocks

How do you measure execution time of small code snippets?

Why one shouldn't use assert in non-test/production code?

#### Flask

Can you describe what is Django/Flask and how you have used it? Why Flask and not Django? (or vice versa)

What is a route?

As every web framework, Flask provides a route functionality that lets you serve a content of a given URL.

There are multiple ways to map a URL with a function in Python.

- Decorator: you can use python decorators. In this case we're using `app`. This `app` decorator is the instance of the `Flask` class. And route it's a method of this class.

```
@app.route('/')
def home():
return 'main website'
```

- `add_url_rule` method: This is a method of the Flask class. We can also use it for map the URL with a function.

```
def home():
return 'main website'

app.add_url_rule('/', view_func=home)
```

What is a blueprint in Flask?

What is a template?

#### zip

Given x = [1, 2, 3], what is the result of list(zip(x))?

```
[(1,), (2,), (3,)]
```

What is the result of each of the following:

```
list(zip(range(5), range(50), range(50)))
list(zip(range(5), range(50), range(-2)))
```

```
[(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4)]
[]
```

#### Python Descriptors

Explain Descriptors

Read about descriptors [here](https://docs.python.org/3/howto/descriptor.html)

What would be the result of running a.num2 assuming the following code

```
class B:
def __get__(self, obj, objtype=None):
reuturn 10

class A:
num1 = 2
num2 = Five()
```


10

What would be the result of running some_car = Car("Red", 4) assuming the following code

```
class Print:

def __get__(self, obj, objtype=None):
value = obj._color
print("Color was set to {}".format(valie))
return value

def __set__(self, obj, value):
print("The color of the car is {}".format(value))
obj._color = value

class Car:

color = Print()

def __ini__(self, color, age):
self.color = color
self.age = age
```


An instance of Car class will be created and the following will be printed: "The color of the car is Red"

#### Python Misc

How can you spawn multiple processes with Python?

Implement simple calculator for two numbers

```
def add(num1, num2):
return num1 + num2

def sub(num1, num2):
return num1 - num2

def mul(num1, num2):
return num1*num2

def div(num1, num2):
return num1 / num2

operators = {
'+': add,
'-': sub,
'*': mul,
'/': div
}

if __name__ == '__main__':
operator = str(input("Operator: "))
num1 = int(input("1st number: "))
num2 = int(input("2nd number: "))
print(operators[operator](num1, num2))
```

What data types are you familiar with that are not Python built-in types but still provided by modules which are part of the standard library?

This is a good reference https://docs.python.org/3/library/datatypes.html

Explain what is a decorator


In python, everything is an object, even functions themselves. Therefore you could pass functions as arguments
for another function eg;

```
def wee(word):
return word

def oh(f):
return f + "Ohh"

>>> oh(wee("Wee"))
<<< Wee Ohh
```

This allows us to control the before execution of any given function and if we added another function as wrapper,
(a function receiving another function that receives a function as parameter) we could also control the after execution.

Sometimes we want to control the before-after execution of many functions and it would get tedious to write

f = function(function_1())
f = function(function_1(function_2(*args)))

every time, that's what decorators do, they introduce syntax to write all of this on the go, using the keyword '@'.

Can you show how to write and use decorators?


These two decorators (ntimes and timer) are usually used to display decorators functionalities, you can find them in lots of
tutorials/reviews. I first saw these examples two years ago in pyData 2017. https://www.youtube.com/watch?v=7lmCu8wz8ro&t=3731s

```
Simple decorator:

def deco(f):
print(f"Hi I am the {f.__name__}() function!")
return f

@deco
def hello_world():
return "Hi, I'm in!"

a = hello_world()
print(a)

>>> Hi I am the hello_world() function!
Hi, I'm in!
```

This is the simplest decorator version, it basically saves us from writting a = deco(hello_world()).
But at this point we can only control the before execution, let's take on the after:

```
def deco(f):
def wrapper(*args, **kwargs):
print("Rick Sanchez!")
func = f(*args, **kwargs)
print("I'm in!")
return func
return wrapper

@deco
def f(word):
print(word)

a = f("************")
>>> Rick Sanchez!
************
I'm in!
```

deco receives a function -> f
wrapper receives the arguments -> *args, **kwargs

wrapper returns the function plus the arguments -> f(*args, **kwargs)
deco returns wrapper.

As you can see we conveniently do things before and after the execution of a given function.

For example, we could write a decorator that calculates the execution time of a function.

```
import time
def deco(f):
def wrapper(*args, **kwargs):
before = time.time()
func = f(*args, **kwargs)
after = time.time()
print(after-before)
return func
return wrapper

@deco
def f():
time.sleep(2)
print("************")

a = f()
>>> 2.0008859634399414
```

Or create a decorator that executes a function n times.

```
def n_times(n):
def wrapper(f):
def inner(*args, **kwargs):
for _ in range(n):
func = f(*args, **kwargs)
return func
return inner
return wrapper

@n_times(4)
def f():
print("************")

a = f()

>>>************
************
************
************
```

Write a decorator that calculates the execution time of a function

Write a script which will determine if a given host is accessible on a given port

Are you familiar with Dataclasses? Can you explain what are they used for?

You wrote a class to represent a car. How would you compare two cars instances if two cars are equal if they have the same model and color?

```
class Car:
def __init__(self, model, color):
self.model = model
self.color = color

def __eq__(self, other):
if not isinstance(other, Car):
return NotImplemented
return self.model == other.model and self.color == other.color

>> a = Car('model_1', 'red')
>> b = Car('model_2', 'green')
>> c = Car('model_1', 'red')
>> a == b
False
>> a == c
True
```

Explain Context Manager

Tell me everything you know about concurrency in Python

Explain the Buffer Protocol

Do you have experience with web scraping? Can you describe what have you used and for what?

Can you implement Linux's tail command in Python? Bonus: implement head as well

You have created a web page where a user can upload a document. But the function which reads the uploaded files, runs for a long time, based on the document size and user has to wait for the read operation to complete before he/she can continue using the web site. How can you overcome this?

How yield works exactly?