Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Review questionnaires
- > **TODO** добавить вопросы по
- >
- > * базам данных
- > * http протоколу
- ## SE1
- * какими python framework'ми приходилось пользоваться
- * основные компоненты django /models, views, forms, middlewares, context processors etc./
- * как работают middleware в django
- * какие знаете методы оптимизации запросов в django
- * какие есть типы перечисляемых данных в python
- * mutable/immutable
- * чем отличаются list от tuple
- * для чего удобно использовать set
- * что такое декораторы, зачем нужны
- * `@property`/`@classmethod`/`@staticmethod` зачем нужны, в чем разница
- * что такое генераторы/итераторы, зачем нужны
- * для чего используется python пакет `copy`
- * какие "магические" методы вы знаете
- * написать код который поменяет ключи и значения местами в dict'е
- * для чего нужны функции map и filter
- * какие еще встроенные функции вы знаете
- * приходилось ли использовать Redis? какие задачи решали?
- * reverse a list [1, 2, 3, 4, 5, 6]
- > Answer:
- ```python
- ll[::-1]
- ```
- ## SE2
- * приходилось ли работать с formset'ми, для чего они нужны и как их использовать
- * есть ли опыт написания кастомных field'ов модели, какие задачи выполняют field'ы
- * как узнать где должны располагать python пакеты
- * для чего используется конструкция `__name__ == '__main__'`
- * посчитать суму чисел заданых списком строк используя `map` и `reduce`
- * написать пример генератора
- * что выведет последння строка
- ```python
- d = {
- 'key1': 1,
- 'key2': {
- 'key21': 22,
- 'key22': 33,
- },
- }
- dcopy = copy.copy(d)
- dcopy['key1'] = 5
- dcopy['key2']['key21'] = 55
- print(d)
- ```
- * что такое контекст процессор, для чего он нужен, как написать свой
- ```python
- >>> c = cycle(['odd', 'even'])
- >>> c.next()
- odd
- >>> c.next()
- even
- >>> c.next()
- odd
- ```
- * написать mixin который добавит все переданные именованные аргументы в конструктор как атрибуты инстанса класса
- * какие вы знаете отличия между python 2 и 3. что делает приведенный ниже код в обоих версиях
- ```python
- rcpts = ['user1@email.com', 'user2@email.com', 'user3@email.com']
- map(send_notification, rcpts)
- ```
- * Чем отличается строка в Python 2.x и Python 3.x ? Что такое unicode и зачем он нужен?
- * структура моделей для отеля(комнаты и букинг, как проверить что комната свободна в определенный промежуток дат/времени)
- * AsyncIO
- * что из себя представляет? на что расчитано? за счет чего приемущество?
- * какой есть способ выполнения синхронного кода внутри AsyncIO
- * что такое generator "send"? Что выведет следующий блок кода?
- ```python
- def counter(maximum):
- i = 0
- while i < maximum:
- print('~~~~~~~~~~')
- val = (yield i*2)
- print("Val: {}".format(val))
- if val is not None:
- i = val
- else:
- i += 1
- it = counter(9)
- print(it.__next__())
- print(it.__next__())
- print(it.send(8))
- print(it.__next__())
- ```
- * Для чего нужен ThreadPoolExecutor. Чем отличается ThreadPoolExecutor от ProcessPoolExecutor? Какой для чего используется и в чем плюсы/минусы каждого?
- * Local and Global variables: what will be the output of the following programs?
- ```python
- x = 1
- def f():
- x = 2
- return x
- print x
- print f()
- print x
- ```
- > As x is defined inside f() method, it use local variable. The result will be 1,2,1
- ```python
- x = 1
- def f():
- y = x
- x = 2
- return x + y
- print x
- print f()
- print x
- ```
- > Answer: As x is defined in f() method, but it is done after assigning it to y, we will have an error "local variable 'x' referenced before assignment"
- * Conditional expressions. What happens when the following code is executed? Will it give any error? Explain the reasons.
- ```python
- x = 2
- if x == 2:
- print x
- else:
- print y
- ```
- > No, it will not, because the first block will be executed, and it will not be found that y isn’t assigned
- ```python
- x = 2
- if x == 2:
- print x
- else:
- x +
- ```
- > Answer: There will be an error «SyntaxError: invalid syntax» because it will be found on compile phase
- * Write iterator that reverses passed list:
- ```python
- >>> it = reverse_iter([1, 2, 3, 4])
- >>> it.next()
- 4
- >>> it.next()
- 3
- >>> it.next()
- 2
- >>> it.next()
- 1
- >>> it.next()
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- StopIteration
- ```
- > Answer:
- ```python
- class reverse_iter:
- def __init__(self, iterable_obj):
- self.i = len(iterable_obj) - 1
- self.iterable_obj = iterable_obj
- def __iter__(self):
- return self
- def next(self):
- if self.i > 0:
- i = self.i
- self.i -= 1
- return self.iterable_obj[i]
- else:
- raise StopIteration()
- ```
- * Write generator that reverses list
- > Answer:
- ```python
- def reverse_generator(iterable_obj):
- for x in iterable_obj[::-1]:
- yield x
- ```
- ## SE3
- * написать класс, который бы по всем внешним признакам был бы словарем, но позволял обращаться к ключам как к атрибутам
- * написать функцию-фабрику возвращающую функцию суммирования передаваемых аргументов
- ```python
- >>> add1 = addition(1)
- >>> add1(2)
- 3
- >>> add1(5)
- 8
- ```
- * Local, Global and Nonlocal (introduced in python3) variables: what will be the output of the following programs?
- ```python
- def f():
- x = 42
- def g():
- nonlocal x
- x = 43
- print("Before calling g: " + str(x))
- print("Calling g now:")
- g()
- print("After calling g: " + str(x))
- x = 3
- f()
- print("x in main: " + str(x))
- ```
- > Answer:
- Before calling g: 42
- Calling g now:
- After calling g: 43
- x in main: 3
- * AsyncIO
- * в чем разница между двумя примерами
- ```python
- import asyncio
- from datetime import datetime
- from concurrent.futures import ThreadPoolExecutor
- async def not_sleep():
- print('NOT SLEEP', datetime.now())
- async def factorial(name, number):
- f = 1
- for i in range(2, number+1):
- print('Task {}: Compute factorial({})'.format(name, i))
- await not_sleep()
- f *= i
- print('Task {}: factorial({}) is {}'.format(name, number, f))
- loop = asyncio.get_event_loop()
- loop.set_default_executor(ThreadPoolExecutor(4))
- tasks = [
- asyncio.ensure_future(factorial("A", 2)),
- asyncio.ensure_future(factorial("B", 3)),
- asyncio.ensure_future(factorial("C", 4)),
- ]
- loop.run_until_complete(asyncio.wait(tasks))
- loop.close()
- ```
- ```python
- import asyncio
- from datetime import datetime
- from concurrent.futures import ThreadPoolExecutor
- async def custom_sleep():
- print('SLEEP', datetime.now())
- await asyncio.sleep(1)
- async def factorial(name, number):
- f = 1
- for i in range(2, number+1):
- print('Task {}: Compute factorial({})'.format(name, i))
- await custom_sleep()
- f *= i
- print('Task {}: factorial({}) is {}'.format(name, number, f))
- loop = asyncio.get_event_loop()
- loop.set_default_executor(ThreadPoolExecutor(4))
- tasks = [
- asyncio.ensure_future(factorial("A", 2)),
- asyncio.ensure_future(factorial("B", 3)),
- asyncio.ensure_future(factorial("C", 4)),
- ]
- loop.run_until_complete(asyncio.wait(tasks))
- loop.close()
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement