Skip to content

bregman-arie/python-exercises

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ℹ️  This repo contains questions and exercises to learn and practice Python

📊  There are currently 231 exercises and questions

Exercises

Hello World

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

Objects & Data Types

Name Objective & Instructions Solution Comments
Objects 101 Exercise Solution
Data Types? I know a few Exercise Solution
Choose a Data Type - level 1 Exercise Solution
Choose a Data Type - level 2 Exercise Solution
Mutability Exercise Solution
Strongly Typed Exercise Solution
Object Creation Exercise Solution

Variables

Name Objective & Instructions Solution Comments
Valid Names Exercise Solution
Locations or Names Exercise Solution
Types Exercise Solution
Multiple Value Assignment Exercise Solution
Copying Variables Exercise Solution
Mutable Objects Exercise Solution

Booleans

Name Objective & Instructions Solution Comments
True or False? Exercise Solution
Conversion Exercise Solution

Strings

Name Objective & Instructions Solution Comments
22 times Exercise
Variables Exercise Solution
What is the result? - Level 1 Exercise Solution
What is the result? - Level 2 Exercise Solution
Starts with a letter Exercise Solution
Change Strings Exercise Solution
All Digits Exercise Solution
Removing Characters Exercise Solution
Reverse a String Exercise Solution
Compress Strings Exercise
Slicing - Level 1 Exercise Solution
Slicing - Level 2 Exercise Solution
Swap Case Exercise Solution HackerRank
Count Substring Exercise Solution HackerRank
Capitalize! Exercise Solution HackerRank

Numbers

Name Objective & Instructions Solution Comments
What is the result? Exercise Solution
Operations - Level 1 Exercise Solution
Operations - Level 2 Exercise Solution
Bases Exercise Solution
Palindrome Exercise Solution

Lists & Tuples

Name Objective & Instructions Solution Comments
Access List Items Exercise Solution
Equal Lists Exercise Solution
Length Exercise
Append & Insert Exercise Solution
Min Max Exercise Solution
Three Biggest Items Exercise Solution
What is the result? - Level 1 Exercise Solution
What is the result? - Level 2 Exercise Solution
Running Sum Exercise Solution
Remove Duplicates from Sorted List Exercise Solution LeetCode
Find the Runner-Up Score! Exercise Solution HackerRank
Nested Lists Exercise Solution HackerRank

Dictionaries

Name Objective & Instructions Solution Comments
Facts Only Exercise Solution

Loops

Name Objective & Instructions Solution Comments
Break Out Exercise Solution
Break Out 2 Exercise Solution
Every character Exercise Solution
Stream of Numbers Exercise Solution
Refactor-1 Exercise Solution

Functions

Name Objective & Instructions Solution Comments
My First Function Exercise Solution
Calculator Exercise Solution
First Class Objects Exercise Solution

Classes

Name Objective & Instructions Solution Comments
Classes 101 Exercise Solution
Attributes Exercise Solution
Print Order Exercise Solution

OOP

Name Objective & Instructions Solution Comments
Inheritance Exercise Solution

Magic Methods

Name Objective & Instructions Solution Comments
Length Magic Method Exercise

Unit Testing

Name Objective & Instructions Solution Comments
Calculator Unit Tests Exercise Solution
Fix Calculator Unit Tests Exercise

Exceptions

Name Objective & Instructions Solution Comments
What exception is raised? - Level 1 Exercise Solution
What exception is raised? - Level 2 Exercise Solution
Bound To It Exercise Solution

Regex

Name Objective & Instructions Solution Comments
Substitute Strings Exercise Solution

Files

Name Objective & Instructions Solution Comments
Read a File Exercise
Reverse a file Exercise
Print specific line Exercise

Operating Systems

Name Objective & Instructions Solution Comments
File exists Exercise
Print all the files in a directory Exercise

Improve the Code

Name Objective & Instructions Solution Comments
If True Exercise Solution
Walrus Exercise Solution
Vowel Letters Exercise Solution

Type Hinting

Name Objective & Instructions Solution Comments
Type Hinting Facts Only Exercise Solution
Pros & Cons Exercise Solution
Type Hinting 101 Exercise Solution
Type Hinting 102 Exercise Solution

Misc

Name Objective & Instructions Solution Comments
Random Number Exercise
Random Item Exercise

Lambda

Name Objective & Instructions Solution
Multiply the arguments and return the result Exercise Solution
Write a python program to generate a function to double a specified number. Exercise Solution

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)
print("Hello Amazing", end=" ")
print("World")

The following program reads two numbers from the user
x = int(input())
y = int(input())

print the sum and the difference between the numbers


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"
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)
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
for i in range(n + 1):
   if i % 2 == 0:
       print(i)

Classes

Define a class that does nothing
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]?
[int(i) for in in "2 0 1 7".split()]

Lists

How to remove duplicates from a given sorted list?

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.

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

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.
x = lambda a: a + 10
print(x(10))
  • An addition function
addition = lambda x, y: x + y
print(addition(10, 20))
  • Squaring function
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: "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

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:

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 (<code object a at 0x0000029C4D3C2DB0, file "<dis>", line 2>)
              2 LOAD_CONST               1 ('a')
              4 MAKE_FUNCTION            0
              6 STORE_NAME               0 (a)

  5           8 LOAD_CONST               2 (<code object b at 0x0000029C4D3C2ED0, file "<dis>", 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 <code object a at 0x0000029C4D3C2DB0, file "<dis>", line 2>:
  3           0 LOAD_CONST               0 (None)
              2 RETURN_VALUE

Disassembly of <code object b at 0x0000029C4D3C2ED0, file "<dis>", 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

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?

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published