from random import randint
import tkinter
class MineSweeper(object):
def __init__(self, rows, columns, mines_density):
self.columns, self.rows, self.minescount = columns, rows, int(mines_density * rows * columns)
self.window = root = tkinter.Tk()
self.table = tkinter.Frame(self.window)
self.table.pack()
self.btnew = tkinter.Button(self.window, text='New')
self.btnew.pack()
self.btnew.config(command=lambda: self.reset())
self.squares = []
for y in range(rows):
self.squares.append([])
for x in range(columns):
button = tkinter.Button(self.table, padx=0, pady=0, width=2, height=1, bg='silver')
button.grid(row=x, column=y, sticky='news')
self.squares[-1].append(button)
def clicked(ax=x, ay=y):
def deeper(bx, by):
s = self.minesaround[by][bx]
if self.state[by][bx] < 0:
self.refresh(bx, by, s)
if not s:
for i, j in self.neighbours(bx, by):
deeper(i, j)
if self.state[ay][ax] == -1:
if (ax, ay) in self.mines:
self.refresh(ax, ay, 9)
else:
deeper(ax, ay)
button.config(command=clicked)
def right_clicked(widget, ax=x, ay=y):
s = self.state[ay][ax]
if s < 0:
self.refresh(ax, ay, -3 - s)
button.bind('<Button-3>', right_clicked)
print(root.winfo_screenwidth(), (root.winfo_screenheight()))
root.geometry('{:+d}{:+d}'.format((root.winfo_screenwidth() - columns * 70 + 11) // 2,
(root.winfo_screenheight() - rows * 50 + 11) // 2))
self.state = [[-1] * self.columns for _ in range(self.rows)]
self.reset()
def neighbours(self, ax, ay):
for i in range(max(ax - 1, 0), min(ax + 2, self.columns)):
for j in range(max(ay - 1, 0), min(ay + 2, self.rows)):
if i != ax or j != ay:
yield i, j
def reset(self):
self.mines = set()
while len(self.mines) < self.minescount:
self.mines.add((randint(0, self.columns - 1), randint(0, self.rows - 1)))
self.minesaround = [[0] * self.columns for _ in range(self.rows)]
for x, y in self.mines:
for i, j in self.neighbours(x, y):
self.minesaround[j][i] += 1
for j in range(self.rows):
for i in range(self.columns):
self.refresh(i, j, -1)
def refresh(self, x, y, newstate):
button = self.squares[y][x]
if self.state[y][x] != newstate:
self.state[y][x] = newstate
text, fg = (('', None), ('1', 'blue'), ('2', 'darkgreen'), ('3', 'red'),
('4', 'darkblue'), ('5', 'darkred'), ('6', 'black'), ('7', 'red'),
('8', 'red'), ('☠', 'red'), ('⚑', 'yellow'), ('', None))[newstate]
bg = bg, relief = (('white', 'sunken'), ('silver', 'raised'))[newstate < 0]
button.config(text=text, fg=fg, bg=bg, relief=relief)
MineSweeper(40, 25, 1 / 6).window.mainloop()
def f(s):
for i in range(1, len(s) // 2 + 1):
if s[:len(s) - i] == s[i:]:
return s[:i]
print(f("PYTHONPYTHONPYTHONPYTHONPYTHONPYTHONP"))
from collections import Counter
def display(t, gen):
sz = 10
sz2 = sz * 2
space = [[" "] * sz2 for i in range(sz2)]
for x, y in gen:
if sz > x >= -sz <= y < sz:
space[y + sz][x + sz] = "()"
for row in space:
print(''.join(row))
print("{:>3n}".format(t), "--" * sz2)
def game_life(cells, generations):
gen = set((x, y) for y, row in enumerate(cells) for x, cell in enumerate(row) if cell)
for t in range(generations):
display(t, gen)
ngh = Counter((x + i, y + j) for x, y in gen for i in range(-1, 2) for j in range(-1, 2))
gen = set(xy for xy, cnt in ngh.items() if cnt == 3 or cnt == 4 and xy in gen)
# game_life([[1, 1, 1]], 5) # палка
# game_life([[1, 1], [1, 1]], 5) # квадрат
game_life([[1, 1, 1], [0, 0, 1], [0, 1, 0]], 40) # планер
a, b = mmh3.hash64('abc')
print((a << 64) + b)
def tet(a, n):
return a ** (tet(a, n - 1)) if n else 1
def main():
a = str(90)
b = str(678)
c = str(670)
loc = locals()
print(''.join(loc[ch] for ch in "abc"))
main()
my_string = "a"
mapping = [('a', 'ab'), ('b', 'bc'), ('c', 'cd'), ('d', 'de'), ('e', 'ef')]
for k, v in mapping:
my_string = my_string.replace(k, v)
print(my_string)
# просто и быстро
STR_TEXT = "Требуется произвести подсчет числа прописных букв в тексте."
AllCapitalLetters = set("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ")
CapitalInTEXT = [c for c in STR_TEXT if c in AllCapitalLetters]
print(CapitalInTEXT)
print(len(CapitalInTEXT))
STR_TEXT = "CapitalInTEXT = [c for c in STR_TEXT if 'A' <= c <= 'Z']"
CapitalInTEXT = [c for c in STR_TEXT if 'A' <= c <= 'Z']
In [1]: ''.join(chr(i) for i in range(1025, 1072))
Out[1]: 'ЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
в других кодировках по-другому.AllCapitalLetters = 'ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
# обрати внимание на порядок букв
# на неотсортированном AllCapitalLetters алгоритм виснет
CapitalInTEXT = []
for c in STR_TEXT:
i = 0
j = len(AllCapitalLetters) - 1
while i <= j:
m = (i + j) // 2
cm = AllCapitalLetters[m]
if c > cm:
i = m + 1
elif c < cm:
j = m - 1
else:
CapitalInTEXT.append(cm)
break
from bisect import bisect_left
AllCapitalLetters = 'ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
CapitalInTEXT = []
for c in STR_TEXT:
idx = bisect_left(AllCapitalLetters, c)
if idx < len(AllCapitalLetters) and c == AllCapitalLetters[idx]:
CapitalInTEXT.append(c)
print(acts[0].__closure__)
print(acts[1].__closure__)
print(acts[0].__closure__[0].cell_contents)
def makeActions():
acts = []
for i in range(5):
def f(x, a=i):
return a ** x
acts.append(f)
return acts
acts.append(lambda x, a=i: a ** x)