мы типа просто создаем функцию uppercase(greet) которая будет всегда вызываться когда мы пишем greet()? И почему тогда если uppercase(greet) возвращает объект типа функция, как она сама собой вызывается?
@uppercase
def greet():
return 'маленькие буквы'
def greet():
return 'маленькие буквы'
greet = uppercase(greet)
a = "[1, 22 , 3, ad, Bc, 3.5]"
lst=[]
for elem in re.findall('([\w.]+)', a):
if elem.isnumeric():
lst.append(int(elem))
else:
try:lst.append(float(elem))
except:lst.append(elem)
print(lst)
[1, 22, 3, 'ad', 'Bc', 3.5]
import matplotlib.pyplot as plt
def diagram(date,sys,dia):
# создаем пустую канву fig
dpi = 100
fig = plt.figure(dpi = dpi, figsize = (800 / dpi, 600 / dpi))
# "...Столкнулся с проблемой, что для названия осей не хватает места..."
# Добавляем subplot на канву
# [left, bottom, width, height] - каждый параметр в пределах от 0 до 1
# меняем bottom и height, чтобы двигать subplot по канве вверх-вниз,
# тем самым уменьшая или увеличивая место для xlabel и xticks
# bottom + height <= 1
ax = fig.add_axes([0.1, 0.2, 0.8, 0.7])
ax.set_title("Title - values from date")
ax.set_xlabel('Day - Time')
ax.set_ylabel('Values')
# Рисуем графики:
#ax.grid(True) - если надо отобразить сетку
#ax.plot(date, sys, linestyle = 'solid', marker='o', markersize=1, label='SYS')
#ax.plot(date, dia, linestyle = 'solid', marker='o', markersize=1, label='DIA')
# Рисуем диаграмму:
ax.bar(date, sys, 1 / len(date), color='red', label='SYS')
ax.bar(date, dia, 1 / len(date), color='blue', label='DIA')
ax.legend() # Показываем легенду
#ax.legend(loc='upper left') - изменить положение легенды
# "...как изменить разбиение оси y, что б там было от 0 до 220 с интервалом 10 или 20..."
# от 0 до 220
y_lim_min = 0
y_lim_max = 220
ax.set_ylim(y_lim_min, y_lim_max)
# с интервалом 20
step_major = 20
y_major_ticks = range(y_lim_min, y_lim_max, step_major)
ax.set_yticks(y_major_ticks)
# Меняем параметры для основных тиков оси Х (для Y - axis='y', для обеих осей - axis='both')
# для основных тиков which='major', для дополнительных which='minor'
ax.tick_params(axis='x', which='major', labelsize=10, labelrotation=45)
plt.savefig('test.png', dpi = dpi) # Сохранить в файл
plt.show()
import random
import datetime as dt
day = [dt.datetime(2021, 2, 16, 15, 15, 00) + dt.timedelta(hours=i*3) for i in range(0,15)]
sys = [random.randint(110,140) for _ in range(15)]
dia = [i - random.randint(1,5)-30 for i in sys]
diagram(day,sys,dia)
def del_dup(line):
stack = []
for char in line:
stack.pop() if stack and char == stack[-1] else stack.append(char)
return ''.join(stack)
text = 'wwaldaadicffenn'
print(del_dup(text))
In [4]:
alice
newlist = ['650776-2200520-000', '654446-0444530-000', '788126-8895872-000']
new_list = [' '.join(x.split('-',1)) for x in newlist]
print(new_list)
In [8]:
['650776 2200520-000', '654446 0444530-000', '788126 8895872-000']
new_text = '\n'.join(' '.join(x.split('-',1)) for x in newlist)
print(new_text)
In [9]:
650776 2200520-000
654446 0444530-000
788126 8895872-000
f = open(file,"rb", encoding='...')
list1 = [1, 3, 5, 6, 10]
k = len(list1)
for i, _ in enumerate(list1):
print(list1[(i-1)] + list1[(i+1)%k], end=' ')
partition = 'boot'
out="""
# mtd0: 00500000 00020000 "boot"
# mtd1: 00500000 00020000 "recovery"
# mtd2: 00140000 00020000 "misc"
# mtd3: 00060000 00020000 "splash"
# mtd4: 0aa00000 00020000 "system"
# mtd5: 05d00000 00020000 "cache"
# mtd6: 0a6a0000 00020000 "userdata"
# mtd7: 01400000 00020000 "cust"
"""
for line in out.splitlines():
if partition in line:
print(line.split()[1][:-1])
break
In [25]:
mtd0
for line in out.splitlines():
if partition in line:
print(line[2:6])
break
a = '{один|два|три}{текст_2{{один|два|три}|{один|два|три}}|{один|два|три}}текст_1'
res = re.search('({.+})({.+})', a)
print(res.group(1))
print(res.group(2))
In [8]:
{один|два|три}
{текст_2{{один|два|три}|{один|два|три}}|{один|два|три}}
class Test:
def creat_role(self,ctx):
print("ctreate_role")
loading_bar(self.update_mute)(ctx)
# self.update_mute(ctx)
# @loading_bar
def update_mute(self, ctx):
print(f"update_mute {ctx}")
def loading_bar(func):
print("loading_bar")
def decorator(*args, **kwargs):
print("decorator")
func(*args, **kwargs)
for i in range(1, 6):
print("finish")
return decorator
loading_bar(self.update_mute)(ctx)
, а # self.update_mute(ctx)
# @loading_bar
раскомментировать text = 'Lorem ipsum dolor sit amet, 1234567890123456789012345678901234567890, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
from textwrap import wrap
def justify(line, width):
gap_width, max_replace = divmod(width - len(line) + line.count(' '), line.count(' '))
return line.replace(' ', ' ' * gap_width).replace(' ' * gap_width, ' ' * (gap_width + 1), max_replace)
def lines_formatter(text, width):
lines = wrap(text, width, break_long_words=False)
for i, line in enumerate(lines[:-1]):
if len(line) <= width and line.count(' '):
lines[i] = justify(line, width).rstrip()
return '\n'.join(lines)
print(lines_formatter(text, 80))
In [17]:
Lorem ipsum dolor sit amet, 1234567890123456789012345678901234567890,
consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua.
print(lines_formatter(text, 35))
In [18]:
Lorem ipsum dolor sit amet,
1234567890123456789012345678901234567890,
consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut
labore et dolore magna aliqua.
def sumelem(seq, step):
for i, elem in enumerate(seq,1):
if i%step:
yield elem
else:
yield elem
yield sum(seq[i-step:i])
print(*sumelem(a, 5))
Расскажите о своем мнении, как сделать код лучше?
alphabet = 'abcdefghijklmnopqrstuvwxyz'
text = "The sunset sets at twelve o'clock."
def alphabet_position(text):
text = ' '.join(char for char in text.lower() if char.isalpha())
return text.translate({ord(c): str(i) for i,c in enumerate(alphabet,1)})
print(alphabet_position(text))
In [4]:
20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11