ddd
[(36, 'abc', 5158), (35, 'aaa', 4023), (44, 'aaa', 3756), (171, 'alc', 3262), (179, 'soc', 701), (42, 'abs', 3879), (43, 'abs', 531)]
ddd.sort(key=lambda x: x[-1])
ddd
[(43, 'abs', 531), (179, 'soc', 701), (171, 'alc', 3262), (44, 'aaa', 3756), (42, 'abs', 3879), (35, 'aaa', 4023), (36, 'abc', 5158)]
t = {v[-1]: v for v in ddd}
t
{531: (43, 'abs', 531), 701: (179, 'soc', 701), 3262: (171, 'alc', 3262), 3756: (44, 'aaa', 3756), 3879: (42, 'abs', 3879), 4023: (35, 'aaa', 4023), 5158: (36, 'abc', 5158)}
import json
class Test:
def method1(self):
pass
def method2(self):
pass
# Через оборачивания
class CounterUseMethod:
count_method = {}
@classmethod
def counter(cls, method):
def wrapper(self, *args, **kwargs):
name = f'{self.__class__.__name__}: {method.__name__}'
if name not in cls.count_method:
cls.count_method[name] = 0
cls.count_method[name] += 1
return method(self, *args, **kwargs)
return wrapper
Test.method1 = CounterUseMethod.counter(Test.method1)
Test.method2 = CounterUseMethod.counter(Test.method2)
# Через наследование
class Counter(Test):
count_method = {}
def method1(self):
name = 'method1'
if name not in self.count_method:
self.count_method[name] = 0
self.count_method[name] += 1
return super().method1()
def method2(self):
name = 'method2'
if name not in self.count_method:
self.count_method[name] = 0
self.count_method[name] += 1
return super().method2()
test = Test()
test2 = Counter()
for _ in range(10):
test.method1()
test2.method1()
for _ in range(5):
test.method2()
test2.method2()
print(json.dumps(CounterUseMethod.count_method, indent=4))
print(json.dumps(test2.count_method, indent=4))
from pprint import pprint
films = ('Форсаж: Хоббс и Шоу', 'Вельзевул', 'Приключения Реми')
rasp = (
(('10:00', 'Kino Forum'), ('10:00', 'Kino Forum'), ('10:00', 'Lumiera Cinema (ЦУМ)')),
(('12:50', 'Chaplin MEGA Park'), ('23:50', 'Chaplin MEGA Alma-Ata')),
(('10:00', 'Lumiera Cinema (ЦУМ)'), ('10:00', 'Nomad Cinema'))
)
result = [
(k, *v)
for k, r in zip(films, rasp)
for v in r
]
pprint(result)
[('Форсаж: Хоббс и Шоу', '10:00', 'Kino Forum'),
('Форсаж: Хоббс и Шоу', '10:00', 'Kino Forum'),
('Форсаж: Хоббс и Шоу', '10:00', 'Lumiera Cinema (ЦУМ)'),
('Вельзевул', '12:50', 'Chaplin MEGA Park'),
('Вельзевул', '23:50', 'Chaplin MEGA Alma-Ata'),
('Приключения Реми', '10:00', 'Lumiera Cinema (ЦУМ)'),
('Приключения Реми', '10:00', 'Nomad Cinema')]
def pytest_collection_modifyitems(items):
mark = pytest.mark.skip('Test is not present in test run.')
# Тут любая магия которая придет к вам в голову.
for item in items:
if item.config.getoption('url2') is None:
item.add_marker(mark)
# UPD я бы посмотрел, в сторону того что бы не пложить фикстуру request_get_service, а прокидывать ей url,
# запрашивая её в нужных местах, что-то типо такого.
#########################
@pytest.fixture()
def request_get_service(requests, url):
return requests.get(url)
#########################
@pytest.fixture()
def use_url2(request_get_service, requests):
url = requests.config.getoption('url2')
return request_get_service(requests, url)
@pytest.fixture()
def use_url3(request_get_service, requests):
url = requests.config.getoption('url2')
return request_get_service(requests, url)
from pprint import pprint
TRUE_COUNT = 2
def yes(obj: dict, values: dict):
obj_values = {v for v in obj.values() if isinstance(v, (str, int, float, tuple, bool))}
return len(obj_values.intersection(values.values())) >= TRUE_COUNT
def find(key, keys, obj, accept_values):
find_obj = None
if isinstance(obj, dict):
if yes(obj, accept_values):
find_obj = obj
else:
for key, value in obj.items():
find_obj = find(key, keys, value, accept_values)
if find_obj:
break
elif isinstance(obj, list):
for key, value in enumerate(obj):
find_obj = find(key, keys, value, accept_values)
if find_obj:
break
if find_obj:
keys.append(key)
pprint(list(reversed(keys)))
return find_obj
for accept in my.values():
pprint(find('', [], rr, accept))
# Условно у меня есть одна абстрация для всех классов, куда я сложил какие-то базовые вещи для всех.
@dataclass
class ApiAbstraction(ABC):
config: Any = field(init=True)
session: ClientSession = field(init=True, default_factory=ClientSession)
async def close(self):
await self.session.close()
# И есть разные классы, для авторизации и апи
@dataclass
class ApiBLABLA(ApiAbstraction):
# Загрузить файл
async def send_file(self, filepath: str):
endpoint = f"app/files"
new_url = urljoin(self.config.api, endpoint)
headers = {"accept": JSON}
file = os.path.abspath(filepath)
data = {"file": open(file, "r")}
raw_result = await self.session.post(new_url, headers=headers, data=data)
result = await raw_result.json()
response = get_response_instance(result)
if response.success:
file = FileUploadModel.init_from_data(response.result)
return file
return response
# Условно класс для авторизации
@dataclass
class Auth(ApiAbstraction):
async def login(self):
endpoint = "auth/blabla"
new_url = urljoin(self.config.auth, endpoint)
headers = {}
raw_response = await self.session.get(new_url, headers=headers)
content = await raw_response.json(content_type=None)
response = get_response_instance(content, AuthModel)
return response
# Для ответов у меня есть модели, в которые конвертируется JSON ответ. можно и напрямую работать, но нам захотелось через модели.
@dataclass
class AuthModel(AbstractClass):
key: str = ''
obj = [
{'_id': 'wZQlBGoBENgcYA5dUvr_',
'_index': 'fh_images',
'_score': 0.3617011156311892,
'_source': {'img_id': '298156',
'img_url': 'https://img.com/c9318/u298156/-6/y_84164775.jpg'},
'_type': 'fh_image'},
{'_id': 'wpQlBGoBENgcYA5dV_pJ',
'_index': 'fh_images',
'_score': 0.44313779433299844,
'_source': {'img_id': '298156',
'img_url': 'https://img.com/c11125/u298156/125130624/y_1d015950.jpg'},
'_type': 'fh_image'},
{'_id': 'x5QlBGoBENgcYA5da_pJ',
'_index': 'fh_images',
'_score': 0.44582819825057535,
'_source': {'img_id': '298156',
'img_url': 'https://img.com/c4475/u298156/-6/y_32e0b727.jpg'},
'_type': 'fh_image'},
{'_id': 'w5QlBGoBENgcYA5dWvrP',
'_index': 'fh_images',
'_score': 0.45485040641214125,
'_source': {'img_id': '298156',
'img_url': 'https://img.com/c11125/u298156/125130624/y_80599d36.jpg'},
'_type': 'fh_image'},
{'_id': 'xJQlBGoBENgcYA5dXvrv',
'_index': 'fh_images',
'_score': 0.4625495354012009,
'_source': {'img_id': '298156',
'img_url': 'https://img.com/c9318/u298156/125130624/y_ab5d368d.jpg'},
'_type': 'fh_image'},
{'_id': 'xpQlBGoBENgcYA5dZ_pU',
'_index': 'fh_images',
'_score': 0.4636520489656735,
'_source': {'img_id': '298156',
'img_url': 'https://img.com/c11187/u298156/-6/y_8e5cdd46.jpg'},
'_type': 'fh_image'},
{'_id': 'xZQlBGoBENgcYA5dY_oi',
'_index': 'fh_images',
'_score': 0.5156954172925243,
'_source': {'img_id': '298156',
'img_url': 'https://img.com/c4422/u298156/-6/y_8458ec16.jpg'},
'_type': 'fh_image'},
{'_id': 'xJQKBGoBENgcYA5dKvQ5',
'_index': 'fh_images',
'_score': 0.5572724509457869,
'_source': {'img_id': '299217',
'img_url': 'https://img.com/c10739/u299217/-6/y_19eb9a0c.jpg'},
'_type': 'fh_image'},
{'_id': 's5QgBGoBENgcYA5dtPla',
'_index': 'fh_images',
'_score': 0.5624892892097831,
'_source': {'img_id': '298711',
'img_url': 'https://img.com/c308425/v308425711/3c/UJdRfCsT3fs.jpg'},
'_type': 'fh_image'},
{'_id': 'qpQpBGoBENgcYA5dyvui',
'_index': 'fh_images',
'_score': 0.5646689160902589,
'_source': {'img_id': '298039',
'img_url': 'https://img.com/c5786/u298039/-6/y_e3bc7d5c.jpg'},
'_type': 'fh_image'},
]
import json
from itertools import groupby
result = {
k: [(sub_obj['_score'], sub_obj['_source']['img_url']) for sub_obj in values]
for k, values in groupby(obj, key=lambda x: x['_source']['img_id'])
}
print(json.dumps(result, indent=4))
import random
from collections import Counter
M, N = 5, 5
matrix = [[random.randrange(0, 10) for _ in range(M)] for _ in range(N)]
# Посчитали количество повторов
result = {
i: sum(v for v in Counter(sub_list).values() if v > 1)
for i, sub_list in enumerate(matrix)
}
print(result)
# А дальше что нужно то и выводите.
print(sorted(result, key=lambda key: result[key], reverse=True))
print(max(result, key=lambda key: result[key]))
--dist=loadscope: tests will be grouped by module for test functions and by class for test methods, then each group will be sent to an available worker, guaranteeing that all tests in a group run in the same process. This can be useful if you have expensive module-level or class-level fixtures. Currently the groupings can’t be customized, with grouping by class takes priority over grouping by module. This feature was added in version 1.19.
--dist=loadfile: tests will be grouped by file name, and then will be sent to an available worker, guaranteeing that all tests in a group run in the same worker. This feature was added in version 1.21.
from datetime import datetime, timedelta
from random import randint
t = datetime.now().replace(minute=0, second=0, microsecond=0)
list_event = [(t + timedelta(minutes=30 * i)).time().isoformat() for i in range(48)]
values = [randint(1, 100) for _ in range(48)]
records = [dict(zip(('time', 'value'), value)) for value in zip(list_event, values)]
from collections import namedtuple
Hint = namedtuple('Hint', ('title', 'event', 'used'))
hints = {
'1': Hint('Помощь зала', lambda: None, 0),
'2': Hint('50/50а', lambda: None, 0),
'3': Hint('Звонок другу', lambda: None, 0)
}
current_hints = hints.copy()
print('Текущии подсказки:\n', hints)
need_help = input("Вам нужна помощь?\n1.Да\n2.Нет\n ")
if need_help == "1":
what_help = input({key: hint.title for key, hint in hints.items() if not hint.used})
tip = current_hints[what_help]
tip.event()
current_hints[what_help] = tip._replace(used=True)
print('Текущии подсказки:\n', [hint.title for hint in current_hints.values() if not hint.used])
from itertools import groupby
source = [
{'code': 'AA01', 'group': 'U01', 'user': '1375', },
{'code': 'AA01', 'group': 'U01', 'user': '1575', },
{'code': 'AA03', 'group': 'U02', 'user': '1375', },
{'code': 'AA02', 'group': 'U02', 'user': '1345', },
{'code': 'AA02', 'group': 'U03', 'user': '1315', },
{'code': 'AA01', 'group': 'U04', 'user': '1615', },
]
result = {k:list(v) for k,v in groupby(source, lambda x: x['group'])}
>>> print(result)
{'U01': [{'code': 'AA01', 'group': 'U01', 'user': '1375'}, {'code': 'AA01', 'group': 'U01', 'user': '1575'}], 'U02': [{'code': 'AA03', 'group': 'U02', 'user': '1375'}, {'code': 'AA02', 'group': 'U02', 'user': '1345'}], 'U03': [{'code': 'AA02', 'group': 'U03', 'user': '1315'}], 'U04': [{'code': 'AA01', 'group': 'U04', 'user': '1615'}]}
>>> result = {k:{row['user']: row['code'] for row in v} for k,v in groupby(source, lambda x: x['group'])}
>>> result
{'U01': {'1375': 'AA01', '1575': 'AA01'}, 'U02': {'1375': 'AA03', '1345': 'AA02'}, 'U03': {'1315': 'AA02'}, 'U04': {'1615': 'AA01'}}
>>>
s = [23,45,67]
from itertools import chain, combinations
def all_subsets(ss):
return chain(*map(lambda x: combinations(ss, x), range(1, len(ss)+1)))
variants = max([vv for vv in (sum(v) for v in all_subsets(s)) if vv % 2 == 0])
d ={'BTC': [(None, None), (1, -0.4), (3, 0.3333333333333333), (0, 0.75), (1, None)], 'ETH': [(None, None), (0, 0.5), (0, 0.3333333333333333), (0, -0.1), (2, None)]}
[dict(zip(d.keys(), v)) for v in zip(*d.values())]
[{'BTC': (None, None), 'ETH': (None, None)},
{'BTC': (1, -0.4), 'ETH': (0, 0.5)},
{'BTC': (3, 0.3333333333333333), 'ETH': (0, 0.3333333333333333)},
{'BTC': (0, 0.75), 'ETH': (0, -0.1)},
{'BTC': (1, None), 'ETH': (2, None)}]