226 lines
5.7 KiB
Python
226 lines
5.7 KiB
Python
# -*- coding: utf-8 -*-
|
|
import asyncio
|
|
from concurrent import futures
|
|
import time
|
|
|
|
|
|
def question_1():
|
|
class Klasa:
|
|
_instance = None
|
|
|
|
def __new__(cls, *args, **kwargs):
|
|
if cls._instance is None:
|
|
cls._instance = super().__new__(cls, *args, **kwargs)
|
|
print(cls.__dict__)
|
|
return cls._instance
|
|
|
|
def __init__(self):
|
|
self.instance_var = 'Hello, World!'
|
|
print(self.__dict__)
|
|
|
|
obiekt = Klasa()
|
|
obiekt.zmienna = ' ... of Python.'
|
|
zupelnie_inny_obiekt = Klasa()
|
|
print(obiekt.instance_var)
|
|
print(zupelnie_inny_obiekt.zmienna)
|
|
|
|
|
|
def question_2():
|
|
numery = [1, 2, 3, 4]
|
|
slowa = ['jeden', 'dwa', 'trzy', 'cztery']
|
|
print(dict(zip(slowa, numery)))
|
|
print(list(map(lambda x: x*x, numery)))
|
|
print(list(filter(lambda x: x % 2 == 0, numery)))
|
|
print([x for x in range(4)])
|
|
print(list((x for x in numery)))
|
|
print(tuple(x for x in numery))
|
|
print(type({x for x in numery}))
|
|
dict_compr = {x: y for x, y in zip([float(x) for x in numery], slowa)}
|
|
for key, value in dict_compr.items():
|
|
print(f'{key=:.2}, {value = !r}')
|
|
|
|
|
|
def question_3():
|
|
def do_something(seconds):
|
|
print(f'Sleeping for {seconds} seconds...')
|
|
time.sleep(seconds)
|
|
print(f'Done sleeping for {seconds}...')
|
|
return 'Hello, World!'
|
|
|
|
async def do_something_but_async(seconds):
|
|
print(f'Sleeping for {seconds} seconds...')
|
|
await asyncio.sleep(seconds)
|
|
print(f'Done sleeping for {seconds}...')
|
|
return 'Hello, World!'
|
|
|
|
def threaded_test():
|
|
start = time.perf_counter()
|
|
with futures.ThreadPoolExecutor() as executor:
|
|
results = executor.map(do_something, [3, 2, 1])
|
|
for result in results:
|
|
print(result)
|
|
finish = time.perf_counter()
|
|
print(f'Finished in {round(finish - start, 3)} second(s)')
|
|
|
|
async def async_test():
|
|
start = time.perf_counter()
|
|
task1 = asyncio.create_task(do_something_but_async(3))
|
|
task2 = asyncio.create_task(do_something_but_async(2))
|
|
task3 = asyncio.create_task(do_something_but_async(1))
|
|
result1 = await task1
|
|
result2 = await task2
|
|
result3 = await task3
|
|
print(result1, result2, result3)
|
|
finish = time.perf_counter()
|
|
print(f'Finished in {round(finish - start, 3)} second(s)')
|
|
|
|
threaded_test()
|
|
asyncio.run(async_test())
|
|
|
|
|
|
def question_4():
|
|
class Lista:
|
|
def __init__(self, prawdziwa_lista):
|
|
self.i = 0
|
|
self.prawdziwa_lista = prawdziwa_lista
|
|
|
|
def __next__(self):
|
|
if self.i < len(self.prawdziwa_lista):
|
|
current = self.prawdziwa_lista[self.i]
|
|
self.i += 1
|
|
return current
|
|
else:
|
|
raise StopIteration
|
|
|
|
def __iter__(self):
|
|
self.i = 0
|
|
return self
|
|
|
|
moja_lista = Lista([1, 2, 3])
|
|
print(next(moja_lista))
|
|
for i in moja_lista:
|
|
print(i)
|
|
|
|
|
|
def question_5():
|
|
print(type(None))
|
|
|
|
def funkcja(a=[], b=None):
|
|
print(f'\n{a=}, {b=}')
|
|
if not b:
|
|
print('not b')
|
|
if b is None:
|
|
print('b is None')
|
|
print(f'{a == b = }')
|
|
print(f'{a is b = }')
|
|
# print(f'{id(a)=}, {id(b)=}')
|
|
|
|
funkcja(a=None)
|
|
funkcja(b=[])
|
|
|
|
|
|
def question_8():
|
|
def funkcja(*args, **kwargs):
|
|
print(args)
|
|
print(*args)
|
|
for k, v in kwargs.items():
|
|
print(k, v)
|
|
|
|
funkcja(1, 2, something=3, somewhere=4)
|
|
|
|
|
|
def question_10():
|
|
from copy import deepcopy
|
|
lista_1 = ['a', 'b', 'c']
|
|
lista_2 = lista_1
|
|
lista_1.append('d')
|
|
print(f'{lista_2 = }')
|
|
lista_1 = lista_2[:]
|
|
lista_3 = deepcopy(lista_2)
|
|
lista_3.pop()
|
|
print(f'{lista_3 = }')
|
|
lista_2.append('e')
|
|
print(f'{lista_1 = }, {lista_2 = }, {lista_3 = }')
|
|
|
|
|
|
def question_11():
|
|
def circular_gen(lista):
|
|
while lista:
|
|
for element in lista:
|
|
yield element
|
|
|
|
silnik_4t = circular_gen(['ssanie', 'sprezanie', 'zaplon', 'wydalanie'])
|
|
for i in range(6):
|
|
print(next(silnik_4t))
|
|
|
|
|
|
def question_12():
|
|
def n_fib_recur(n):
|
|
if n <= 1:
|
|
return 1
|
|
return n_fib_recur(n - 2) + n_fib_recur(n - 1)
|
|
|
|
print(f'suma 7 i 6 wyrazu ciągu fib. wynosi {n_fib_recur(7)}')
|
|
|
|
|
|
def question_13():
|
|
class Klasa:
|
|
def __init__(self, tekst, liczba):
|
|
self.str_var = tekst
|
|
self.int_val = liczba
|
|
|
|
def __repr__(self):
|
|
return f'{self.__class__.__name__}(\'{self.str_var}\', {self.int_val})'
|
|
|
|
def __str__(self):
|
|
return f'<{self.str_var} ({self.int_val})>'
|
|
|
|
klasa = Klasa('Hello, World!', 42)
|
|
lista = [klasa]
|
|
print(klasa)
|
|
print(lista)
|
|
|
|
|
|
def question_15():
|
|
lista = [1, 2, 3, 4, 5, 6, 7, 8]
|
|
print(lista[::-1])
|
|
print(lista[-1])
|
|
|
|
|
|
def question_16():
|
|
from sys import exc_info
|
|
|
|
def exceptional(number):
|
|
print(f'\nTrying {number}:')
|
|
try:
|
|
print(1 / number)
|
|
except:
|
|
print(f'Ruh-roh! {exc_info()[1].__repr__()}')
|
|
else:
|
|
print('All is well.')
|
|
finally:
|
|
print('Finished.')
|
|
|
|
exceptional(1)
|
|
exceptional(0)
|
|
|
|
def primes(last):
|
|
primes_list = []
|
|
for number in range(2, last + 1):
|
|
for check in range(2, number):
|
|
if number % check == 0:
|
|
break
|
|
else:
|
|
primes_list.append(number)
|
|
return primes_list
|
|
|
|
print(primes(100))
|
|
|
|
|
|
def question_17():
|
|
print('\n'.join([f"{i}: {'Two! ' if i % 2 == 0 else ''}{'Three!' if i % 3 == 0 else ''}" for i in range(101)]))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
question_5()
|