pd.get_dummies(df[['event', 'city']], prefix='', prefix_sep='', columns=['event']).groupby('city').sum()
def my_func(x):
...
return result
from itertools import chain
N = 7
for n in chain(range(1, N + 1, 2), range(N - 2, 0, -2)):
print(f'{{:^{N}}}'.format('*' * n))
# print('{{:^{}}}'.format(N).format('*' * n))
>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>30}'.format('right aligned')
' right aligned'
>>> '{:^30}'.format('centered')
' centered '
>>> '{:*^30}'.format('centered') # use '*' as a fill char
'***********centered***********'
from functools import reduce
from operator import mul
def persistence(n):
i = 0
while n > 9:
n = reduce(mul, map(int, str(n)), 1)
i += 1
return i
def persistence(n):
i = 0
while n > 9:
n = eval('*'.join(f'{n}'))
i += 1
return i
from functools import reduce
from operator import mul
from itertools import count
def persistence(n):
for i in count(0):
if n > 9:
n = reduce(mul, map(int, str(n)), 1)
else:
return i
assert persistence(39) == 3
assert persistence(999) == 4
assert persistence(4) == 0
def square_digits_v1(n):
return int(''.join(str(int(x) ** 2) for x in str(n)))
def square_digits_v2(n, t=str.maketrans({str(d): str(d ** 2) for d in range(10)})):
return int(str(n).translate(t))
def square_digits_v3(n): # import re
return int(re.sub('\d', lambda m: str(int(m.group(0)) ** 2), str(n)))
def square_digits_v4(n): # import numpy as np
return int(''.join((np.fromiter(str(n), int) ** 2).astype(str)))
def square_digits_v5(n): # Только вывод на печать
print(*[int(x) ** 2 for x in str(n)], sep='')
from decimal import Decimal
from io import StringIO
def square_digits_v6(n):
with StringIO() as buffer:
for digit in Decimal(n).as_tuple().digits:
print(digit ** 2, end='', file=buffer)
return int(buffer.getvalue())
as_int = lambda f: lambda x: int(f(x))
@as_int
def square_digits_v7(n):
return eval('f"{'+'**2}{'.join(f'{n}')+'**2}"')
import re
def flatten(lst):
return [int(x) for x in re.findall('\d+', str(lst))]
from skimage.util import montage2d
from itertools import chain
def flatten(seq):
try:
yield from chain.from_iterable(flatten(x) for x in seq if x is not None)
except TypeError:
yield seq
flat_list = list(flatten(lst))
Вместо try/except можно использовать проверку hasattr(seq, '__iter__').def flatten(seq):
try:
yield from chain(*map(flatten, seq))
except TypeError:
yield seq