from itertools import groupby
def squeeze(text):
return ''.join(key for key, group in groupby(text))
squeeze('aAaaabbccdcc') # => 'aAabcdc'
def squeeze(text):
for c1, c2 in zip(text[:-1], text[1:]):
if c1 != c2:
yield c1
yield c2
''.join(squeeze('aAaaabbccdcc')) # => 'aAabcdc'
from operator import ne
from itertools import compress, chain
def squeeze(text):
return ''.join(chain(compress(text, map(ne, text[:-1], text[1:])), text[-1]))
squeeze('aAaaabbccdcc') # => 'aAabcdc'
from collections import namedtuple
Record = namedtuple('Record', 'a, b, c, d, e, f, g, h')
r = Record(*[1]*8)
print(r.a, r.b, r.h)
class O():
pass
o = O()
for attr in 'abcdefgh':
setattr(o, attr, 1)
print(o.a, o.b, o.h)
mapping = str.maketrans(
"f,dult`;pbqrkvyjghcnea[wxio]sm'.z",
"абвгдеёжзийклмнопрстуфхцчшщъыьэюя",
)
calc = {
'квадрат': {
'площадь': lambda **kwargs: bottom ** 2,
'периметр':lambda **kwargs: bottom * 4,
},
'прямоугольник': {
'площадь': lambda **kwargs: bottom * height,
'периметр':lambda **kwargs: (bottom + height) * 2,
},
'треугольник': {
'площадь': lambda **kwargs: bottom * height / 2,
}
}
def ask(question, options=None, expected=str):
if options:
question = '{} ({}): '.format(question, '|'.join(options))
answer = None
while (options and answer not in options) or (type(answer) is not expected):
answer = input(question)
if expected is str:
answer = answer.lower().translate(mapping)
candidates = set(option for option in options if option.startswith(answer))
if len(candidates) == 1:
answer = candidates.pop()
else:
try:
answer = expected(answer)
except ValueError:
pass
return answer
if __name__ == '__main__':
figure = ask('Какую фигуру необходимо рассчитать?', set(calc))
parameter = ask('Какой параметр требуется вычислить?', set(calc[figure]))
bottom = ask('Введите длину основания: ', expected=float)
if figure == 'квадрат':
height = bottom
else:
height = ask('Введите высоту: ', expected=float)
result = calc[figure][parameter](bottom=bottom, height=height)
print(f'{parameter.title()} {figure}а: {result:.3f}')
d = dict((int(k), v) if k.isdigit() else (k, v) for (k, v) in d.items())
def convert(item):
try:
return int(item)
except ValueError:
return item
d = dict(zip(map(convert, d.keys()), d.values()))
key = lambda c: ord('Е') + 0.5 if c == 'Ё' else ord(c)
import locale
from functools import cmp_to_key
from collections import OrderedDict
locale.setlocale(locale.LC_ALL, 'Russian_Russia.1251')
a = [{'src': 'Яблоко', 'dst': 2343}, {'src': 'Ананас', 'dst': 323}, {'src': 'Ёжик', 'dst': 3223}]
# Чтобы не вызывать связку cmp_to_key(locale.strcoll) в sorted() многократно
def keyfunc(item, func=cmp_to_key(locale.strcoll)):
return func(item[0])
d = OrderedDict(sorted(((e['src'], e['dst']) for e in a), key=keyfunc))
# Чтобы не вызывать связку cmp_to_key(locale.strcoll) в sorted() многократно
def keyfunc(item, func=cmp_to_key(locale.strcoll)):
return func(item['src'])
sorted(a, key=keyfunc)
from sortedcontainers import SortedDict
d = SortedDict(cmp_to_key(locale.strcoll), {e['src']:e['dst'] for e in a})
from itertools import count, cycle
def distances(n):
yield n-1
for i in range(n-1, 0, -1):
yield i
yield i
yield i
def directions(di=0, dj=1):
while True:
yield di, dj
di, dj = dj, -di
def matrix(n=3, ival=count(1), fdir=directions, fdist=distances, i=0, j=0):
m = [[0]*n for i in range(n)]
for (di, dj), distance in zip(fdir(), fdist(n)):
for step in range(distance):
m[i][j] = next(ival)
i += di
j += dj
return m
for row in matrix(9):
print(*map('{:02d}'.format, row))
from itertools import count, cycle, chain, tee
def distances(n):
return chain([n-1], *zip(*tee(range(n-1, 0, -1), 2)), [1])
def directions():
return cycle([(0, 1), (1, 0), (0, -1), (-1, 0)])
01 02 03 04 05 06 07 08 09
32 33 34 35 36 37 38 39 10
31 56 57 58 59 60 61 40 11
30 55 72 73 74 75 62 41 12
29 54 71 80 81 76 63 42 13
28 53 70 79 78 77 64 43 14
27 52 69 68 67 66 65 44 15
26 51 50 49 48 47 46 45 16
25 24 23 22 21 20 19 18 17
import numpy as np
a1 = np.array([1,2,3,4,5], dtype=np.float64)
a2 = np.array([1,2,3,4,0], dtype=np.float64)
print (a1 / a2)
[ 1. 1. 1. 1. inf]
with open('z:\\test.csv', 'rt') as f:
data = [line.strip().split(';') for line in f]
matrix = [
['a', '3', '5', '7'],
['b', '1', '2', '3'],
['c', '1', '2', '3'],
]
[sum(int(item) for item in column if item.isdigit()) for column in zip(*matrix)]
[sum(map(int, filter(str.isdigit, column))) for column in zip(*matrix)]
trans_table = str.maketrans('ETOPAHKXCBMetopahkxcbm', 'ЕТОРАНКХСВМеторанкхсвм')
'Cтрана X'.translate(trans_table)
from random import choice
from itertools import chain, repeat
from functools import reduce
text = "Quick brown fox jumps over the lazy dog"
repl = ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
' '.join(f'{word} {choice(repl)}' for word in text.split())
'Quick two brown four fox one jumps seven over four the three lazy one dog two'
def inserts(replacements):
while True:
yield choice(replacements)
' '.join(chain(*zip(text.split(), inserts(repl))))
' '.join(chain(*zip(text.split(), map(choice, repeat(repl)))))
' '.join(chain(*map(lambda word: (word, choice(repl)), text.split())))
' '.join(reduce(lambda lst, word: lst + [word, choice(repl)], text.split(), []))
import re
re.split('(\d+)', "a44b3c222")
[int(s) if s.isdigit() else s for s in filter(None, re.split('(\d+)', "a44b3c222"))]
[[str, int][s.isdigit()](s) for s in filter(None, re.split('(\d+)', "a44b3c222"))]
from itertools import groupby
[int(''.join(v)) if k else ''.join(v) for k, v in groupby("a44b3c222", key=lambda s: s.isdigit())]
from math import gcd
lcm = a * b / gcd(a, b)
from itertools import count, dropwhile
lcm = next(dropwhile(lambda d: d % a != 0 or d % b != 0, count(max(a, b))))
text = 'The quick brown fox jumps over the lazy dog'
checklist = {'fox', 'dog', 'cat'}
common_words = set(text.split()) & checklist
print(common_words)
{'fox', 'dog'}