def iter_pigeons(): i = 1 while True: yield sum(range(1, i + 1)) i += 1 def checkio(portions): pigeons = iter_pigeons() feeded = 0 while True: hungry = next(pigeons) if portions <= hungry: return portions if portions > feeded else feeded…
CheckIO: Pawn Brotherhood
import itertools def safe_pawns(pawns): safe_squares = itertools.chain(*[calc_safe_squares(p) for p in pawns]) return len(pawns & set(safe_squares)) def calc_safe_squares(pos): return (chr(ord(pos[0]) – 1) + str(int(pos[1]) + 1), chr(ord(pos[0]) + 1) + str(int(pos[1]) + 1)) if __name__ == ‘__main__’: #These “asserts” using only…
CheckIO: Speech Module
FIRST_TEN = [“one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, “nine”] SECOND_TEN = [“ten”, “eleven”, “twelve”, “thirteen”, “fourteen”, “fifteen”, “sixteen”, “seventeen”, “eighteen”, “nineteen”] OTHER_TENS = [“twenty”, “thirty”, “forty”, “fifty”, “sixty”, “seventy”, “eighty”, “ninety”] HUNDRED = “hundred” def checkio(number): second_tens =…
Python: Exchange rows and columns
# ABC # DEF # GHI >>> rows = [‘ABC’, ‘DEF’, ‘GHI’] >>> cols = [”.join(x) for x in zip(*rows)] >>> cols [‘ADG’, ‘BEH’, ‘CFI’]
CheckIO: Xs and Os Referee
def checkio(rows): cols = [”.join([rows[y][x] for y in range(3)]) for x in range(3)] digs = [”.join([rows[x][x] for x in range(3)]), ”.join([rows[x][2 – x] for x in range(3)])] triples = rows + cols + digs for check in triples: winner =…
CheckIO: The Most Wanted Letter
from string import ascii_lowercase def checkio(text): letters = [x for x in text.lower() if x in ascii_lowercase] counts = sorted({x : letters.count(x) for x in letters}.items(), key=lambda x:x[1], reverse=True) wanted_count = counts[0][1] wanted = sorted([x[0] for x in counts if…
Python: datetime.today()
datetime.today() does’t return today’s date only but today’s datetime. And using datetime.combine, date object can be converted to datetime. >>> from datetime import datetime, date # datetime.today() returns datetime not only date >>> datetime.today() datetime.datetime(2015, 6, 21, 15, 19, 33,…
Python: calculate weeks or months
from dateutil.relativedelta import relativedelta from datetime import datetime today = datetime.today() today.strftime(‘%Y-%m-%d’) # ‘2015-06-14’ next_week = today + relativedelta(weeks=1) next_week.strftime(‘%Y-%m-%d’) # ‘2015-06-21’ next_month = today + relativedelta(months=1) next_month.strftime(‘%Y-%m-%d’) # ‘2015-07-14’ from calendar import monthrange lastday_of_month = monthrange(2015, 6)[1] lastday_of_month #…
Django: copy model instance
To copy model instance, replacing pk value is the easiest way. obj = Foo.objects.get(pk=”foo”) obj.pk = “bar” obj.save() http://stackoverflow.com/questions/4733609/how-do-i-clone-a-django-model-instance-object-and-save-it-to-the-database