curl -X GET "https://api.coingecko.com/api/v3/coins/list" -H "accept: application/json" | json_pp >> cash_list
cat cash_list | grep -E "id.+bitcoin.+cash"
"id" : "10x-long-bitcoin-cash-token",
"id" : "10x-short-bitcoin-cash-token",
"id" : "1x-short-bitcoin-cash-token",
"id" : "3x-long-bitcoin-cash-token",
"id" : "3x-short-bitcoin-cash-token",
"id" : "bitcoin-cash",
"id" : "bitcoin-cash-sv",
"id" : "bitcoin-free-cash",
"id" : "ebitcoin-cash",
dann = [
(89, 20, 41, 1, 11),
(11, 1, 1, 1, 1)
]
def round_up(v, d):
result = v // d + (1 if v % d else 0)
return result
def find(room_1, max_level, room_old, p_old, level_old):
count_room_for_level = 0
# Определим количество этажей на этаже
if max_level == 1 and p_old == 1:
return 1, 1
for count_room_for_level in range(40):
if ((level_old - 1) * count_room_for_level) * p_old < room_old < (count_room_for_level * level_old) * p_old:
print(count_room_for_level)
break
else:
return -1
# Определим возможный подъезд
p_new = round_up(room_1, (max_level * count_room_for_level))
# Этаж
level_new = round_up(room_1, count_room_for_level) % max_level
print(p_new, level_new)
return p_new, level_new
print(list(find(*v) for v in dann))
from collections import defaultdict
from itertools import chain
result = defaultdict(int)
first = [{'month': 'марта', 'stat': 10}, {'month': 'февраля', 'stat': 5}, {'month': 'января', 'stat': 20}]
second = [{'month': 'марта', 'stat': 12}, {'month': 'февраля', 'stat': 7}, {'month': 'января', 'stat': 17}]
for row in chain(first, second):
result[row['month']] += row['stat']
print([{'month': k, 'stat': v} for k, v in result.items()])
a = [[[], [[{'a': 1, 'b': 2, 'c': [1, 2, []], 'd':0}, []]], [1, 2, 3], []]]
def clear_data(data):
if isinstance(data, (list, tuple)):
result = []
for value in data:
value = clear_data(value)
if value:
result.append(value)
if len(result) == 1:
return result[0]
return result
elif isinstance(data, dict):
result = {}
for key, value in data.items():
value = clear_data(value)
if value:
result[key] = value
if result:
return result
return data
print(clear_data(a))
[{'a': 1, 'b': 2, 'c': [1, 2]}, [1, 2, 3]]
import re
from dataclasses import dataclass
@dataclass
class Time:
minute: int
second: int
ms: int
@classmethod
def init(cls, data):
return cls(**{k: int(v) for k, v in data.items()})
def to_seconds(self):
return self.minute * 60 + self.second
strings = ["1m57s", "17s520ms", "1m", "10s"]
time_parse = re.compile(r"((?P<minute>\d+)(m(?!s)))?((?P<second>\d+)(s))?((?P<ms>\d+)(ms))?")
d = [Time.init(time_parse.match(v).groupdict(default='0')) for v in strings]
print(d)
print([v.to_seconds() for v in d])
[Time(minute=1, second=57, ms=0), Time(minute=0, second=17, ms=520), Time(minute=1, second=0, ms=0), Time(minute=0, second=10, ms=0)]
[117, 17, 60, 10]
# Ваш файл
file = """
Петров;85;92;78
Сидоров;100;88;94
Иванов;58;72;85
""".strip().split('\n')
# преобразуем в данные
data = {v[0]: list(map(float, v[1:])) for v in (s.split(';') for s in file)}
print(data)
# разворачиваем ваш список и считаем
avg = {i: f'sum({l})/{len(l)} = {sum(l) / len(l)}' for i, l in enumerate(zip(*data.values()))}
print(avg)
free -m | sed -n 2p | awk '{print $4}'
alph = {
"q": "й", "w": "ц", "e": "у", "r": "к", "t": "е", "y": "н", "u": "г", "i": "ш", "o": "щ", "p": "з", "a": "ф",
"s": "ы", "d": "в", "f": "а", "g": "п", "h": "р", "j": "о", "k": "л", "l": "д", "z": "я", "x": "ч", "c": "с",
"v": "м", "b": "и", "n": "т", "m": "ь", " ": " ", ";": "ж", "'": "э", "?": ",", "/": ".", "&": "?", "`": "ё",
"[": "х", "]": "ъ", ",": "б", ".": "ю"
}
en_char = ''.join(alph)
ru_char = ''.join(alph.values())
trans = ''.maketrans(en_char, ru_char)
print('ghbdtn'.translate(trans))
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]))