from itertools import groupby
def rle(text):
return [(key, len(tuple(group))) for key, group in groupby(text)]
def rle(src):
result = []
# допишем букву, отличающуюся от последней в строке
src += 'b' if src.endswith('a') else 'a'
# теперь, заметь, она не пуста и проверка на пустоту не нужна
current = src[0]
counter = 0 # тут ошибочка, ты пытался дважды посчитать первую букву
for e in src:
if e == current:
counter += 1
else:
result.append((current, counter))
current = e
counter = 1
return result
string = 'aaabbbtttggghhhavaaa'
print(rle(string))
result.append((current, counter))
class Book(models.Model):
...
author = models.ForeignKey(Author, related_name="books", on_delete=models.SET_NULL, null=True)
...
def index(request):
context = {}
authors = Author.objects.all()
context['authors'] = authors
return render(request, 'index.html', context)
...
<div>
{% for author in authors %}
<h1>{{ author.first_name }}</h1>
{% for book in author.books.all %}
<h4>{{ book.title }}</h4>
{% empty %}
<p>Похоже, у этого автора нет книг :(</p>
{% endfor %}
{% endfor %}
</div>
...
import os
import random
import time
class Colony:
def __init__(self, width, height):
self.width = width
self.height = height
self.field = [
[random.randint(0,1) for i in range(width)] for j in range(height)
]
def live(self):
"""
Check cell's neighbors and modify cell's state.
"""
for row in range(0,self.height):
for col in range(0,self.width):
live_neighbours = self.check_neighbours(row, col)
if live_neighbours < 2:
# die
self.field[row][col] = 0
# elif live_neighbours in (2,3):
# remain as is
elif live_neighbours == 3:
# raise
self.field[row][col] = 1
elif live_neighbours > 3:
# die
self.field[row][col] = 0
def check_neighbours(self, row, col):
live_neighbours = 0
for r in (row - 1, row, row + 1):
for c in (col - 1, col, col + 1):
if c >=0 and c < self.width and r >=0 and r < self.height:
if self.field[r][c] and not (c == col and r == row):
live_neighbours += 1
return live_neighbours
def redraw(self):
"""
Clears screen and draws actual field state.
"""
os.system('clear')
for row in self.field:
for cell in row:
print(cell, end='')
print('', end='\n')
if __name__ == '__main__':
# TODO: check for filename or field dimensions in comand line parameters
# dimensions are hardcoded for now.
start_time = time.time()
first_loop = 1
width = 20
height = 20
colony = Colony(width, height)
while True:
colony.live()
if time.time() - start_time > 0.99 or first_loop:
first_loop = 0
start_time = time.time()
colony.redraw()
print('Ctrl + C to stop')
from random import randint, randrange
from pprint import pprint
from os import system
from copy import deepcopy
class CellLife:
def __init__(self, x = None, y = None):
self.x, self.y = [randrange(10, 25) for _ in range(2) if x is None or y is None]
self.field = [[randint(0, 1) for _ in range(self.x)] for _ in range(self.y)]
self.field_state = None
def environment(self, row, index):
left_neighbors = row[:index][-8:]
right_neighbors = row[index:][1:9:]
while len(left_neighbors + right_neighbors) > 8:
if left_neighbors < right_neighbors:
right_neighbors = right_neighbors[:-1]
else:
left_neighbors = left_neighbors[1:]
return left_neighbors + right_neighbors
def dead_or_alive(self, env, cell):
state = None
if cell == 1:
if env.count(1) < 2 or env.count(1) > 3:
state = False
elif env.count(1) in (2, 3):
state = True
else:
if env.count(1) == 3:
state = True
return state
def start_survival(self):
while self.field_state != self.field:
self.field_state = deepcopy(self.field)
for r_index, row in enumerate(self.field):
for c_index, cell in enumerate(row):
env = self.environment(row, c_index)
state = self.dead_or_alive(env, cell)
if state is not None:
if state is True:
self.field[r_index][c_index] = 1
else:
self.field[r_index][c_index] = 0
system('cls')
pprint(self.field)
cell_field = CellLife()
cell_field.start_survival()
import json
from flask import Flask
test_dict = {"foo": "var"}
json_ = json.dumps(test_dict, indent=4)
app = Flask(__name__)
@app.route('/')
def index():
return json_
app.run()
import requests
request = requests.get(IP)
dict_ = request.json()
Для чего просиживаете на тостере по 5-6 часов в день?