words = ['abandon', 'ability', 'able', 'about', 'above', 'absent', 'absorb', 'abact', 'absurd', 'abuse']
number = 12
index = 0
seed = ' '.join([words[index]] * number) # повторяет n раз указанный элемент списка через пробел
print(seed)
words = ['abandon', 'ability', 'able', 'about', 'above', 'absent', 'absorb', 'abact', 'absurd', 'abuse']
import random
start = 0
length = 12
stop = start + length
seed = words[start: stop]
random.shuffle(seed)
seed = ' '.join(seed)
print(seed)
line = {'1': '1_value', '2': '3454358', '3': '3_value', '4': '313123','5':'5_value'}
data = tuple(line.values())
print(data)
line = {'1': '1_value', '2': '3454358', '3': '3_value', '4': '313123','5':'5_value'}
data =(line["1"],line["2"],line["3"],line["4"],line["5"])
print(data)
import pandas as pd
def get_pairs(keys: list, data: list) -> dict:
"""
Подготовительная функция
Раскладывает значения из data по ключам из key в порядке, как в key
:param keys: ['foo', 'spam', 'foo', ...]
:param data: [('foo', 'bar'), ('foo', 'baz'), ('spam', 'ham'), ...]
:return: {'foo': ['bar', 'baz'], 'spam': ['ham'], ...}
"""
inter_pairs = dict([(key, []) for key in set(keys)])
while bool(len(data)):
key, value = data.pop(0)
inter_pairs[key].append(value)
return inter_pairs
def prepare_next_attr(key: str, value: str, descr: list) -> tuple:
"""
Служебная функция
Готовит очередной комплект атрибутов
для вычисления следующего результата
:param key:
:param value:
:param descr:
:return: next_key, next_pair, next_descr
"""
descr = [i.lower() for i in descr]
next_key = f'{key.lower()}, '
next_pair = f'{next_key}{value.lower()}'
next_descr = descr.pop(0)
return next_key, next_pair, next_descr
def get_next_res_item(key: str, value: str, descr: list) -> str:
"""
Служебная функция
Готовит результат, сравнивая по Descr
(тут подгонка if-ами под задание)
:param key:
:param value:
:param descr:
:return: результат для помещения в список результатов
"""
next_key, next_pair, next_descr = prepare_next_attr(key, value, descr)
if next_pair == next_descr:
res_item = f'{key}: {value};'
elif next_key in next_descr:
res_item = f'{key};'
else:
res_item = f'{key}'
return res_item
def make_result(keys: list, inter_pairs: dict, descr: list) -> pd.Series:
"""
Перебирает ключи, получает для каждого очередной результат,
складывает результаты в pd.Series
:param keys:
:param inter_pairs:
:param descr:
:return: pd.Series с результатами
"""
intermedia_result = []
for key in keys:
value = inter_pairs[key].pop(0)
intermedia_result.append(
get_next_res_item(key,
value,
descr)
)
return pd.Series(intermedia_result)
if __name__ == '__main__':
df1 = {
'Descr': ["VALVE, PRESSURE", "pump ttf", "Valve, electrical", "Geeku, electrical",
"VALVE, OVERBOARD, BUTTERFLY"],
'N_Product': ["VALVE", "PUMP", "VALVE", "GEEKU", "VALVE"],
}
df2 = {'N_Product': ["VALVE", "VALVE", "VALVE", "PUMP", "GEEKU"],
'M_Product': ["PRESSURE", "qwerty", "", "", "ELECTRICAL"],
}
target = {
'Descr': ["VALVE, PRESSURE", "pump ttf", "Valve, electrical", "Geeku, electrical", "VALVE, OVERBOARD, "
"BUTTERFLY"],
'N_Product': ["VALVE", "PUMP", "VALVE", "GEEKU", "VALVE"],
'Result': ["VALVE: PRESSURE;", "PUMP", "VALVE;", "GEEKU: ELECTRICAL;", "VALVE;"], }
df1 = pd.DataFrame(df1)
df2 = pd.DataFrame(df2)
df_target = pd.DataFrame(target)
df2_list = list(zip(df2['N_Product'], df2['M_Product']))
pairs = get_pairs(df1['N_Product'], df2_list)
result = make_result(df1['N_Product'], pairs, df1['Descr'])
df1['Result'] = result.values
print(df1)
print(all(df1 == df_target))
for code in store:
price_1 = code['price']
for name in goods:
code = goods[name]
print('Название товара:', name, ' Его код:', code)
for code in store:
price_1 = store[code][0]['price']
quantity_1 = store[code][0]['quantity']
summ = price_1 * quantity_1
print('полная стоимость товара:', summ)
for name in goods:
code = goods[name]
print('Название товара:', name, ' Его код:', code)
for code, value in store.items():
price_1 = value[0]['price']
quantity_1 = value[0]['quantity']
summ = price_1 * quantity_1
print('полная стоимость товара:', summ)
import hashlib
from random import randint
ALGS = ('sha3_512', 'sha384', 'md5', 'shake_128', 'sha256', 'sha3_256', 'sha3_224', 'sha512', 'blake2s', 'sha3_384', 'sha224', 'shake_256', 'blake2b', 'sha1')
first = 1
last = 999999
def prepare_target(target):
if not isinstance(target, bytearray):
if not isinstance(target, str):
target = str(target)
target = target.encode()
return target
def calc_hash(alg, target):
target = prepare_target(target)
if alg in ALGS:
command = f'hashlib.{alg}({target})'
try:
return eval(command).hexdigest()
except TypeError:
pass
def create_test_target(target_hash):
if target_hash is not None:
return '1'*len(target_hash)
def detect_hash_alg(target_hash):
result_algs = []
for alg in ALGS:
test_target = create_test_target(target_hash)
my_hash = calc_hash(alg, test_target)
if my_hash is not None:
lenght = len(my_hash)
if lenght == len(target_hash):
result_algs.append(alg)
return result_algs
def find_target(target_hash):
stop = False
algs = detect_hash_alg(target_hash)
print(f'подходящие алгоритмы: {algs}')
for i in range(first, last+1):
for alg in algs:
first_hash = calc_hash(alg, i)
if first_hash == target_hash:
print(f'founded\t{i} {alg}')
stop = True
break
if stop:
break
if not stop:
print(f'for {target_hash} not found')
if __name__ == '__main__':
target_hash = '127b1f0d6253fdfe78d806497217f2454a30e124d1f655b6c2a8c68f6dc7a7061993557b50252f253220a3a059142290cd0c2c467c0ee5bfbbd6a8a538c5d040'
test = randint(first, last+1)
alg = 'sha256'
test_hash = calc_hash(alg, test)
print(test_hash)
print(f'target \t{test} {alg}')
print('тестовый поиск:')
find_target(test_hash)
print('боевой поиск:')
find_target(target_hash)
def more_or_less_one(number: int) -> str:
return str(not any([abs(int(str(number)[x]) - int(str(number)[x+1]))-1 for x in range(len(str(number))-1)]))
data = 234543
print(more_or_less_one(data))
data = 234564
print(more_or_less_one(data))
diction = {'city': ['zoo', 'park', 'cafe'], 'zoo': ['tiger', 'zebra'],
'park': ['squirrel', 'dog'], 'cafe': 'people'}
def detect_root(in_dict):
for key in in_dict.keys():
if key in set(in_dict.keys()) - set(in_dict[key]):
return key
def detect_person_place(in_dict, person):
for place in in_dict[detect_root(in_dict)]:
if person in in_dict[place]:
return place
person = 'people'
print('Yes' if person in diction.values() else 'No')
if person in diction.values():
print(detect_person_place(diction, person))
class User:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __repr__(self):
return f'a:{self.a}\tb:{self.b}\tc:{self.c}'
users = [User(1, 2, 3), User(('z', 'y', 'x'), 5, 6), User('a', 'b', None)]
for user in users:
print(user)
print(f'a:{user.a}')
print(users[1].a)
print(users[2].c)
from telethon import utils
real_id, peer_type = utils.resolve_id(-1001234567891)
print(real_id) # 1234567891
print(peer_type) # <class 'telethon.tl.types.PeerChannel'>
peer = peer_type(real_id)
print(peer) # PeerChannel(channel_id=1234567891)
results = []
table = [i for i in range(1000)]
for record in table:
double = None
triple = None
if not bool(record % 2):
double = record
if not bool(record % 3):
triple = record
if any([double, triple]):
results.append({'double': double,'triple': triple})
print(results)