{"title": "100 doors", "language": "Python 2.5+", "task": "There are 100 doors in a row that are all initially closed. \n\nYou make 100 passes by the doors. \n\nThe first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "doors = [False] * 100\nfor i in range(100):\n for j in range(i, 100, i+1):\n doors[j] = not doors[j]\n print(\"Door %d:\" % (i+1), 'open' if doors[i] else 'close')\n"} {"title": "100 doors", "language": "Python 3.x", "task": "There are 100 doors in a row that are all initially closed. \n\nYou make 100 passes by the doors. \n\nThe first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "for i in range(1, 101):\n if i**0.5 % 1:\n state='closed'\n else:\n state='open'\n print(\"Door {}:{}\".format(i, state))\n"} {"title": "100 prisoners", "language": "Python", "task": "The Problem:\n* 100 prisoners are individually numbered 1 to 100\n* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n* Prisoners start outside the room\n:* They can decide some strategy before any enter the room.\n:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n:* A prisoner can open no more than 50 drawers.\n:* A prisoner tries to find his own number.\n:* A prisoner finding his own number is then held apart from the others.\n* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. \n\n\n;The task:\n# Simulate several thousand instances of the game where the prisoners randomly open drawers\n# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n:* First opening the drawer whose outside number is his prisoner number.\n:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n;References:\n# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "import random\n\ndef play_random(n):\n # using 0-99 instead of ranges 1-100\n pardoned = 0\n in_drawer = list(range(100))\n sampler = list(range(100))\n for _round in range(n):\n random.shuffle(in_drawer)\n found = False\n for prisoner in range(100):\n found = False\n for reveal in random.sample(sampler, 50):\n card = in_drawer[reveal]\n if card == prisoner:\n found = True\n break\n if not found:\n break\n if found:\n pardoned += 1\n return pardoned / n * 100 # %\n\ndef play_optimal(n):\n # using 0-99 instead of ranges 1-100\n pardoned = 0\n in_drawer = list(range(100))\n for _round in range(n):\n random.shuffle(in_drawer)\n for prisoner in range(100):\n reveal = prisoner\n found = False\n for go in range(50):\n card = in_drawer[reveal]\n if card == prisoner:\n found = True\n break\n reveal = card\n if not found:\n break\n if found:\n pardoned += 1\n return pardoned / n * 100 # %\n\nif __name__ == '__main__':\n n = 100_000\n print(\" Simulation count:\", n)\n print(f\" Random play wins: {play_random(n):4.1f}% of simulations\")\n print(f\"Optimal play wins: {play_optimal(n):4.1f}% of simulations\")"} {"title": "100 prisoners", "language": "Python 3.7", "task": "The Problem:\n* 100 prisoners are individually numbered 1 to 100\n* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n* Prisoners start outside the room\n:* They can decide some strategy before any enter the room.\n:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n:* A prisoner can open no more than 50 drawers.\n:* A prisoner tries to find his own number.\n:* A prisoner finding his own number is then held apart from the others.\n* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. \n\n\n;The task:\n# Simulate several thousand instances of the game where the prisoners randomly open drawers\n# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n:* First opening the drawer whose outside number is his prisoner number.\n:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n;References:\n# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "'''100 Prisoners'''\n\nfrom random import randint, sample\n\n\n# allChainedPathsAreShort :: Int -> IO (0|1)\ndef allChainedPathsAreShort(n):\n '''1 if none of the index-chasing cycles in a shuffled\n sample of [1..n] cards are longer than half the\n sample size. Otherwise, 0.\n '''\n limit = n // 2\n xs = range(1, 1 + n)\n shuffled = sample(xs, k=n)\n\n # A cycle of boxes, drawn from a shuffled\n # sample, which includes the given target.\n def cycleIncluding(target):\n boxChain = [target]\n v = shuffled[target - 1]\n while v != target:\n boxChain.append(v)\n v = shuffled[v - 1]\n return boxChain\n\n # Nothing if the target list is empty, or if the cycle which contains the\n # first target is larger than half the sample size.\n # Otherwise, just a cycle of enchained boxes containing the first target\n # in the list, tupled with the residue of any remaining targets which\n # fall outside that cycle.\n def boxCycle(targets):\n if targets:\n boxChain = cycleIncluding(targets[0])\n return Just((\n difference(targets[1:])(boxChain),\n boxChain\n )) if limit >= len(boxChain) else Nothing()\n else:\n return Nothing()\n\n # No cycles longer than half of total box count ?\n return int(n == sum(map(len, unfoldr(boxCycle)(xs))))\n\n\n# randomTrialResult :: RandomIO (0|1) -> Int -> (0|1)\ndef randomTrialResult(coin):\n '''1 if every one of the prisoners finds their ticket\n in an arbitrary half of the sample. Otherwise 0.\n '''\n return lambda n: int(all(\n coin(x) for x in range(1, 1 + n)\n ))\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Two sampling techniques constrasted with 100 drawers\n and 100 prisoners, over 100,000 trial runs.\n '''\n halfOfDrawers = randomRInt(0)(1)\n\n def optimalDrawerSampling(x):\n return allChainedPathsAreShort(x)\n\n def randomDrawerSampling(x):\n return randomTrialResult(halfOfDrawers)(x)\n\n # kSamplesWithNBoxes :: Int -> Int -> String\n def kSamplesWithNBoxes(k):\n tests = range(1, 1 + k)\n return lambda n: '\\n\\n' + fTable(\n str(k) + ' tests of optimal vs random drawer-sampling ' +\n 'with ' + str(n) + ' boxes: \\n'\n )(fName)(lambda r: '{:.2%}'.format(r))(\n lambda f: sum(f(n) for x in tests) / k\n )([\n optimalDrawerSampling,\n randomDrawerSampling,\n ])\n\n print(kSamplesWithNBoxes(10000)(10))\n\n print(kSamplesWithNBoxes(10000)(100))\n\n print(kSamplesWithNBoxes(100000)(100))\n\n\n# ------------------------DISPLAY--------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# fname :: (a -> b) -> String\ndef fName(f):\n '''Name bound to the given function.'''\n return f.__name__\n\n\n# ------------------------GENERIC -------------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# difference :: Eq a => [a] -> [a] -> [a]\ndef difference(xs):\n '''All elements of xs, except any also found in ys.'''\n return lambda ys: list(set(xs) - set(ys))\n\n\n# randomRInt :: Int -> Int -> IO () -> Int\ndef randomRInt(m):\n '''The return value of randomRInt is itself\n a function. The returned function, whenever\n called, yields a a new pseudo-random integer\n in the range [m..n].\n '''\n return lambda n: lambda _: randint(m, n)\n\n\n# unfoldr(lambda x: Just((x, x - 1)) if 0 != x else Nothing())(10)\n# -> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]\ndef unfoldr(f):\n '''Dual to reduce or foldr.\n Where catamorphism reduces a list to a summary value,\n the anamorphic unfoldr builds a list from a seed value.\n As long as f returns Just(a, b), a is prepended to the list,\n and the residual b is used as the argument for the next\n application of f.\n When f returns Nothing, the completed list is returned.\n '''\n def go(v):\n xr = v, v\n xs = []\n while True:\n mb = f(xr[0])\n if mb.get('Nothing'):\n return xs\n else:\n xr = mb.get('Just')\n xs.append(xr[1])\n return xs\n return lambda x: go(x)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "15 puzzle game", "language": "Python 3.X", "task": "Implement the Fifteen Puzzle Game.\n\n\nThe '''15-puzzle''' is also known as: \n:::* '''Fifteen Puzzle'''\n:::* '''Gem Puzzle'''\n:::* '''Boss Puzzle'''\n:::* '''Game of Fifteen'''\n:::* '''Mystic Square'''\n:::* '''14-15 Puzzle'''\n:::* and some others.\n\n\n;Related Tasks:\n:* 15 Puzzle Solver\n:* [[16 Puzzle Game]]\n\n", "solution": "''' Python 3.6.5 code using Tkinter graphical user interface.''' \n\nfrom tkinter import *\nfrom tkinter import messagebox\nimport random\n\n# ************************************************\n\nclass Board:\n def __init__(self, playable=True):\n while True:\n # list of text for game squares:\n self.lot = [str(i) for i in range(1,16)] + ['']\n if not playable:\n break\n # list of text for game squares randomized:\n random.shuffle(self.lot)\n if self.is_solvable():\n break\n \n # game board is 2D array of game squares:\n self.bd = []\n i = 0\n for r in range(4):\n row = []\n for c in range(4):\n row.append(Square(r,c,self.lot[i]))\n i += 1\n self.bd.append(row)\n \n # How to check if an instance of a 15 puzzle\n # is solvable is explained here:\n # https://www.geeksforgeeks.org/check-instance-15-puzzle-solvable/\n # I only coded for the case where N is even.\n def is_solvable(self):\n inv = self.get_inversions()\n odd = self.is_odd_row()\n if inv % 2 == 0 and odd:\n return True\n if inv % 2 == 1 and not odd:\n return True\n return False\n \n def get_inversions(self):\n cnt = 0\n for i, x in enumerate(self.lot[:-1]):\n if x != '':\n for y in self.lot[i+1:]:\n if y != '' and int(x) > int(y):\n cnt += 1\n return cnt\n\n # returns True if open square is in odd row from bottom:\n def is_odd_row(self):\n idx = self.lot.index('')\n return idx in [4,5,6,7,12,13,14,15] \n\n # returns name, text, and button object at row & col:\n def get_item(self, r, c):\n return self.bd[r][c].get()\n\n def get_square(self, r, c):\n return self.bd[r][c]\n\n def game_won(self):\n goal = [str(i) for i in range(1,16)] + ['']\n i = 0\n for r in range(4):\n for c in range(4):\n nm, txt, btn = self.get_item(r,c)\n if txt != goal[i]:\n return False\n i += 1\n return True\n \n# ************************************************\n\nclass Square: # ['btn00', '0', None]\n def __init__(self, row, col, txt):\n self.row = row\n self.col = col\n self.name = 'btn' + str(row) + str(col)\n self.txt = txt\n self.btn = None\n \n def get(self):\n return [self.name, self.txt, self.btn]\n\n def set_btn(self, btn):\n self.btn = btn\n\n def set_txt(self, txt):\n self.txt = txt\n\n# ************************************************\n\nclass Game:\n def __init__(self, gw):\n self.window = gw\n\n # game data:\n self.bd = None\n self.playable = False\n\n # top frame:\n self.top_fr = Frame(gw,\n width=600,\n height=100,\n bg='light green')\n self.top_fr.pack(fill=X)\n\n self.hdg = Label(self.top_fr,\n text=' 15 PUZZLE GAME ',\n font='arial 22 bold',\n fg='Navy Blue',\n bg='white')\n self.hdg.place(relx=0.5, rely=0.4,\n anchor=CENTER)\n\n self.dir = Label(self.top_fr,\n text=\"(Click 'New Game' to begin)\",\n font='arial 12 ',\n fg='Navy Blue',\n bg='light green')\n self.dir.place(relx=0.5, rely=0.8,\n anchor=CENTER)\n\n self.play_btn = Button(self.top_fr,\n text='New \\nGame',\n bd=5,\n bg='PaleGreen4',\n fg='White',\n font='times 12 bold',\n command=self.new_game)\n self.play_btn.place(relx=0.92, rely=0.5,\n anchor=E)\n\n # bottom frame:\n self.btm_fr = Frame(gw,\n width=600,\n height=500,\n bg='light steel blue')\n self.btm_fr.pack(fill=X)\n\n # board frame:\n self.bd_fr = Frame(self.btm_fr,\n width=400+2,\n height=400+2,\n relief='solid',\n bd=1,\n bg='lemon chiffon')\n self.bd_fr.place(relx=0.5, rely=0.5,\n anchor=CENTER)\n\n self.play_game()\n\n# ************************************************\n\n def new_game(self):\n self.playable = True\n self.dir.config(text='(Click on a square to move it)')\n self.play_game()\n\n def play_game(self):\n # place squares on board:\n if self.playable:\n btn_state = 'normal'\n else:\n btn_state = 'disable'\n self.bd = Board(self.playable) \n objh = 100 # widget height\n objw = 100 # widget width\n objx = 0 # x-position of widget in frame\n objy = 0 # y-position of widget in frame\n\n for r in range(4):\n for c in range(4):\n nm, txt, btn = self.bd.get_item(r,c)\n bg_color = 'RosyBrown1'\n if txt == '':\n bg_color = 'White' \n game_btn = Button(self.bd_fr,\n text=txt,\n relief='solid',\n bd=1,\n bg=bg_color,\n font='times 12 bold',\n state=btn_state,\n command=lambda x=nm: self.clicked(x))\n game_btn.place(x=objx, y=objy,\n height=objh, width=objw)\n \n sq = self.bd.get_square(r,c)\n sq.set_btn(game_btn)\n \n objx = objx + objw\n objx = 0\n objy = objy + objh\n\n # processing when a square is clicked:\n def clicked(self, nm):\n r, c = int(nm[3]), int(nm[4])\n nm_fr, txt_fr, btn_fr = self.bd.get_item(r,c)\n \n # cannot 'move' open square to itself:\n if not txt_fr:\n messagebox.showerror(\n 'Error Message',\n 'Please select \"square\" to be moved')\n return\n\n # 'move' square to open square if 'adjacent' to it: \n adjs = [(r-1,c), (r, c-1), (r, c+1), (r+1, c)]\n for x, y in adjs:\n if 0 <= x <= 3 and 0 <= y <= 3:\n nm_to, txt_to, btn_to = self.bd.get_item(x,y)\n if not txt_to:\n sq = self.bd.get_square(x,y)\n sq.set_txt(txt_fr)\n sq = self.bd.get_square(r,c)\n sq.set_txt(txt_to)\n btn_to.config(text=txt_fr,\n bg='RosyBrown1')\n btn_fr.config(text=txt_to,\n bg='White')\n # check if game is won: \n if self.bd.game_won():\n ans = messagebox.askquestion(\n 'You won!!! Play again?')\n if ans == 'no':\n self.window.destroy()\n else:\n self.new_game()\n return\n \n # cannot move 'non-adjacent' square to open square:\n messagebox.showerror(\n 'Error Message',\n 'Illigal move, Try again')\n return\n\n# ************************************************\n\nroot = Tk()\nroot.title('15 Puzzle Game')\nroot.geometry('600x600+100+50')\nroot.resizable(False, False)\ng = Game(root)\nroot.mainloop()\n"} {"title": "21 game", "language": "Python 2.X and 3.X", "task": "'''21''' is a two player game, the game is played by choosing \na number ('''1''', '''2''', or '''3''') to be added to the ''running total''.\n\nThe game is won by the player whose chosen number causes the ''running total''\nto reach ''exactly'' '''21'''.\n\nThe ''running total'' starts at zero. \nOne player will be the computer.\n \nPlayers alternate supplying a number to be added to the ''running total''. \n\n\n;Task:\nWrite a computer program that will:\n::* do the prompting (or provide a button menu), \n::* check for errors and display appropriate error messages, \n::* do the additions (add a chosen number to the ''running total''), \n::* display the ''running total'', \n::* provide a mechanism for the player to quit/exit/halt/stop/close the program,\n::* issue a notification when there is a winner, and\n::* determine who goes first (maybe a random or user choice, or can be specified when the game begins). \n\n", "solution": "from random import randint\ndef start():\n\tgame_count=0\n\tprint(\"Enter q to quit at any time.\\nThe computer will choose first.\\nRunning total is now {}\".format(game_count))\n\troundno=1\n\twhile game_count<21:\n\t\tprint(\"\\nROUND {}: \\n\".format(roundno))\n\t\tt = select_count(game_count)\n\t\tgame_count = game_count+t\n\t\tprint(\"Running total is now {}\\n\".format(game_count))\n\t\tif game_count>=21:\n\t\t\tprint(\"So, commiserations, the computer has won!\")\n\t\t\treturn 0\n\t\tt = request_count()\n\t\tif not t:\n\t\t\tprint('OK,quitting the game')\n\t\t\treturn -1\n\t\tgame_count = game_count+t\n\t\tprint(\"Running total is now {}\\n\".format(game_count))\n\t\tif game_count>=21:\n\t\t\tprint(\"So, congratulations, you've won!\")\n\t\t\treturn 1\n\t\troundno+=1\n\ndef select_count(game_count):\n\t'''selects a random number if the game_count is less than 18. otherwise chooses the winning number'''\n\tif game_count<18:\n\t\tt= randint(1,3)\n\telse:\n\t\tt = 21-game_count\n\tprint(\"The computer chooses {}\".format(t))\n\treturn t\n\ndef request_count():\n\t'''request user input between 1,2 and 3. It will continue till either quit(q) or one of those numbers is requested.'''\n\tt=\"\"\n\twhile True:\n\t\ttry:\n\t\t\tt = raw_input('Your choice 1 to 3 :')\n\t\t\tif int(t) in [1,2,3]:\n\t\t\t\treturn int(t)\n\t\t\telse:\n\t\t\t\tprint(\"Out of range, try again\")\n\t\texcept:\n\t\t\tif t==\"q\":\n\t\t\t\treturn None\n\t\t\telse:\n\t\t\t\tprint(\"Invalid Entry, try again\")\n\nc=0\nm=0\nr=True\nwhile r:\n\to = start()\n\tif o==-1:\n\t\tbreak\n\telse:\n\t\tc+=1 if o==0 else 0\n\t\tm+=1 if o==1 else 0\n\tprint(\"Computer wins {0} game, human wins {1} games\".format(c,m))\n\tt = raw_input(\"Another game?(press y to continue):\")\n\tr = (t==\"y\")"} {"title": "24 game", "language": "Python", "task": "The 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. \n\nThe goal is for the player to enter an expression that (numerically) evaluates to '''24'''.\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\n\n;Notes\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\n;Related tasks\n* [[24 game/Solve]]\n\n\n;Reference\n* The 24 Game on h2g2.\n\n", "solution": "'''\n The 24 Game\n\n Given any four digits in the range 1 to 9, which may have repetitions,\n Using just the +, -, *, and / operators; and the possible use of\n brackets, (), show how to make an answer of 24.\n\n An answer of \"q\" will quit the game.\n An answer of \"!\" will generate a new set of four digits.\n Otherwise you are repeatedly asked for an expression until it evaluates to 24\n\n Note: you cannot form multiple digit numbers from the supplied digits,\n so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n'''\n\nfrom __future__ import division, print_function\nimport random, ast, re\nimport sys\n\nif sys.version_info[0] < 3: input = raw_input\n\ndef choose4():\n 'four random digits >0 as characters'\n return [str(random.randint(1,9)) for i in range(4)]\n\ndef welcome(digits):\n print (__doc__)\n print (\"Your four digits: \" + ' '.join(digits))\n\ndef check(answer, digits):\n allowed = set('() +-*/\\t'+''.join(digits))\n ok = all(ch in allowed for ch in answer) and \\\n all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n and not re.search('\\d\\d', answer)\n if ok:\n try:\n ast.parse(answer)\n except:\n ok = False\n return ok\n\ndef main(): \n digits = choose4()\n welcome(digits)\n trial = 0\n answer = ''\n chk = ans = False\n while not (chk and ans == 24):\n trial +=1\n answer = input(\"Expression %i: \" % trial)\n chk = check(answer, digits)\n if answer.lower() == 'q':\n break\n if answer == '!':\n digits = choose4()\n print (\"New digits:\", ' '.join(digits))\n continue\n if not chk:\n print (\"The input '%s' was wonky!\" % answer)\n else:\n ans = eval(answer)\n print (\" = \", ans)\n if ans == 24:\n print (\"Thats right!\")\n print (\"Thank you and goodbye\") \n\nif __name__ == '__main__': main() "} {"title": "4-rings or 4-squares puzzle", "language": "Python", "task": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "def foursquares(lo,hi,unique,show):\n\n def acd_iter():\n \"\"\"\n Iterates through all the possible valid values of \n a, c, and d.\n \n a = c + d\n \"\"\"\n for c in range(lo,hi+1):\n for d in range(lo,hi+1):\n if (not unique) or (c <> d):\n a = c + d\n if a >= lo and a <= hi:\n if (not unique) or (c <> 0 and d <> 0):\n yield (a,c,d)\n \n def ge_iter():\n \"\"\"\n Iterates through all the possible valid values of \n g and e.\n \n g = d + e\n \"\"\"\n for e in range(lo,hi+1):\n if (not unique) or (e not in (a,c,d)):\n g = d + e\n if g >= lo and g <= hi:\n if (not unique) or (g not in (a,c,d,e)):\n yield (g,e)\n \n def bf_iter():\n \"\"\"\n Iterates through all the possible valid values of \n b and f.\n \n b = e + f - c\n \"\"\"\n for f in range(lo,hi+1):\n if (not unique) or (f not in (a,c,d,g,e)):\n b = e + f - c\n if b >= lo and b <= hi:\n if (not unique) or (b not in (a,c,d,g,e,f)):\n yield (b,f)\n\n solutions = 0 \n acd_itr = acd_iter() \n for acd in acd_itr:\n a,c,d = acd\n ge_itr = ge_iter()\n for ge in ge_itr:\n g,e = ge\n bf_itr = bf_iter()\n for bf in bf_itr:\n b,f = bf\n solutions += 1\n if show:\n print str((a,b,c,d,e,f,g))[1:-1]\n if unique:\n uorn = \"unique\"\n else:\n uorn = \"non-unique\"\n \n print str(solutions)+\" \"+uorn+\" solutions in \"+str(lo)+\" to \"+str(hi)\n print"} {"title": "4-rings or 4-squares puzzle", "language": "Python 3.7", "task": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "'''4-rings or 4-squares puzzle'''\n\nfrom itertools import chain\n\n\n# rings :: noRepeatedDigits -> DigitList -> Lists of solutions\n# rings :: Bool -> [Int] -> [[Int]]\ndef rings(uniq):\n '''Sets of unique or non-unique integer values\n (drawn from the `digits` argument)\n for each of the seven names [a..g] such that:\n (a + b) == (b + c + d) == (d + e + f) == (f + g)\n '''\n def go(digits):\n ns = sorted(digits, reverse=True)\n h = ns[0]\n\n # CENTRAL DIGIT :: d\n def central(d):\n xs = list(filter(lambda x: h >= (d + x), ns))\n\n # LEFT NEIGHBOUR AND LEFTMOST :: c and a\n def left(c):\n a = c + d\n if a > h:\n return []\n else:\n # RIGHT NEIGHBOUR AND RIGHTMOST :: e and g\n def right(e):\n g = d + e\n if ((g > h) or (uniq and (g == c))):\n return []\n else:\n agDelta = a - g\n bfs = difference(ns)(\n [d, c, e, g, a]\n ) if uniq else ns\n\n # MID LEFT AND RIGHT :: b and f\n def midLeftRight(b):\n f = b + agDelta\n return [[a, b, c, d, e, f, g]] if (\n (f in bfs) and (\n (not uniq) or (\n f not in [a, b, c, d, e, g]\n )\n )\n ) else []\n\n # CANDIDATE DIGITS BOUND TO POSITIONS [a .. g] --------\n\n return concatMap(midLeftRight)(bfs)\n\n return concatMap(right)(\n difference(xs)([d, c, a]) if uniq else ns\n )\n\n return concatMap(left)(\n delete(d)(xs) if uniq else ns\n )\n\n return concatMap(central)(ns)\n\n return lambda digits: go(digits) if digits else []\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Testing unique digits [1..7], [3..9] and unrestricted digits'''\n\n print(main.__doc__ + ':\\n')\n print(unlines(map(\n lambda tpl: '\\nrings' + repr(tpl) + ':\\n\\n' + unlines(\n map(repr, uncurry(rings)(*tpl))\n ), [\n (True, enumFromTo(1)(7)),\n (True, enumFromTo(3)(9))\n ]\n )))\n tpl = (False, enumFromTo(0)(9))\n print(\n '\\n\\nlen(rings' + repr(tpl) + '):\\n\\n' +\n str(len(uncurry(rings)(*tpl)))\n )\n\n\n# GENERIC -------------------------------------------------\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).\n '''\n return lambda xs: list(\n chain.from_iterable(map(f, xs))\n )\n\n\n# delete :: Eq a => a -> [a] -> [a]\ndef delete(x):\n '''xs with the first of any instances of x removed.'''\n def go(xs):\n xs.remove(x)\n return xs\n return lambda xs: go(list(xs)) if (\n x in xs\n ) else list(xs)\n\n\n# difference :: Eq a => [a] -> [a] -> [a]\ndef difference(xs):\n '''All elements of ys except any also found in xs'''\n def go(ys):\n s = set(ys)\n return [x for x in xs if x not in s]\n return lambda ys: go(ys)\n\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n '''A function over a pair of arguments,\n derived from a vanilla or curried function.\n '''\n return lambda x, y: f(x)(y)\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string formed by the intercalation\n of a list of strings with the newline character.\n '''\n return '\\n'.join(xs)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "99 bottles of beer", "language": "Python 3.6+", "task": "Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* Wikipedia 99 bottles of beer\n\n", "solution": "\"\"\"\nExcercise of style. An overkill for the task :-D\n\n1. OOP, with abstract class and implementation with much common magic methods\n2. you can customize:\n a. the initial number\n b. the name of the item and its plural\n c. the string to display when there's no more items\n d. the normal action\n e. the final action\n f. the template used, for foreign languages\n3. strofas of the song are created with multiprocessing\n4. when you launch it as a script, you can specify an optional parameter for \n the number of initial items\n\"\"\"\n\nfrom string import Template\nfrom abc import ABC, abstractmethod\nfrom multiprocessing.pool import Pool as ProcPool\nfrom functools import partial\nimport sys\n\nclass Song(ABC):\n @abstractmethod\n def sing(self):\n \"\"\"\n it must return the song as a text-like object\n \"\"\"\n \n pass\n\nclass MuchItemsSomewhere(Song):\n eq_attrs = (\n \"initial_number\", \n \"zero_items\", \n \"action1\", \n \"action2\", \n \"item\", \n \"items\", \n \"strofa_tpl\"\n )\n \n hash_attrs = eq_attrs\n repr_attrs = eq_attrs\n \n __slots__ = eq_attrs + (\"_repr\", \"_hash\")\n \n def __init__(\n self, \n items = \"bottles of beer\", \n item = \"bottle of beer\",\n where = \"on the wall\",\n initial_number = None,\n zero_items = \"No more\",\n action1 = \"Take one down, pass it around\",\n action2 = \"Go to the store, buy some more\",\n template = None,\n ):\n initial_number_true = 99 if initial_number is None else initial_number\n \n try:\n is_initial_number_int = (initial_number_true % 1) == 0\n except Exception:\n is_initial_number_int = False\n \n if not is_initial_number_int:\n raise ValueError(\"`initial_number` parameter must be None or a int-like object\")\n \n if initial_number_true < 0:\n raise ValueError(\"`initial_number` parameter must be >=0\")\n \n \n true_tpl = template or \"\"\"\\\n$i $items1 $where\n$i $items1\n$action\n$j $items2 $where\"\"\"\n \n strofa_tpl_tmp = Template(true_tpl)\n strofa_tpl = Template(strofa_tpl_tmp.safe_substitute(where=where))\n \n self.zero_items = zero_items\n self.action1 = action1\n self.action2 = action2\n self.initial_number = initial_number_true\n self.item = item\n self.items = items\n self.strofa_tpl = strofa_tpl\n self._hash = None\n self._repr = None\n \n def strofa(self, number):\n zero_items = self.zero_items\n item = self.item\n items = self.items\n \n if number == 0:\n i = zero_items\n action = self.action2\n j = self.initial_number\n else:\n i = number\n action = self.action1\n j = i - 1\n \n if i == 1:\n items1 = item\n j = zero_items\n else:\n items1 = items\n \n if j == 1:\n items2 = item\n else:\n items2 = items\n \n return self.strofa_tpl.substitute(\n i = i, \n j = j, \n action = action, \n items1 = items1, \n items2 = items2\n )\n \n def sing(self):\n with ProcPool() as proc_pool:\n strofa = self.strofa\n initial_number = self.initial_number\n args = range(initial_number, -1, -1)\n return \"\\n\\n\".join(proc_pool.map(strofa, args))\n \n def __copy__(self, *args, **kwargs):\n return self\n \n def __deepcopy__(self, *args, **kwargs):\n return self\n \n def __eq__(self, other, *args, **kwargs):\n if self is other:\n return True\n \n getmyattr = partial(getattr, self)\n getotherattr = partial(getattr, other)\n eq_attrs = self.eq_attrs\n \n for attr in eq_attrs:\n val = getmyattr(attr)\n \n try:\n val2 = getotherattr(attr)\n except Exception:\n return False\n \n if attr == \"strofa_tpl\":\n val_true = val.safe_substitute()\n val2_true = val.safe_substitute()\n else:\n val_true = val\n val2_true = val\n \n if val_true != val2_true:\n return False\n \n return True\n \n def __hash__(self, *args, **kwargs):\n _hash = self._hash\n \n if _hash is None:\n getmyattr = partial(getattr, self)\n attrs = self.hash_attrs\n hash_true = self._hash = hash(tuple(map(getmyattr, attrs)))\n else:\n hash_true = _hash\n \n return hash_true\n \n def __repr__(self, *args, **kwargs):\n _repr = self._repr\n \n if _repr is None:\n repr_attrs = self.repr_attrs\n getmyattr = partial(getattr, self)\n \n attrs = []\n \n for attr in repr_attrs:\n val = getmyattr(attr)\n \n if attr == \"strofa_tpl\":\n val_true = val.safe_substitute()\n else:\n val_true = val\n \n attrs.append(f\"{attr}={repr(val_true)}\")\n \n repr_true = self._repr = f\"{self.__class__.__name__}({', '.join(attrs)})\"\n else:\n repr_true = _repr\n \n return repr_true\n\ndef muchBeersOnTheWall(num):\n song = MuchItemsSomewhere(initial_number=num)\n \n return song.sing()\n\ndef balladOfProgrammer(num):\n \"\"\"\n Prints\n \"99 Subtle Bugs in Production\"\n or\n \"The Ballad of Programmer\"\n \"\"\"\n \n song = MuchItemsSomewhere(\n initial_number = num,\n items = \"subtle bugs\",\n item = \"subtle bug\",\n where = \"in Production\",\n action1 = \"Debug and catch, commit a patch\",\n action2 = \"Release the fixes, wait for some tickets\",\n zero_items = \"Zarro\",\n )\n\n return song.sing()\n\ndef main(num):\n print(f\"### {num} Bottles of Beers on the Wall ###\")\n print()\n print(muchBeersOnTheWall(num))\n print()\n print()\n print('### \"The Ballad of Programmer\", by Marco Sulla')\n print()\n print(balladOfProgrammer(num))\n\nif __name__ == \"__main__\":\n # Ok, argparse is **really** too much\n argv = sys.argv\n \n if len(argv) == 1:\n num = None\n elif len(argv) == 2:\n try:\n num = int(argv[1])\n except Exception:\n raise ValueError(\n f\"{__file__} parameter must be an integer, or can be omitted\"\n )\n else:\n raise RuntimeError(f\"{__file__} takes one parameter at max\")\n \n main(num)\n\n__all__ = (Song.__name__, MuchItemsSomewhere.__name__, muchBeersOnTheWall.__name__, balladOfProgrammer.__name__)\n"} {"title": "99 bottles of beer", "language": "Python 3", "task": "Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* Wikipedia 99 bottles of beer\n\n", "solution": "\"\"\"\n 99 Bottles of Beer on the Wall made functional\n \n Main function accepts a number of parameters, so you can specify a name of \n the drink, its container and other things. English only.\n\"\"\"\n\nfrom functools import partial\nfrom typing import Callable\n\n\ndef regular_plural(noun: str) -> str:\n \"\"\"English rule to get the plural form of a word\"\"\"\n if noun[-1] == \"s\":\n return noun + \"es\"\n \n return noun + \"s\"\n\n\ndef beer_song(\n *,\n location: str = 'on the wall',\n distribution: str = 'Take one down, pass it around',\n solution: str = 'Better go to the store to buy some more!',\n container: str = 'bottle',\n plurifier: Callable[[str], str] = regular_plural,\n liquid: str = \"beer\",\n initial_count: int = 99,\n) -> str:\n \"\"\"\n Return the lyrics of the beer song\n :param location: initial location of the drink\n :param distribution: specifies the process of its distribution\n :param solution: what happens when we run out of drinks\n :param container: bottle/barrel/flask or other containers\n :param plurifier: function converting a word to its plural form\n :param liquid: the name of the drink in the given container\n :param initial_count: how many containers available initially\n \"\"\"\n \n verse = partial(\n get_verse,\n initial_count = initial_count, \n location = location,\n distribution = distribution,\n solution = solution,\n container = container,\n plurifier = plurifier,\n liquid = liquid,\n )\n \n verses = map(verse, range(initial_count, -1, -1))\n return '\\n\\n'.join(verses)\n\n\ndef get_verse(\n count: int,\n *,\n initial_count: str,\n location: str,\n distribution: str,\n solution: str,\n container: str,\n plurifier: Callable[[str], str],\n liquid: str,\n) -> str:\n \"\"\"Returns the verse for the given amount of drinks\"\"\"\n \n asset = partial(\n get_asset,\n container = container,\n plurifier = plurifier,\n liquid = liquid,\n )\n \n current_asset = asset(count)\n next_number = count - 1 if count else initial_count\n next_asset = asset(next_number)\n action = distribution if count else solution\n \n inventory = partial(\n get_inventory,\n location = location,\n )\n \n return '\\n'.join((\n inventory(current_asset),\n current_asset,\n action,\n inventory(next_asset),\n ))\n\n\ndef get_inventory(\n asset: str,\n *,\n location: str,\n) -> str:\n \"\"\"\n Used to return the first or the fourth line of the verse\n\n >>> get_inventory(\"10 bottles of beer\", location=\"on the wall\")\n \"10 bottles of beer on the wall\"\n \"\"\"\n return ' '.join((asset, location))\n\n\ndef get_asset(\n count: int,\n *,\n container: str,\n plurifier: Callable[[str], str],\n liquid: str,\n) -> str:\n \"\"\"\n Quantified asset\n \n >>> get_asset(0, container=\"jar\", plurifier=regular_plural, liquid='milk')\n \"No more jars of milk\"\n \"\"\"\n \n containers = plurifier(container) if count != 1 else container\n spelled_out_quantity = str(count) if count else \"No more\" \n return ' '.join((spelled_out_quantity, containers, \"of\", liquid))\n\n\nif __name__ == '__main__':\n print(beer_song())\n"} {"title": "99 bottles of beer", "language": "Python 3.7+", "task": "Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* Wikipedia 99 bottles of beer\n\n", "solution": "'''99 Units of Disposable Asset'''\n\n\nfrom itertools import chain\n\n\n# main :: IO ()\ndef main():\n '''Modalised asset dispersal procedure.'''\n\n # localisation :: (String, String, String)\n localisation = (\n 'on the wall',\n 'Take one down, pass it around',\n 'Better go to the store to buy some more'\n )\n\n print(unlines(map(\n incantation(localisation),\n enumFromThenTo(99)(98)(0)\n )))\n\n\n# incantation :: (String, String, String) -> Int -> String\ndef incantation(localisation):\n '''Versification of asset disposal\n and inventory update.'''\n\n location, distribution, solution = localisation\n\n def inventory(n):\n return unwords([asset(n), location])\n return lambda n: solution if 0 == n else (\n unlines([\n inventory(n),\n asset(n),\n distribution,\n inventory(pred(n))\n ])\n )\n\n\n# asset :: Int -> String\ndef asset(n):\n '''Quantified asset.'''\n def suffix(n):\n return [] if 1 == n else 's'\n return unwords([\n str(n),\n concat(reversed(concat(cons(suffix(n))([\"elttob\"]))))\n ])\n\n\n# GENERIC -------------------------------------------------\n\n# concat :: [[a]] -> [a]\n# concat :: [String] -> String\ndef concat(xxs):\n '''The concatenation of all the elements in a list.'''\n xs = list(chain.from_iterable(xxs))\n unit = '' if isinstance(xs, str) else []\n return unit if not xs else (\n ''.join(xs) if isinstance(xs[0], str) else xs\n )\n\n\n# cons :: a -> [a] -> [a]\ndef cons(x):\n '''Construction of a list from x as head,\n and xs as tail.'''\n return lambda xs: [x] + xs if (\n isinstance(xs, list)\n ) else chain([x], xs)\n\n\n# enumFromThenTo :: Int -> Int -> Int -> [Int]\ndef enumFromThenTo(m):\n '''Integer values enumerated from m to n\n with a step defined by nxt-m.'''\n def go(nxt, n):\n d = nxt - m\n return list(range(m, d + n, d))\n return lambda nxt: lambda n: (\n go(nxt, n)\n )\n\n\n# pred :: Enum a => a -> a\ndef pred(x):\n '''The predecessor of a value. For numeric types, (- 1).'''\n return x - 1 if isinstance(x, int) else (\n chr(ord(x) - 1)\n )\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string derived by the intercalation\n of a list of strings with the newline character.'''\n return '\\n'.join(xs)\n\n\n# unwords :: [String] -> String\ndef unwords(xs):\n '''A space-separated string derived from\n a list of words.'''\n return ' '.join(xs)\n\n\nif __name__ == '__main__':\n main()"} {"title": "9 billion names of God the integer", "language": "Python", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \"name\":\n:The integer 1 has 1 name \"1\".\n:The integer 2 has 2 names \"1+1\", and \"2\".\n:The integer 3 has 3 names \"1+1+1\", \"2+1\", and \"3\".\n:The integer 4 has 5 names \"1+1+1+1\", \"2+1+1\", \"2+2\", \"3+1\", \"4\".\n:The integer 5 has 7 names \"1+1+1+1+1\", \"2+1+1+1\", \"2+2+1\", \"3+1+1\", \"3+2\", \"4+1\", \"5\".\n\n\n;Task\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n\nWhere row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.\n\nA function G(n) should return the sum of the n-th row. \n\nDemonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). \n\nOptionally note that the sum of the n-th row P(n) is the integer partition function. \n\nDemonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot P(n) against n for n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "cache = [[1]]\ndef cumu(n):\n for l in range(len(cache), n+1):\n r = [0]\n for x in range(1, l+1):\n r.append(r[-1] + cache[l-x][min(x, l-x)])\n cache.append(r)\n return cache[n]\n\ndef row(n):\n r = cumu(n)\n return [r[i+1] - r[i] for i in range(n)]\n\nprint \"rows:\"\nfor x in range(1, 11): print \"%2d:\"%x, row(x)\n\n\nprint \"\\nsums:\"\nfor x in [23, 123, 1234, 12345]: print x, cumu(x)[-1]"} {"title": "9 billion names of God the integer", "language": "Python from C", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \"name\":\n:The integer 1 has 1 name \"1\".\n:The integer 2 has 2 names \"1+1\", and \"2\".\n:The integer 3 has 3 names \"1+1+1\", \"2+1\", and \"3\".\n:The integer 4 has 5 names \"1+1+1+1\", \"2+1+1\", \"2+2\", \"3+1\", \"4\".\n:The integer 5 has 7 names \"1+1+1+1+1\", \"2+1+1+1\", \"2+2+1\", \"3+1+1\", \"3+2\", \"4+1\", \"5\".\n\n\n;Task\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n\nWhere row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.\n\nA function G(n) should return the sum of the n-th row. \n\nDemonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). \n\nOptionally note that the sum of the n-th row P(n) is the integer partition function. \n\nDemonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot P(n) against n for n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "def partitions(n):\n partitions.p.append(0)\n\n for k in xrange(1, n + 1):\n d = n - k * (3 * k - 1) // 2\n if d < 0:\n break\n\n if k & 1:\n partitions.p[n] += partitions.p[d]\n else:\n partitions.p[n] -= partitions.p[d]\n\n d -= k\n if d < 0:\n break\n\n if k & 1:\n partitions.p[n] += partitions.p[d]\n else:\n partitions.p[n] -= partitions.p[d]\n\n return partitions.p[-1]\n\npartitions.p = [1]\n\ndef main():\n ns = set([23, 123, 1234, 12345])\n max_ns = max(ns)\n\n for i in xrange(1, max_ns + 1):\n if i > max_ns:\n break\n p = partitions(i)\n if i in ns:\n print \"%6d: %s\" % (i, p)\n\nmain()"} {"title": "A+B", "language": "Python", "task": "'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n;Task:\nGiven two integers, '''A''' and '''B'''. \n\nTheir sum needs to be calculated.\n\n\n;Input data:\nTwo integers are written in the input stream, separated by space(s):\n: (-1000 \\le A,B \\le +1000)\n\n\n;Output data:\nThe required output is one integer: the sum of '''A''' and '''B'''.\n\n\n;Example:\n::{|class=\"standard\"\n ! input \n ! output \n |-\n | 2 2 \n | 4 \n |-\n | 3 2 \n | 5 \n |}\n\n", "solution": "a = int(input(\"First number: \"))\nb = int(input(\"Second number: \"))\nprint(\"Result:\", a+b)"} {"title": "ABC problem", "language": "Python", "task": "You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "'''\nNote that this code is broken, e.g., it won't work when \nblocks = [(\"A\", \"B\"), (\"A\",\"C\")] and the word is \"AB\", where the answer\nshould be True, but the code returns False.\n'''\nblocks = [(\"B\", \"O\"),\n (\"X\", \"K\"),\n (\"D\", \"Q\"),\n (\"C\", \"P\"),\n (\"N\", \"A\"),\n (\"G\", \"T\"),\n (\"R\", \"E\"),\n (\"T\", \"G\"),\n (\"Q\", \"D\"),\n (\"F\", \"S\"),\n (\"J\", \"W\"),\n (\"H\", \"U\"),\n (\"V\", \"I\"),\n (\"A\", \"N\"),\n (\"O\", \"B\"),\n (\"E\", \"R\"),\n (\"F\", \"S\"),\n (\"L\", \"Y\"),\n (\"P\", \"C\"),\n (\"Z\", \"M\")]\n\n\ndef can_make_word(word, block_collection=blocks):\n \"\"\"\n Return True if `word` can be made from the blocks in `block_collection`.\n\n >>> can_make_word(\"\")\n False\n >>> can_make_word(\"a\")\n True\n >>> can_make_word(\"bark\")\n True\n >>> can_make_word(\"book\")\n False\n >>> can_make_word(\"treat\")\n True\n >>> can_make_word(\"common\")\n False\n >>> can_make_word(\"squad\")\n True\n >>> can_make_word(\"coNFused\")\n True\n \"\"\"\n if not word:\n return False\n\n blocks_remaining = block_collection[:]\n for char in word.upper():\n for block in blocks_remaining:\n if char in block:\n blocks_remaining.remove(block)\n break\n else:\n return False\n return True\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n print(\", \".join(\"'%s': %s\" % (w, can_make_word(w)) for w in\n [\"\", \"a\", \"baRk\", \"booK\", \"treat\", \n \"COMMON\", \"squad\", \"Confused\"]))\n"} {"title": "ASCII art diagram converter", "language": "Python", "task": "Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:\nhttp://www.ietf.org/rfc/rfc1035.txt\n\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ID |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | QDCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ANCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | NSCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ARCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\nWhere (every column of the table is 1 bit):\n\n ID is 16 bits\n QR = Query (0) or Response (1)\n Opcode = Four bits defining kind of query:\n 0: a standard query (QUERY)\n 1: an inverse query (IQUERY)\n 2: a server status request (STATUS)\n 3-15: reserved for future use\n AA = Authoritative Answer bit\n TC = Truncation bit\n RD = Recursion Desired bit\n RA = Recursion Available bit\n Z = Reserved\n RCODE = Response code\n QC = Question Count\n ANC = Answer Count\n AUC = Authority Count\n ADC = Additional Count\n\nWrite a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.\n\nIf your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.\n\nSuch \"Header\" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars \"+--+\". The code should perform a little of validation of the input string, but for brevity a full validation is not required.\n\nBonus: perform a thoroughly validation of the input string.\n\n", "solution": "\"\"\"\nhttp://rosettacode.org/wiki/ASCII_art_diagram_converter\n\nPython example based off Go example:\n\nhttp://rosettacode.org/wiki/ASCII_art_diagram_converter#Go\n\n\"\"\"\n\ndef validate(diagram):\n\n # trim empty lines\n \n rawlines = diagram.splitlines()\n lines = []\n for line in rawlines:\n if line != '':\n lines.append(line)\n \n # validate non-empty lines\n \n if len(lines) == 0:\n print('diagram has no non-empty lines!')\n return None\n \n width = len(lines[0])\n cols = (width - 1) // 3\n \n if cols not in [8, 16, 32, 64]: \n print('number of columns should be 8, 16, 32 or 64')\n return None\n \n if len(lines)%2 == 0:\n print('number of non-empty lines should be odd')\n return None\n \n if lines[0] != (('+--' * cols)+'+'):\n print('incorrect header line')\n return None\n\n for i in range(len(lines)):\n line=lines[i]\n if i == 0:\n continue\n elif i%2 == 0:\n if line != lines[0]:\n print('incorrect separator line')\n return None\n elif len(line) != width:\n print('inconsistent line widths')\n return None\n elif line[0] != '|' or line[width-1] != '|':\n print(\"non-separator lines must begin and end with '|'\") \n return None\n \n return lines\n\n\"\"\"\n\nresults is list of lists like:\n\n[[name, bits, start, end],...\n\n\"\"\"\n\ndef decode(lines):\n print(\"Name Bits Start End\")\n print(\"======= ==== ===== ===\")\n \n startbit = 0\n \n results = []\n \n for line in lines:\n infield=False\n for c in line:\n if not infield and c == '|':\n infield = True\n spaces = 0\n name = ''\n elif infield:\n if c == ' ':\n spaces += 1\n elif c != '|':\n name += c\n else:\n bits = (spaces + len(name) + 1) // 3\n endbit = startbit + bits - 1\n print('{0:7} {1:2d} {2:2d} {3:2d}'.format(name, bits, startbit, endbit))\n reslist = [name, bits, startbit, endbit]\n results.append(reslist)\n spaces = 0\n name = ''\n startbit += bits\n \n return results\n \ndef unpack(results, hex):\n print(\"\\nTest string in hex:\")\n print(hex)\n print(\"\\nTest string in binary:\")\n bin = f'{int(hex, 16):0>{4*len(hex)}b}'\n print(bin)\n print(\"\\nUnpacked:\\n\")\n print(\"Name Size Bit pattern\")\n print(\"======= ==== ================\")\n for r in results:\n name = r[0]\n size = r[1]\n startbit = r[2]\n endbit = r[3]\n bitpattern = bin[startbit:endbit+1]\n print('{0:7} {1:2d} {2:16}'.format(name, size, bitpattern))\n\n\ndiagram = \"\"\"\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| ID |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| QDCOUNT |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| ANCOUNT |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| NSCOUNT |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| ARCOUNT |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\n\"\"\"\n\nlines = validate(diagram)\n\nif lines == None:\n print(\"No lines returned\")\nelse:\n print(\" \")\n print(\"Diagram after trimming whitespace and removal of blank lines:\")\n print(\" \")\n for line in lines:\n print(line)\n \n print(\" \")\n print(\"Decoded:\")\n print(\" \")\n\n results = decode(lines) \n \n # test string\n \n hex = \"78477bbf5496e12e1bf169a4\" \n \n unpack(results, hex)\n"} {"title": "AVL tree", "language": "Python", "task": "{{wikipedia|AVL tree}}\n\n\n\nIn computer science, an '''AVL tree''' is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log ''n'') time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.\n\nAVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log ''n'') time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor m-balanced; that is, sibling nodes can have hugely differing numbers of descendants.\n\n\n;Task:\nImplement an AVL tree in the language of choice, and provide at least basic operations.\n\n;Related task\n[[Red_black_tree_sort]]\n\n", "solution": "# Module: calculus.py\n\nimport enum\n\nclass entry_not_found(Exception):\n \"\"\"Raised when an entry is not found in a collection\"\"\"\n pass\n\nclass entry_already_exists(Exception):\n \"\"\"Raised when an entry already exists in a collection\"\"\"\n pass\n\nclass state(enum.Enum):\n header = 0\n left_high = 1\n right_high = 2\n balanced = 3\n\nclass direction(enum.Enum):\n from_left = 0\n from_right = 1\n\nfrom abc import ABC, abstractmethod\n\nclass comparer(ABC):\n\n @abstractmethod\n def compare(self,t):\n pass\n\nclass node(comparer):\n \n def __init__(self):\n self.parent = None\n self.left = self\n self.right = self\n self.balance = state.header\n\n def compare(self,t):\n if self.key < t:\n return -1\n elif t < self.key:\n return 1\n else:\n return 0\n\n def is_header(self):\n return self.balance == state.header\n\n def length(self):\n if self != None:\n if self.left != None:\n left = self.left.length()\n else:\n left = 0\n if self.right != None: \n right = self.right.length()\n else:\n right = 0\n \n return left + right + 1\n else:\n return 0\n \n def rotate_left(self):\n _parent = self.parent\n x = self.right\n self.parent = x\n x.parent = _parent\n if x.left is not None:\n x.left.parent = self\n self.right = x.left\n x.left = self\n return x\n \n \n def rotate_right(self):\n _parent = self.parent\n x = self.left\n self.parent = x\n x.parent = _parent;\n if x.right is not None:\n x.right.parent = self\n self.left = x.right\n x.right = self\n return x\n\n def balance_left(self):\n \n _left = self.left\n\n if _left is None:\n return self;\n \n if _left.balance == state.left_high:\n self.balance = state.balanced\n _left.balance = state.balanced\n self = self.rotate_right()\n elif _left.balance == state.right_high: \n subright = _left.right\n if subright.balance == state.balanced:\n self.balance = state.balanced\n _left.balance = state.balanced\n elif subright.balance == state.right_high:\n self.balance = state.balanced\n _left.balance = state.left_high\n elif subright.balance == left_high:\n root.balance = state.right_high\n _left.balance = state.balanced\n subright.balance = state.balanced\n _left = _left.rotate_left()\n self.left = _left\n self = self.rotate_right()\n elif _left.balance == state.balanced:\n self.balance = state.left_high\n _left.balance = state.right_high\n self = self.rotate_right()\n return self;\n \n def balance_right(self):\n\n _right = self.right\n\n if _right is None:\n return self;\n \n if _right.balance == state.right_high:\n self.balance = state.balanced\n _right.balance = state.balanced\n self = self.rotate_left()\n elif _right.balance == state.left_high:\n subleft = _right.left;\n if subleft.balance == state.balanced:\n self.balance = state.balanced\n _right.balance = state.balanced\n elif subleft.balance == state.left_high:\n self.balance = state.balanced\n _right.balance = state.right_high\n elif subleft.balance == state.right_high:\n self.balance = state.left_high\n _right.balance = state.balanced\n subleft.balance = state.balanced\n _right = _right.rotate_right()\n self.right = _right\n self = self.rotate_left()\n elif _right.balance == state.balanced:\n self.balance = state.right_high\n _right.balance = state.left_high\n self = self.rotate_left()\n return self\n\n\n def balance_tree(self, direct):\n taller = True\n while taller:\n _parent = self.parent;\n if _parent.left == self:\n next_from = direction.from_left\n else:\n next_from = direction.from_right;\n\n if direct == direction.from_left:\n if self.balance == state.left_high:\n if _parent.is_header():\n _parent.parent = _parent.parent.balance_left()\n elif _parent.left == self:\n _parent.left = _parent.left.balance_left()\n else:\n _parent.right = _parent.right.balance_left()\n taller = False\n \n elif self.balance == state.balanced:\n self.balance = state.left_high\n taller = True\n \n elif self.balance == state.right_high:\n self.balance = state.balanced\n taller = False\n else:\n if self.balance == state.left_high:\n self.balance = state.balanced\n taller = False\n \n elif self.balance == state.balanced:\n self.balance = state.right_high\n taller = True\n \n elif self.balance == state.right_high:\n if _parent.is_header():\n _parent.parent = _parent.parent.balance_right()\n elif _parent.left == self:\n _parent.left = _parent.left.balance_right()\n else:\n _parent.right = _parent.right.balance_right()\n taller = False\n \n if taller:\n if _parent.is_header():\n taller = False\n else:\n self = _parent\n direct = next_from\n\n def balance_tree_remove(self, _from):\n \n if self.is_header():\n return;\n\n shorter = True;\n\n while shorter:\n _parent = self.parent;\n if _parent.left == self:\n next_from = direction.from_left\n else:\n next_from = direction.from_right\n\n if _from == direction.from_left:\n if self.balance == state.left_high:\n shorter = True\n \n elif self.balance == state.balanced:\n self.balance = state.right_high;\n shorter = False\n \n elif self.balance == state.right_high:\n if self.right is not None:\n if self.right.balance == state.balanced:\n shorter = False\n else:\n shorter = True\n else:\n shorter = False;\n\n if _parent.is_header():\n _parent.parent = _parent.parent.balance_right()\n elif _parent.left == self:\n _parent.left = _parent.left.balance_right();\n else:\n _parent.right = _parent.right.balance_right()\n \n else:\n if self.balance == state.right_high:\n self.balance = state.balanced\n shorter = True\n \n elif self.balance == state.balanced:\n self.balance = state.left_high\n shorter = False\n \n elif self.balance == state.left_high:\n\n if self.left is not None:\n if self.left.balance == state.balanced:\n shorter = False\n else:\n shorter = True\n else:\n short = False;\n\n if _parent.is_header():\n _parent.parent = _parent.parent.balance_left();\n elif _parent.left == self:\n _parent.left = _parent.left.balance_left();\n else:\n _parent.right = _parent.right.balance_left();\n \n if shorter:\n if _parent.is_header():\n shorter = False\n else: \n _from = next_from\n self = _parent\n\n def previous(self):\n if self.is_header():\n return self.right\n\n if self.left is not None:\n y = self.left\n while y.right is not None:\n y = y.right\n return y\n \n else: \n y = self.parent;\n if y.is_header():\n return y\n\n x = self\n while x == y.left:\n x = y\n y = y.parent\n\n return y\n \n def next(self):\n if self.is_header():\n return self.left\n\n if self.right is not None:\n y = self.right\n while y.left is not None:\n y = y.left\n return y;\n \n else:\n y = self.parent\n if y.is_header():\n return y\n\n x = self; \n while x == y.right:\n x = y\n y = y.parent;\n \n return y\n\n def swap_nodes(a, b):\n \n if b == a.left:\n if b.left is not None:\n b.left.parent = a\n\n if b.right is not None:\n b.right.parent = a\n\n if a.right is not None:\n a.right.parent = b\n\n if not a.parent.is_header():\n if a.parent.left == a:\n a.parent.left = b\n else:\n a.parent.right = b;\n else:\n a.parent.parent = b\n\n b.parent = a.parent\n a.parent = b\n\n a.left = b.left\n b.left = a\n\n temp = a.right\n a.right = b.right\n b.right = temp\n elif b == a.right:\n if b.right is not None:\n b.right.parent = a\n \n if b.left is not None:\n b.left.parent = a\n\n if a.left is not None:\n a.left.parent = b\n\n if not a.parent.is_header(): \n if a.parent.left == a:\n a.parent.left = b\n else:\n a.parent.right = b\n else:\n a.parent.parent = b\n\n b.parent = a.parent\n a.parent = b\n\n a.right = b.right\n b.right = a\n\n temp = a.left\n a.left = b.left\n b.left = temp\n elif a == b.left:\n if a.left is not None:\n a.left.parent = b\n \n if a.right is not None:\n a.right.parent = b\n\n if b.right is not None:\n b.right.parent = a\n\n if not parent.is_header(): \n if b.parent.left == b:\n b.parent.left = a\n else:\n b.parent.right = a\n else:\n b.parent.parent = a\n\n a.parent = b.parent\n b.parent = a\n\n b.left = a.left\n a.left = b\n\n temp = a.right\n a.right = b.right\n b.right = temp\n elif a == b.right:\n if a.right is not None:\n a.right.parent = b\n if a.left is not None:\n a.left.parent = b\n\n if b.left is not None:\n b.left.parent = a\n\n if not b.parent.is_header():\n if b.parent.left == b:\n b.parent.left = a\n else:\n b.parent.right = a\n else:\n b.parent.parent = a\n\n a.parent = b.parent\n b.parent = a\n\n b.right = a.right\n a.right = b\n\n temp = a.left\n a.left = b.left\n b.left = temp\n else:\n if a.parent == b.parent:\n temp = a.parent.left\n a.parent.left = a.parent.right\n a.parent.right = temp\n else:\n if not a.parent.is_header():\n if a.parent.left == a:\n a.parent.left = b\n else:\n a.parent.right = b\n else:\n a.parent.parent = b\n\n if not b.parent.is_header():\n if b.parent.left == b:\n b.parent.left = a\n else:\n b.parent.right = a\n else:\n b.parent.parent = a\n \n if b.left is not None:\n b.left.parent = a\n \n if b.right is not None:\n b.right.parent = a\n\n if a.left is not None:\n a.left.parent = b\n \n if a.right is not None:\n a.right.parent = b\n\n temp1 = a.left\n a.left = b.left\n b.left = temp1\n\n temp2 = a.right\n a.right = b.right\n b.right = temp2\n\n temp3 = a.parent\n a.parent = b.parent\n b.parent = temp3\n \n balance = a.balance\n a.balance = b.balance\n b.balance = balance\n \nclass parent_node(node):\n\n def __init__(self, parent):\n self.parent = parent\n self.left = None\n self.right = None\n self.balance = state.balanced\n\nclass set_node(node):\n\n def __init__(self, parent, key):\n self.parent = parent\n self.left = None\n self.right = None\n self.balance = state.balanced\n self.key = key\n\nclass ordered_set:\n \n def __init__(self):\n self.header = node()\n\n def __iter__(self):\n self.node = self.header\n return self\n \n def __next__(self):\n self.node = self.node.next()\n if self.node.is_header():\n raise StopIteration\n return self.node.key\n\n def __delitem__(self, key):\n self.remove(key)\n\n def __lt__(self, other):\n first1 = self.header.left\n last1 = self.header\n first2 = other.header.left\n last2 = other.header\n\n while (first1 != last1) and (first2 != last2):\n l = first1.key < first2.key\n if not l: \n first1 = first1.next();\n first2 = first2.next();\n else:\n return True;\n \n a = self.__len__()\n b = other.__len__()\n return a < b\n\n def __hash__(self):\n h = 0\n for i in self:\n h = h + i.__hash__()\n return h \n\n def __eq__(self, other):\n if self < other:\n return False\n if other < self:\n return False\n return True\n \n def __ne__(self, other):\n if self < other:\n return True\n if other < self:\n return True\n return False\n\n def __len__(self):\n return self.header.parent.length()\n\n def __getitem__(self, key):\n return self.contains(key)\n\n def __str__(self):\n l = self.header.right\n s = \"{\"\n i = self.header.left\n h = self.header\n while i != h:\n s = s + i.key.__str__()\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \"}\"\n return s\n\n def __or__(self, other):\n r = ordered_set()\n \n first1 = self.header.left\n last1 = self.header\n first2 = other.header.left\n last2 = other.header\n \n while first1 != last1 and first2 != last2:\n les = first1.key < first2.key\n graater = first2.key < first1.key\n\n if les:\n r.add(first1.key)\n first1 = first1.next()\n elif graater:\n r.add(first2.key)\n first2 = first2.next()\n else:\n r.add(first1.key)\n first1 = first1.next()\n first2 = first2.next()\n \n while first1 != last1:\n r.add(first1.key)\n first1 = first1.next()\n \n while first2 != last2:\n r.add(first2.key)\n first2 = first2.next()\n\n return r\n\n def __and__(self, other):\n r = ordered_set()\n \n first1 = self.header.left\n last1 = self.header\n first2 = other.header.left\n last2 = other.header\n \n while first1 != last1 and first2 != last2:\n les = first1.key < first2.key\n graater = first2.key < first1.key\n\n if les:\n first1 = first1.next()\n elif graater:\n first2 = first2.next()\n else:\n r.add(first1.key)\n first1 = first1.next()\n first2 = first2.next()\n \n return r\n\n def __xor__(self, other):\n r = ordered_set()\n \n first1 = self.header.left\n last1 = self.header\n first2 = other.header.left\n last2 = other.header\n \n while first1 != last1 and first2 != last2:\n les = first1.key < first2.key\n graater = first2.key < first1.key\n\n if les:\n r.add(first1.key)\n first1 = first1.next()\n elif graater:\n r.add(first2.key)\n first2 = first2.next()\n else:\n first1 = first1.next()\n first2 = first2.next()\n \n while first1 != last1:\n r.add(first1.key)\n first1 = first1.next()\n \n while first2 != last2:\n r.add(first2.key)\n first2 = first2.next()\n\n return r\n\n\n def __sub__(self, other):\n r = ordered_set()\n \n first1 = self.header.left\n last1 = self.header\n first2 = other.header.left\n last2 = other.header\n \n while first1 != last1 and first2 != last2:\n les = first1.key < first2.key\n graater = first2.key < first1.key\n\n if les:\n r.add(first1.key)\n first1 = first1.next()\n elif graater:\n r.add(first2.key)\n first2 = first2.next()\n else:\n first1 = first1.next()\n first2 = first2.next()\n \n while first1 != last1:\n r.add(first1.key)\n first1 = first1.next()\n\n return r\n \n def __lshift__(self, data):\n self.add(data)\n return self\n\n def __rshift__(self, data):\n self.remove(data)\n return self\n\n def is_subset(self, other):\n first1 = self.header.left\n last1 = self.header\n first2 = other.header.left\n last2 = other.header\n\n is_subet = True\n\n while first1 != last1 and first2 != last2:\n if first1.key < first2.key:\n is_subset = False\n break\n elif first2.key < first1.key:\n first2 = first2.next()\n else:\n first1 = first1.next()\n first2 = first2.next()\n \n if is_subet:\n if first1 != last1:\n is_subet = False\n \n return is_subet\n\n def is_superset(self,other):\n return other.is_subset(self)\n \n def add(self, data):\n if self.header.parent is None:\n self.header.parent = set_node(self.header,data)\n self.header.left = self.header.parent\n self.header.right = self.header.parent\n else:\n \n root = self.header.parent\n\n while True:\n c = root.compare(data)\n if c >= 0:\n if root.left is not None:\n root = root.left\n else:\n new_node = set_node(root,data)\n root.left = new_node\n \n if self.header.left == root:\n self.header.left = new_node\n root.balance_tree(direction.from_left)\n return\n \n else:\n if root.right is not None:\n root = root.right\n else:\n new_node = set_node(root, data)\n root.right = new_node\n if self.header.right == root:\n self.header.right = new_node\n root.balance_tree(direction.from_right)\n return\n \n def remove(self,data):\n root = self.header.parent;\n\n while True:\n if root is None:\n raise entry_not_found(\"Entry not found in collection\")\n \n c = root.compare(data)\n\n if c < 0:\n root = root.left;\n\n elif c > 0:\n root = root.right;\n\n else:\n \n if root.left is not None:\n if root.right is not None: \n replace = root.left\n while replace.right is not None:\n replace = replace.right\n root.swap_nodes(replace)\n \n _parent = root.parent\n\n if _parent.left == root:\n _from = direction.from_left\n else:\n _from = direction.from_right\n\n if self.header.left == root:\n \n n = root.next();\n \n if n.is_header():\n self.header.left = self.header\n self.header.right = self.header\n else:\n self.header.left = n\n elif self.header.right == root: \n\n p = root.previous();\n\n if p.is_header():\n self.header.left = self.header\n self.header.right = self.header\n else:\n self.header.right = p\n\n if root.left is None:\n if _parent == self.header:\n self.header.parent = root.right\n elif _parent.left == root:\n _parent.left = root.right\n else:\n _parent.right = root.right\n\n if root.right is not None:\n root.right.parent = _parent\n \n else:\n if _parent == self.header:\n self.header.parent = root.left\n elif _parent.left == root:\n _parent.left = root.left\n else:\n _parent.right = root.left\n\n if root.left is not None:\n root.left.parent = _parent;\n\n\n _parent.balance_tree_remove(_from)\n return \n\n def contains(self,data):\n root = self.header.parent;\n\n while True:\n if root == None:\n return False\n\n c = root.compare(data);\n\n if c > 0:\n root = root.left;\n\n elif c < 0:\n root = root.right;\n\n else:\n \n return True \n\n \n def find(self,data):\n root = self.header.parent;\n\n while True:\n if root == None:\n raise entry_not_found(\"An entry is not found in a collection\")\n\n c = root.compare(data);\n\n if c > 0:\n root = root.left;\n\n elif c < 0:\n root = root.right;\n\n else:\n \n return root.key; \n \nclass key_value(comparer):\n\n def __init__(self, key, value):\n self.key = key\n self.value = value\n\n def compare(self,kv):\n if self.key < kv.key:\n return -1\n elif kv.key < self.key:\n return 1\n else:\n return 0\n\n def __lt__(self, other):\n return self.key < other.key\n\n def __str__(self):\n return '(' + self.key.__str__() + ',' + self.value.__str__() + ')'\n\n def __eq__(self, other):\n return self.key == other.key\n\n def __hash__(self):\n return hash(self.key)\n \n\nclass dictionary:\n\n def __init__(self):\n self.set = ordered_set()\n return None\n\n def __lt__(self, other):\n if self.keys() < other.keys():\n return true\n\n if other.keys() < self.keys():\n return false\n \n first1 = self.set.header.left\n last1 = self.set.header\n first2 = other.set.header.left\n last2 = other.set.header\n\n while (first1 != last1) and (first2 != last2):\n l = first1.key.value < first2.key.value\n if not l: \n first1 = first1.next();\n first2 = first2.next();\n else:\n return True;\n \n a = self.__len__()\n b = other.__len__()\n return a < b\n\n\n def add(self, key, value):\n try:\n self.set.remove(key_value(key,None))\n except entry_not_found:\n pass \n self.set.add(key_value(key,value))\n return\n\n def remove(self, key):\n self.set.remove(key_value(key,None))\n return\n\n def clear(self):\n self.set.header = node()\n\n def sort(self):\n \n sort_bag = bag()\n for e in self:\n sort_bag.add(e.value)\n keys_set = self.keys()\n self.clear()\n i = sort_bag.__iter__()\n i = sort_bag.__next__()\n try:\n for e in keys_set:\n self.add(e,i)\n i = sort_bag.__next__()\n except:\n return \n\n def keys(self):\n keys_set = ordered_set()\n for e in self:\n keys_set.add(e.key)\n return keys_set \n \n def __len__(self):\n return self.set.header.parent.length()\n\n def __str__(self):\n l = self.set.header.right;\n s = \"{\"\n i = self.set.header.left;\n h = self.set.header;\n while i != h:\n s = s + \"(\"\n s = s + i.key.key.__str__()\n s = s + \",\"\n s = s + i.key.value.__str__()\n s = s + \")\"\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \"}\"\n return s;\n\n def __iter__(self):\n \n self.set.node = self.set.header\n return self\n \n def __next__(self):\n self.set.node = self.set.node.next()\n if self.set.node.is_header():\n raise StopIteration\n return key_value(self.set.node.key.key,self.set.node.key.value)\n\n def __getitem__(self, key):\n kv = self.set.find(key_value(key,None))\n return kv.value\n\n def __setitem__(self, key, value):\n self.add(key,value)\n return\n\n def __delitem__(self, key):\n self.set.remove(key_value(key,None))\n\n\nclass array:\n\n def __init__(self):\n self.dictionary = dictionary()\n return None\n \n def __len__(self):\n return self.dictionary.__len__()\n\n def push(self, value):\n k = self.dictionary.set.header.right\n if k == self.dictionary.set.header:\n self.dictionary.add(0,value)\n else:\n self.dictionary.add(k.key.key+1,value)\n return\n\n def pop(self):\n if self.dictionary.set.header.parent != None:\n data = self.dictionary.set.header.right.key.value\n self.remove(self.dictionary.set.header.right.key.key)\n return data\n\n def add(self, key, value):\n try:\n self.dictionary.remove(key)\n except entry_not_found:\n pass\n self.dictionary.add(key,value) \n return\n\n def remove(self, key):\n self.dictionary.remove(key)\n return\n\n def sort(self):\n self.dictionary.sort()\n\n def clear(self):\n self.dictionary.header = node();\n \n\n def __iter__(self):\n self.dictionary.node = self.dictionary.set.header\n return self\n \n def __next__(self):\n self.dictionary.node = self.dictionary.node.next()\n if self.dictionary.node.is_header():\n raise StopIteration\n return self.dictionary.node.key.value\n\n def __getitem__(self, key):\n kv = self.dictionary.set.find(key_value(key,None))\n return kv.value\n\n def __setitem__(self, key, value):\n self.add(key,value)\n return\n\n def __delitem__(self, key):\n self.dictionary.remove(key)\n\n def __lshift__(self, data):\n self.push(data)\n return self\n\n def __lt__(self, other):\n return self.dictionary < other.dictionary\n \n def __str__(self):\n l = self.dictionary.set.header.right;\n s = \"{\"\n i = self.dictionary.set.header.left;\n h = self.dictionary.set.header;\n while i != h:\n s = s + i.key.value.__str__()\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \"}\"\n return s;\n \n\nclass bag:\n \n def __init__(self):\n self.header = node()\n \n def __iter__(self):\n self.node = self.header\n return self\n\n def __delitem__(self, key):\n self.remove(key)\n \n def __next__(self):\n self.node = self.node.next()\n if self.node.is_header():\n raise StopIteration\n return self.node.key\n\n def __str__(self):\n l = self.header.right;\n s = \"(\"\n i = self.header.left;\n h = self.header;\n while i != h:\n s = s + i.key.__str__()\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \")\"\n return s;\n\n def __len__(self):\n return self.header.parent.length()\n\n def __lshift__(self, data):\n self.add(data)\n return self\n\n def add(self, data):\n if self.header.parent is None:\n self.header.parent = set_node(self.header,data)\n self.header.left = self.header.parent\n self.header.right = self.header.parent\n else:\n \n root = self.header.parent\n\n while True:\n c = root.compare(data)\n if c >= 0:\n if root.left is not None:\n root = root.left\n else:\n new_node = set_node(root,data)\n root.left = new_node\n \n if self.header.left == root:\n self.header.left = new_node\n\n root.balance_tree(direction.from_left)\n return\n \n else:\n if root.right is not None:\n root = root.right\n else:\n new_node = set_node(root, data)\n root.right = new_node\n\n if self.header.right == root:\n self.header.right = new_node\n\n root.balance_tree(direction.from_right)\n return\n \n def remove_first(self,data):\n \n root = self.header.parent;\n\n while True:\n if root is None:\n return False;\n\n c = root.compare(data);\n\n if c > 0:\n root = root.left;\n\n elif c < 0:\n root = root.right;\n\n else:\n \n if root.left is not None:\n if root.right is not None: \n replace = root.left;\n while replace.right is not None:\n replace = replace.right;\n root.swap_nodes(replace);\n \n _parent = root.parent\n\n if _parent.left == root:\n _from = direction.from_left\n else:\n _from = direction.from_right\n\n if self.header.left == root:\n \n n = root.next();\n \n if n.is_header():\n self.header.left = self.header\n self.header.right = self.header\n else:\n self.header.left = n;\n elif self.header.right == root: \n\n p = root.previous();\n\n if p.is_header():\n self.header.left = self.header\n self.header.right = self.header\n else:\n self.header.right = p\n\n if root.left is None:\n if _parent == self.header:\n self.header.parent = root.right\n elif _parent.left == root:\n _parent.left = root.right\n else:\n _parent.right = root.right\n\n if root.right is not None:\n root.right.parent = _parent\n \n else:\n if _parent == self.header:\n self.header.parent = root.left\n elif _parent.left == root:\n _parent.left = root.left\n else:\n _parent.right = root.left\n\n if root.left is not None:\n root.left.parent = _parent;\n\n\n _parent.balance_tree_remove(_from)\n return True;\n\n def remove(self,data):\n success = self.remove_first(data)\n while success:\n success = self.remove_first(data)\n\n def remove_node(self, root):\n \n if root.left != None and root.right != None:\n replace = root.left\n while replace.right != None:\n replace = replace.right\n root.swap_nodes(replace)\n\n parent = root.parent;\n\n if parent.left == root:\n next_from = direction.from_left\n else:\n next_from = direction.from_right\n\n if self.header.left == root:\n n = root.next()\n\n if n.is_header():\n self.header.left = self.header;\n self.header.right = self.header\n else:\n self.header.left = n\n elif self.header.right == root:\n p = root.previous()\n\n if p.is_header(): \n root.header.left = root.header\n root.header.right = header\n else:\n self.header.right = p\n\n if root.left == None:\n if parent == self.header:\n self.header.parent = root.right\n elif parent.left == root:\n parent.left = root.right\n else:\n parent.right = root.right\n\n if root.right != None:\n root.right.parent = parent\n else:\n if parent == self.header:\n self.header.parent = root.left\n elif parent.left == root:\n parent.left = root.left\n else:\n parent.right = root.left\n\n if root.left != None:\n root.left.parent = parent;\n\n parent.balance_tree_remove(next_from)\n \n def remove_at(self, data, ophset):\n \n p = self.search(data);\n\n if p == None:\n return\n else:\n lower = p\n after = after(data)\n \n s = 0\n while True:\n if ophset == s:\n remove_node(lower);\n return;\n lower = lower.next_node()\n if after == lower:\n break\n s = s+1\n \n return\n\n def search(self, key):\n s = before(key)\n s.next()\n if s.is_header():\n return None\n c = s.compare(s.key)\n if c != 0:\n return None\n return s\n \n \n def before(self, data):\n y = self.header;\n x = self.header.parent;\n\n while x != None:\n if x.compare(data) >= 0:\n x = x.left;\n else:\n y = x;\n x = x.right;\n return y\n \n def after(self, data):\n y = self.header;\n x = self.header.parent;\n\n while x != None:\n if x.compare(data) > 0:\n y = x\n x = x.left\n else:\n x = x.right\n\n return y;\n \n \n def find(self,data):\n root = self.header.parent;\n\n results = array()\n \n while True:\n if root is None:\n break;\n\n p = self.before(data)\n p = p.next()\n if not p.is_header():\n i = p\n l = self.after(data)\n while i != l:\n results.push(i.key)\n i = i.next()\n \n return results\n else:\n break;\n \n return results\n \nclass bag_dictionary:\n\n def __init__(self):\n self.bag = bag()\n return None\n\n def add(self, key, value):\n self.bag.add(key_value(key,value))\n return\n\n def remove(self, key):\n self.bag.remove(key_value(key,None))\n return\n\n def remove_at(self, key, index):\n self.bag.remove_at(key_value(key,None), index)\n return\n\n def clear(self):\n self.bag.header = node()\n\n def __len__(self):\n return self.bag.header.parent.length()\n\n def __str__(self):\n l = self.bag.header.right;\n s = \"{\"\n i = self.bag.header.left;\n h = self.bag.header;\n while i != h:\n s = s + \"(\"\n s = s + i.key.key.__str__()\n s = s + \",\"\n s = s + i.key.value.__str__()\n s = s + \")\"\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \"}\"\n return s;\n\n def __iter__(self):\n \n self.bag.node = self.bag.header\n return self\n \n def __next__(self):\n self.bag.node = self.bag.node.next()\n if self.bag.node.is_header():\n raise StopIteration\n return key_value(self.bag.node.key.key,self.bag.node.key.value)\n\n def __getitem__(self, key):\n kv_array = self.bag.find(key_value(key,None))\n return kv_array\n\n def __setitem__(self, key, value):\n self.add(key,value)\n return\n\n def __delitem__(self, key):\n self.bag.remove(key_value(key,None))\n\nclass unordered_set:\n\n def __init__(self):\n self.bag_dictionary = bag_dictionary()\n\n def __len__(self):\n return self.bag_dictionary.__len__()\n\n def __hash__(self):\n h = 0\n for i in self:\n h = h + i.__hash__()\n return h \n\n def __eq__(self, other):\n for t in self:\n if not other.contains(t):\n return False\n for u in other:\n if self.contains(u):\n return False\n return true;\n\n def __ne__(self, other):\n return not self == other\n \n def __or__(self, other):\n r = unordered_set()\n \n for t in self:\n r.add(t);\n \n for u in other:\n if not self.contains(u):\n r.add(u);\n\n return r\n\n def __and__(self, other):\n r = unordered_set()\n \n for t in self:\n if other.contains(t):\n r.add(t)\n \n for u in other:\n if self.contains(u) and not r.contains(u):\n r.add(u);\n \n return r\n\n def __xor__(self, other):\n r = unordered_set()\n \n for t in self:\n if not other.contains(t):\n r.add(t)\n \n for u in other:\n if not self.contains(u) and not r.contains(u):\n r.add(u)\n \n return r\n\n\n def __sub__(self, other):\n r = ordered_set()\n \n for t in self:\n if not other.contains(t):\n r.add(t);\n \n return r\n \n def __lshift__(self, data):\n self.add(data)\n return self\n\n def __rshift__(self, data):\n self.remove(data)\n return self\n\n def __getitem__(self, key):\n return self.contains(key)\n\n def is_subset(self, other):\n\n is_subet = True\n\n for t in self:\n if not other.contains(t):\n subset = False\n break\n \n return is_subet\n\n def is_superset(self,other):\n return other.is_subset(self)\n\n\n def add(self, value):\n if not self.contains(value):\n self.bag_dictionary.add(hash(value),value)\n else:\n raise entry_already_exists(\"Entry already exists in the unordered set\")\n\n def contains(self, data):\n if self.bag_dictionary.bag.header.parent == None:\n return False;\n else:\n index = hash(data);\n\n _search = self.bag_dictionary.bag.header.parent;\n\n search_index = _search.key.key;\n\n if index < search_index:\n _search = _search.left\n\n elif index > search_index:\n _search = _search.right\n\n if _search == None:\n return False\n\n while _search != None:\n search_index = _search.key.key;\n\n if index < search_index:\n _search = _search.left\n\n elif index > search_index:\n _search = _search.right\n\n else:\n break\n\n if _search == None:\n return False\n\n return self.contains_node(data, _search)\n \n def contains_node(self,data,_node):\n \n previous = _node.previous()\n save = _node\n\n while not previous.is_header() and previous.key.key == _node.key.key:\n save = previous;\n previous = previous.previous()\n \n c = _node.key.value\n _node = save\n if c == data:\n return True\n\n next = _node.next()\n while not next.is_header() and next.key.key == _node.key.key:\n _node = next\n c = _node.key.value\n if c == data:\n return True;\n next = _node.next()\n \n return False;\n \n def find(self,data,_node):\n \n previous = _node.previous()\n save = _node\n\n while not previous.is_header() and previous.key.key == _node.key.key:\n save = previous;\n previous = previous.previous();\n \n _node = save;\n c = _node.key.value\n if c == data:\n return _node\n\n next = _node.next()\n while not next.is_header() and next.key.key == _node.key.key:\n _node = next\n c = _node.data.value\n if c == data:\n return _node\n next = _node.next()\n \n return None\n \n def search(self, data):\n if self.bag_dictionary.bag.header.parent == None:\n return None\n else:\n index = hash(data)\n\n _search = self.bag_dictionary.bag.header.parent\n\n c = _search.key.key\n\n if index < c:\n _search = _search.left;\n\n elif index > c:\n _search = _search.right;\n\n while _search != None:\n\n if index != c:\n break\n \n c = _search.key.key\n\n if index < c:\n _search = _search.left;\n\n elif index > c:\n _search = _search.right;\n\n else:\n break\n\n if _search == None:\n return None\n\n return self.find(data, _search)\n\n def remove(self,data):\n found = self.search(data);\n if found != None:\n self.bag_dictionary.bag.remove_node(found);\n else:\n raise entry_not_found(\"Entry not found in the unordered set\")\n \n def clear(self):\n self.bag_dictionary.bag.header = node()\n\n def __str__(self):\n l = self.bag_dictionary.bag.header.right;\n s = \"{\"\n i = self.bag_dictionary.bag.header.left;\n h = self.bag_dictionary.bag.header;\n while i != h:\n s = s + i.key.value.__str__()\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \"}\"\n return s;\n\n def __iter__(self):\n \n self.bag_dictionary.bag.node = self.bag_dictionary.bag.header\n return self\n \n def __next__(self):\n self.bag_dictionary.bag.node = self.bag_dictionary.bag.node.next()\n if self.bag_dictionary.bag.node.is_header():\n raise StopIteration\n return self.bag_dictionary.bag.node.key.value\n\n\nclass map:\n\n def __init__(self):\n self.set = unordered_set()\n return None\n\n def __len__(self):\n return self.set.__len__()\n\n def add(self, key, value):\n try:\n self.set.remove(key_value(key,None))\n except entry_not_found:\n pass \n self.set.add(key_value(key,value))\n return\n\n def remove(self, key):\n self.set.remove(key_value(key,None))\n return\n\n def clear(self):\n self.set.clear()\n\n def __str__(self):\n l = self.set.bag_dictionary.bag.header.right;\n s = \"{\"\n i = self.set.bag_dictionary.bag.header.left;\n h = self.set.bag_dictionary.bag.header;\n while i != h:\n s = s + \"(\"\n s = s + i.key.value.key.__str__()\n s = s + \",\"\n s = s + i.key.value.value.__str__()\n s = s + \")\"\n if i != l:\n s = s + \",\"\n i = i.next()\n\n s = s + \"}\"\n return s;\n\n def __iter__(self):\n \n self.set.node = self.set.bag_dictionary.bag.header\n return self\n \n def __next__(self):\n self.set.node = self.set.node.next()\n if self.set.node.is_header():\n raise StopIteration\n return key_value(self.set.node.key.key,self.set.node.key.value)\n\n def __getitem__(self, key):\n kv = self.set.find(key_value(key,None))\n return kv.value\n\n def __setitem__(self, key, value):\n self.add(key,value)\n return\n\n def __delitem__(self, key):\n self.remove(key)\n"} {"title": "Abbreviations, automatic", "language": "Python from Kotlin", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an\neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain (as words are added, changed, and/or deleted) if\nthe minimum abbreviation length of that list could be automatically (programmatically) determined.\n\n\nFor this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list).\n\nSunday Monday Tuesday Wednesday Thursday Friday Saturday\nSondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag\nE_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune\nEhud Segno Maksegno Erob Hamus Arbe Kedame\nAl_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit\nGuiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat\ndomingu llunes martes miercoles xueves vienres sabadu\nBazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn\nIgande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat\nRobi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar\nNedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota\nDisul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn\nnedelia ponedelnik vtornik sriada chetvartak petak sabota\nsing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk\nDiumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte\nDzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee\ndy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn\nDimanch Lendi Madi Mekredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^li utery str^eda c^tvrtek patek sobota\nSondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee\ns0ndag mandag tirsdag onsdag torsdag fredag l0rdag\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nDiman^co Lundo Mardo Merkredo ^Jaudo Vendredo Sabato\npUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur manadagur tysdaguy mikudagur hosdagur friggjadagur leygardagur\nYek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh\nsunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai\ndimanche lundi mardi mercredi jeudi vendredi samedi\nSnein Moandei Tiisdei Woansdei Tonersdei Freed Sneon\nDomingo Segunda_feira Martes Mercores Joves Venres Sabado\nk'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag\nKiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato\nravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar\npopule po`akahi po`alua po`akolu po`aha po`alima po`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvasarnap hetfo kedd szerda csutortok pentek szombat\nSunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nDe_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn\ndomenica lunedi martedi mercoledi giovedi venerdi sabato\nNichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi\nIl-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nsve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien\nSekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis\nWangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi\nxing-_qi-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo minomishi martes mierkoles misheushi bernashi mishabaro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\nsphndag mandag tirsdag onsdag torsdag fredag lphrdag\nlo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabierna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminica Luni Mart'i Miercuri Joi Vineri Sambata\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-mairt Di-ciadain Di-ardaoin Di-haoine Di-sathurne\nnedjelja ponedjeljak utorak sreda cxetvrtak petak subota\nSontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo\nIridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-\nnedel^a pondelok utorok streda s^tvrtok piatok sobota\nNedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota\ndomingo lunes martes miercoles jueves viernes sabado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\nsondag mandag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nLe-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak\nwan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao\nTshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso\nPazar Pazartesi Sali Car,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_Ba?y\ndydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn\nDibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw\niCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo\nzuntik montik dinstik mitvokh donershtik fraytik shabes\niSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae\nSun Moon Mars Mercury Jove Venus Saturn\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nKoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend\nDomingo Luns Terza_feira Corta_feira Xoves Venres Sabado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\ndjadomingu djaluna djamars djarason djaweps djabierne djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.''\n\n\nTo make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).\n\n\nNotes concerning the above list of words\n::* each line has a list of days-of-the-week for a language, separated by at least one blank\n::* the words on each line happen to be in order, from Sunday --> Saturday\n::* most lines have words in mixed case and some have all manner of accented words and other characters\n::* some words were translated to the nearest character that was available to ''code page'' '''437'''\n::* the characters in the words are not restricted except that they may not have imbedded blanks\n::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* The list of words (days of the week) needn't be verified/validated.\n::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* A blank line (or a null line) should return a null string.\n::* Process and show the output for at least the first '''five''' lines of the file.\n::* Show all output here.\n\n\n", "solution": "def shortest_abbreviation_length(line, list_size):\n words = line.split()\n word_count = len(words)\n # Can't give true answer with unexpected number of entries\n if word_count != list_size:\n raise ValueError(f'Not enough entries, expected {list_size} found {word_count}')\n\n # Find the small slice length that gives list_size unique values\n abbreviation_length = 1\n abbreviations = set()\n while(True):\n abbreviations = {word[:abbreviation_length] for word in words}\n if len(abbreviations) == list_size:\n return abbreviation_length\n abbreviation_length += 1\n abbreviations.clear()\n\ndef automatic_abbreviations(filename, words_per_line):\n with open(filename) as file:\n for line in file:\n line = line.rstrip()\n if len(line) > 0:\n length = shortest_abbreviation_length(line, words_per_line)\n print(f'{length:2} {line}')\n else:\n print()\n\nautomatic_abbreviations('daysOfWeek.txt', 7)"} {"title": "Abbreviations, automatic", "language": "Python 3", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an\neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain (as words are added, changed, and/or deleted) if\nthe minimum abbreviation length of that list could be automatically (programmatically) determined.\n\n\nFor this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list).\n\nSunday Monday Tuesday Wednesday Thursday Friday Saturday\nSondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag\nE_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune\nEhud Segno Maksegno Erob Hamus Arbe Kedame\nAl_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit\nGuiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat\ndomingu llunes martes miercoles xueves vienres sabadu\nBazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn\nIgande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat\nRobi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar\nNedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota\nDisul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn\nnedelia ponedelnik vtornik sriada chetvartak petak sabota\nsing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk\nDiumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte\nDzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee\ndy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn\nDimanch Lendi Madi Mekredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^li utery str^eda c^tvrtek patek sobota\nSondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee\ns0ndag mandag tirsdag onsdag torsdag fredag l0rdag\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nDiman^co Lundo Mardo Merkredo ^Jaudo Vendredo Sabato\npUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur manadagur tysdaguy mikudagur hosdagur friggjadagur leygardagur\nYek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh\nsunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai\ndimanche lundi mardi mercredi jeudi vendredi samedi\nSnein Moandei Tiisdei Woansdei Tonersdei Freed Sneon\nDomingo Segunda_feira Martes Mercores Joves Venres Sabado\nk'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag\nKiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato\nravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar\npopule po`akahi po`alua po`akolu po`aha po`alima po`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvasarnap hetfo kedd szerda csutortok pentek szombat\nSunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nDe_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn\ndomenica lunedi martedi mercoledi giovedi venerdi sabato\nNichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi\nIl-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nsve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien\nSekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis\nWangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi\nxing-_qi-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo minomishi martes mierkoles misheushi bernashi mishabaro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\nsphndag mandag tirsdag onsdag torsdag fredag lphrdag\nlo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabierna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminica Luni Mart'i Miercuri Joi Vineri Sambata\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-mairt Di-ciadain Di-ardaoin Di-haoine Di-sathurne\nnedjelja ponedjeljak utorak sreda cxetvrtak petak subota\nSontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo\nIridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-\nnedel^a pondelok utorok streda s^tvrtok piatok sobota\nNedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota\ndomingo lunes martes miercoles jueves viernes sabado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\nsondag mandag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nLe-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak\nwan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao\nTshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso\nPazar Pazartesi Sali Car,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_Ba?y\ndydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn\nDibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw\niCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo\nzuntik montik dinstik mitvokh donershtik fraytik shabes\niSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae\nSun Moon Mars Mercury Jove Venus Saturn\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nKoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend\nDomingo Luns Terza_feira Corta_feira Xoves Venres Sabado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\ndjadomingu djaluna djamars djarason djaweps djabierne djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.''\n\n\nTo make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).\n\n\nNotes concerning the above list of words\n::* each line has a list of days-of-the-week for a language, separated by at least one blank\n::* the words on each line happen to be in order, from Sunday --> Saturday\n::* most lines have words in mixed case and some have all manner of accented words and other characters\n::* some words were translated to the nearest character that was available to ''code page'' '''437'''\n::* the characters in the words are not restricted except that they may not have imbedded blanks\n::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* The list of words (days of the week) needn't be verified/validated.\n::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* A blank line (or a null line) should return a null string.\n::* Process and show the output for at least the first '''five''' lines of the file.\n::* Show all output here.\n\n\n", "solution": "'''Automatic abbreviations'''\n\nfrom itertools import (accumulate, chain)\nfrom os.path import expanduser\n\n\n# abbrevLen :: [String] -> Int\ndef abbrevLen(xs):\n '''The minimum length of prefix required to obtain\n a unique abbreviation for each string in xs.'''\n n = len(xs)\n\n return next(\n len(a[0]) for a in map(\n compose(nub)(map_(concat)),\n transpose(list(map(inits, xs)))\n ) if n == len(a)\n )\n\n\n# TEST ----------------------------------------------------\ndef main():\n '''Test'''\n\n xs = map_(strip)(\n lines(readFile('weekDayNames.txt'))\n )\n for i, n in enumerate(map(compose(abbrevLen)(words), xs)):\n print(n, ' ', xs[i])\n\n\n# GENERIC -------------------------------------------------\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# concat :: [String] -> String\ndef concat(xs):\n '''The concatenation of a list of strings.'''\n return ''.join(xs)\n\n\n# inits :: [a] -> [[a]]\ndef inits(xs):\n '''all initial segments of xs, shortest first.'''\n return list(scanl(lambda a, x: a + [x])(\n []\n )(list(xs)))\n\n\n# lines :: String -> [String]\ndef lines(s):\n '''A list of strings,\n (containing no newline characters)\n derived from a single new-line delimited string.'''\n return s.splitlines()\n\n\n# map :: (a -> b) -> [a] -> [b]\ndef map_(f):\n '''The list obtained by applying f\n to each element of xs.'''\n return lambda xs: list(map(f, xs))\n\n\n# nub :: [a] -> [a]\ndef nub(xs):\n '''A list containing the same elements as xs,\n without duplicates, in the order of their\n first occurrence.'''\n return list(dict.fromkeys(xs))\n\n\n# readFile :: FilePath -> IO String\ndef readFile(fp):\n '''The contents of any file at the path\n derived by expanding any ~ in fp.'''\n with open(expanduser(fp), 'r', encoding='utf-8') as f:\n return f.read()\n\n\n# scanl :: (b -> a -> b) -> b -> [a] -> [b]\ndef scanl(f):\n '''scanl is like reduce, but returns a succession of\n intermediate values, building from the left.'''\n return lambda a: lambda xs: (\n accumulate(chain([a], xs), f)\n )\n\n\n# strip :: String -> String\ndef strip(s):\n '''A copy of s without any leading or trailling\n white space.'''\n return s.strip()\n\n\n# transpose :: Matrix a -> Matrix a\ndef transpose(m):\n '''The rows and columns of the argument transposed.\n (The matrix containers and rows can be lists or tuples).'''\n if m:\n inner = type(m[0])\n z = zip(*m)\n return (type(m))(\n map(inner, z) if tuple != inner else z\n )\n else:\n return m\n\n\n# words :: String -> [String]\ndef words(s):\n '''A list of words delimited by characters\n representing white space.'''\n return s.split()\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Abbreviations, easy", "language": "Python 3.6", "task": "This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].\n\n\nFor this task, the following ''command table'' will be used:\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the number of capital letters of the word in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''\n::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''\n::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "command_table_text = \\\n\"\"\"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\nCOUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\nNFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\nJoin SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\nMErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\nREAD RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\nRIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\"\"\"\n\nuser_words = \"riG rePEAT copies put mo rest types fup. 6 poweRin\"\n\ndef find_abbreviations_length(command_table_text):\n \"\"\" find the minimal abbreviation length for each word by counting capital letters.\n a word that does not have capital letters gets it's full length as the minimum.\n \"\"\"\n command_table = dict()\n for word in command_table_text.split():\n abbr_len = sum(1 for c in word if c.isupper())\n if abbr_len == 0:\n abbr_len = len(word)\n command_table[word] = abbr_len\n return command_table\n\ndef find_abbreviations(command_table):\n \"\"\" for each command insert all possible abbreviations\"\"\"\n abbreviations = dict()\n for command, min_abbr_len in command_table.items():\n for l in range(min_abbr_len, len(command)+1):\n abbr = command[:l].lower()\n abbreviations[abbr] = command.upper()\n return abbreviations\n\ndef parse_user_string(user_string, abbreviations):\n user_words = [word.lower() for word in user_string.split()]\n commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n return \" \".join(commands)\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)"} {"title": "Abbreviations, simple", "language": "Python 3.6", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "command_table_text = \"\"\"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\"\"\"\n\nuser_words = \"riG rePEAT copies put mo rest types fup. 6 poweRin\"\n\n\ndef find_abbreviations_length(command_table_text):\n \"\"\" find the minimal abbreviation length for each word.\n a word that does not have minimum abbreviation length specified\n gets it's full lengths as the minimum.\n \"\"\"\n command_table = dict()\n input_iter = iter(command_table_text.split())\n\n word = None\n try:\n while True:\n if word is None:\n word = next(input_iter)\n abbr_len = next(input_iter, len(word))\n try:\n command_table[word] = int(abbr_len)\n word = None\n except ValueError:\n command_table[word] = len(word)\n word = abbr_len\n except StopIteration:\n pass\n return command_table\n\n\ndef find_abbreviations(command_table):\n \"\"\" for each command insert all possible abbreviations\"\"\"\n abbreviations = dict()\n for command, min_abbr_len in command_table.items():\n for l in range(min_abbr_len, len(command)+1):\n abbr = command[:l].lower()\n abbreviations[abbr] = command.upper()\n return abbreviations\n\n\ndef parse_user_string(user_string, abbreviations):\n user_words = [word.lower() for word in user_string.split()]\n commands = [abbreviations.get(user_word, \"*error*\") for user_word in user_words]\n return \" \".join(commands)\n\n\ncommand_table = find_abbreviations_length(command_table_text)\nabbreviations_table = find_abbreviations(command_table)\n\nfull_words = parse_user_string(user_words, abbreviations_table)\n\nprint(\"user words:\", user_words)\nprint(\"full words:\", full_words)\n"} {"title": "Abbreviations, simple", "language": "Python 3.7", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "'''Simple abbreviations'''\n\nfrom functools import reduce\nimport re\n\n\n# withExpansions :: [(String, Int)] -> String -> String\ndef withExpansions(table):\n '''A string in which all words are either\n expanded (if they match abbreviations in\n a supplied table), or replaced with an\n '*error*' string.\n '''\n return lambda s: unwords(map(\n expanded(table), words(s)\n ))\n\n\n# expanded :: [(String, Int)] -> String -> String\ndef expanded(table):\n '''An abbreviation (or error string) for\n a given word, based on a table of full\n strings and minimum abbreviation lengths.\n '''\n def expansion(k):\n u = k.upper()\n lng = len(k)\n\n def p(wn):\n w, n = wn\n return w.startswith(u) and lng >= n\n return find(p)(table) if k else Just(('', 0))\n\n return lambda s: maybe('*error*')(fst)(expansion(s))\n\n\n# cmdsFromString :: String -> [(String, Int)]\ndef cmdsFromString(s):\n '''A simple rule-base consisting of a\n list of tuples [(\n upper case expansion string,\n minimum character count of abbreviation\n )],\n obtained by a parse of single input string.\n '''\n def go(a, x):\n xs, n = a\n return (xs, int(x)) if x.isdigit() else (\n ([(x.upper(), n)] + xs, 0)\n )\n return fst(reduce(\n go,\n reversed(re.split(r'\\s+', s)),\n ([], 0)\n ))\n\n\n# TEST -------------------------------------------------\ndef main():\n '''Tests of abbreviation expansions'''\n\n # table :: [(String, Int)]\n table = cmdsFromString(\n '''add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1\n Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3\n cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3\n extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1\n split 2 spltJOIN load locate 1 Clocate 2 lowerCase 3 upperCase 3\n Lprefix 2 macro merge 2 modify 3 move 2 msg next 1 overlay 1\n parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4\n rgtLEFT right 2 left 2 save set shift 2 si sort sos stack 3\n status 4 top transfer 3 type 1 up 1'''\n )\n\n # tests :: [String]\n tests = [\n 'riG rePEAT copies put mo rest types fup. 6 poweRin',\n ''\n ]\n\n print(\n fTable(__doc__ + ':\\n')(lambda s: \"'\" + s + \"'\")(\n lambda s: \"\\n\\t'\" + s + \"'\"\n )(withExpansions(table))(tests)\n )\n\n\n# GENERIC -------------------------------------------------\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.'''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.'''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# find :: (a -> Bool) -> [a] -> Maybe a\ndef find(p):\n '''Just the first element in the list that matches p,\n or Nothing if no elements match.'''\n def go(xs):\n for x in xs:\n if p(x):\n return Just(x)\n return Nothing()\n return lambda xs: go(xs)\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First member of a pair.'''\n return tpl[0]\n\n\n# fTable :: String -> (a -> String)\n# -> (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function ->\n fx display function ->\n f -> value list -> tabular string.'''\n def go(xShow, fxShow, f, xs):\n w = max(map(compose(len)(xShow), xs))\n return s + '\\n' + '\\n'.join([\n xShow(x).rjust(w, ' ') + (' -> ') + fxShow(f(x))\n for x in xs\n ])\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# maybe :: b -> (a -> b) -> Maybe a -> b\ndef maybe(v):\n '''Either the default value v, if m is Nothing,\n or the application of f to x,\n where m is Just(x).'''\n return lambda f: lambda m: v if m.get('Nothing') else (\n f(m.get('Just'))\n )\n\n\n# unwords :: [String] -> String\ndef unwords(xs):\n '''A space-separated string derived from\n a list of words.'''\n return ' '.join(xs)\n\n\n# words :: String -> [String]\ndef words(s):\n '''A list of words delimited by characters\n representing white space.'''\n return re.split(r'\\s+', s)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Abelian sandpile model", "language": "Python", "task": "{{wikipedia|Abelian sandpile model}}\nImplement the '''Abelian sandpile model''' also known as '''Bak-Tang-Wiesenfeld model'''. Its history, mathematical definition and properties can be found under its wikipedia article.\n\nThe task requires the creation of a 2D grid of arbitrary size on which \"piles of sand\" can be placed. Any \"pile\" that has 4 or more sand particles on it ''collapses'', resulting in '''four particles being subtracted from the pile''' and '''distributed among its neighbors.'''\n\nIt is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task.\nExamples up to 2^30, wow!\njavascript running on web\n'''Examples:'''\n\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 4 0 0 -> 0 1 0 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 6 0 0 -> 0 1 2 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 2 1 2 0\n0 0 16 0 0 -> 1 1 0 1 1\n0 0 0 0 0 0 2 1 2 0\n0 0 0 0 0 0 0 1 0 0\n\n", "solution": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef iterate(grid):\n changed = False\n for ii, arr in enumerate(grid):\n for jj, val in enumerate(arr):\n if val > 3:\n grid[ii, jj] -= 4\n if ii > 0:\n grid[ii - 1, jj] += 1\n if ii < len(grid)-1:\n grid[ii + 1, jj] += 1\n if jj > 0:\n grid[ii, jj - 1] += 1\n if jj < len(grid)-1:\n grid[ii, jj + 1] += 1\n changed = True\n return grid, changed\n\n\ndef simulate(grid):\n while True:\n grid, changed = iterate(grid)\n if not changed:\n return grid\n\n\nif __name__ == '__main__':\n start_grid = np.zeros((10, 10))\n start_grid[4:5, 4:5] = 64\n final_grid = simulate(start_grid.copy())\n plt.figure()\n plt.gray()\n plt.imshow(start_grid)\n plt.figure()\n plt.gray()\n plt.imshow(final_grid)"} {"title": "Abelian sandpile model/Identity", "language": "Python", "task": "Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that \ncontain a number from 0 to 3 inclusive. (The numbers are said to represent \ngrains of sand in each area of the sandpile).\n\nE.g. s1 =\n \n 1 2 0\n 2 1 1\n 0 1 3\n\n\nand s2 =\n\n 2 1 3\n 1 0 1\n 0 1 0\n \n\nAddition on sandpiles is done by adding numbers in corresponding grid areas,\nso for the above:\n\n 1 2 0 2 1 3 3 3 3\n s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2\n 0 1 3 0 1 0 0 2 3\n\n\nIf the addition would result in more than 3 \"grains of sand\" in any area then \nthose areas cause the whole sandpile to become \"unstable\" and the sandpile \nareas are \"toppled\" in an \"avalanche\" until the \"stable\" result is obtained.\n\nAny unstable area (with a number >= 4), is \"toppled\" by loosing one grain of \nsand to each of its four horizontal or vertical neighbours. Grains are lost \nat the edge of the grid, but otherwise increase the number in neighbouring \ncells by one, whilst decreasing the count in the toppled cell by four in each \ntoppling.\n\nA toppling may give an adjacent area more than four grains of sand leading to\na chain of topplings called an \"avalanche\".\nE.g.\n \n 4 3 3 0 4 3 1 0 4 1 1 0 2 1 0\n 3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3\n 0 2 3 0 2 3 0 2 3 0 2 3 1 2 3\n\n\nThe final result is the stable sandpile on the right. \n\n'''Note:''' The order in which cells are toppled does not affect the final result.\n\n;Task:\n* Create a class or datastructure and functions to represent and operate on sandpiles. \n* Confirm the result of the avalanche of topplings shown above\n* Confirm that s1 + s2 == s2 + s1 # Show the stable results\n* If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile:\n\n 2 1 2 \n 1 0 1 \n 2 1 2\n\n\n* Show that s3 + s3_id == s3\n* Show that s3_id + s3_id == s3_id\n\n\nShow confirming output here, with your examples.\n\n\n;References:\n* https://www.youtube.com/watch?v=1MtEUErz7Gg\n* https://en.wikipedia.org/wiki/Abelian_sandpile_model\n\n", "solution": "'''Abelian Sandpile \u2013 Identity'''\n\nfrom operator import add, eq\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Tests of cascades and additions'''\n s0 = [[4, 3, 3], [3, 1, 2], [0, 2, 3]]\n s1 = [[1, 2, 0], [2, 1, 1], [0, 1, 3]]\n s2 = [[2, 1, 3], [1, 0, 1], [0, 1, 0]]\n s3 = [[3, 3, 3], [3, 3, 3], [3, 3, 3]]\n s3_id = [[2, 1, 2], [1, 0, 1], [2, 1, 2]]\n\n series = list(cascadeSeries(s0))\n for expr in [\n 'Cascade:',\n showSandPiles(\n [(' ', series[0])] + [\n (':', xs) for xs in series[1:]\n ]\n ),\n '',\n f's1 + s2 == s2 + s1 -> {addSand(s1)(s2) == addSand(s2)(s1)}',\n showSandPiles([\n (' ', s1),\n ('+', s2),\n ('=', addSand(s1)(s2))\n ]),\n '',\n showSandPiles([\n (' ', s2),\n ('+', s1),\n ('=', addSand(s2)(s1))\n ]),\n '',\n f's3 + s3_id == s3 -> {addSand(s3)(s3_id) == s3}',\n showSandPiles([\n (' ', s3),\n ('+', s3_id),\n ('=', addSand(s3)(s3_id))\n ]),\n '',\n f's3_id + s3_id == s3_id -> {addSand(s3_id)(s3_id) == s3_id}',\n showSandPiles([\n (' ', s3_id),\n ('+', s3_id),\n ('=', addSand(s3_id)(s3_id))\n ]),\n\n ]:\n print(expr)\n\n\n# ----------------------- SANDPILES ------------------------\n\n# addSand :: [[Int]] -> [[Int]] -> [[Int]]\ndef addSand(xs):\n '''The stabilised sum of two sandpiles.\n '''\n def go(ys):\n return cascadeSeries(\n chunksOf(len(xs))(\n map(\n add,\n concat(xs),\n concat(ys)\n )\n )\n )[-1]\n return go\n\n\n# cascadeSeries :: [[Int]] -> [[[Int]]]\ndef cascadeSeries(rows):\n '''The sequence of states from a given\n sand pile to a stable condition.\n '''\n xs = list(rows)\n w = len(xs)\n return [\n list(chunksOf(w)(x)) for x\n in convergence(eq)(\n iterate(nextState(w))(\n concat(xs)\n )\n )\n ]\n\n\n# convergence :: (a -> a -> Bool) -> [a] -> [a]\ndef convergence(p):\n '''All items of xs to the point where the binary\n p returns True over two successive values.\n '''\n def go(xs):\n def conv(prev, ys):\n y = next(ys)\n return [prev] + (\n [] if p(prev, y) else conv(y, ys)\n )\n return conv(next(xs), xs)\n return go\n\n\n# nextState Int -> Int -> [Int] -> [Int]\ndef nextState(w):\n '''The next state of a (potentially unstable)\n flattened sand-pile matrix of row length w.\n '''\n def go(xs):\n def tumble(i):\n neighbours = indexNeighbours(w)(i)\n return [\n 1 + k if j in neighbours else (\n k - (1 + w) if j == i else k\n ) for (j, k) in enumerate(xs)\n ]\n return maybe(xs)(tumble)(\n findIndex(lambda x: w < x)(xs)\n )\n return go\n\n\n# indexNeighbours :: Int -> Int -> [Int]\ndef indexNeighbours(w):\n '''Indices vertically and horizontally adjoining the\n given index in a flattened matrix of dimension w.\n '''\n def go(i):\n lastCol = w - 1\n iSqr = (w * w)\n col = i % w\n return [\n j for j in [i - w, i + w]\n if -1 < j < iSqr\n ] + ([i - 1] if 0 != col else []) + (\n [1 + i] if lastCol != col else []\n )\n return go\n\n\n# ------------------------ DISPLAY -------------------------\n\n# showSandPiles :: [(String, [[Int]])] -> String\ndef showSandPiles(pairs):\n '''Indented multi-line representation\n of a sequence of matrices, delimited\n by preceding operators or indents.\n '''\n return '\\n'.join([\n ' '.join([' '.join(map(str, seq)) for seq in tpl])\n for tpl in zip(*[\n zip(\n *[list(str(pfx).center(len(rows)))]\n + list(zip(*rows))\n )\n for (pfx, rows) in pairs\n ])\n ])\n\n\n# ------------------------ GENERIC -------------------------\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n '''A series of lists of length n, subdividing the\n contents of xs. Where the length of xs is not evenly\n divible, the final list will be shorter than n.\n '''\n def go(xs):\n ys = list(xs)\n return (\n ys[i:n + i] for i in range(0, len(ys), n)\n ) if 0 < n else None\n return go\n\n\n# concat :: [[a]] -> [a]\ndef concat(xs):\n '''The concatenation of all\n elements in a list.\n '''\n return [x for lst in xs for x in lst]\n\n\n# findIndex :: (a -> Bool) -> [a] -> Maybe Int\ndef findIndex(p):\n '''Just the first index at which an\n element in xs matches p,\n or Nothing if no elements match.\n '''\n def go(xs):\n return next(\n (i for (i, x) in enumerate(xs) if p(x)),\n None\n )\n return go\n\n\n# iterate :: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n '''An infinite list of repeated\n applications of f to x.\n '''\n def go(x):\n v = x\n while True:\n yield v\n v = f(v)\n return go\n\n\n# maybe :: b -> (a -> b) -> Maybe a -> b\ndef maybe(v):\n '''Either the default value v, if x is None,\n or the application of f to x.\n '''\n def go(f):\n def g(x):\n return v if None is x else f(x)\n return g\n return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Abundant odd numbers", "language": "Python from Visual Basic .NET", "task": "An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',\nor, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.\n\n\n;E.G.:\n'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); \n or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').\n\n\nAbundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. \n\nTo make things more interesting, this task is specifically about finding ''odd abundant numbers''.\n\n\n;Task\n*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\n;References:\n:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n", "solution": "#!/usr/bin/python\n# Abundant odd numbers - Python\n\noddNumber = 1\naCount = 0\ndSum = 0\n \nfrom math import sqrt\n \ndef divisorSum(n):\n sum = 1\n i = int(sqrt(n)+1)\n \n for d in range (2, i):\n if n % d == 0:\n sum += d\n otherD = n // d\n if otherD != d:\n sum += otherD\n return sum\n \nprint (\"The first 25 abundant odd numbers:\")\nwhile aCount < 25:\n dSum = divisorSum(oddNumber )\n if dSum > oddNumber :\n aCount += 1\n print(\"{0:5} proper divisor sum: {1}\". format(oddNumber ,dSum ))\n oddNumber += 2\n \nwhile aCount < 1000:\n dSum = divisorSum(oddNumber )\n if dSum > oddNumber :\n aCount += 1\n oddNumber += 2\nprint (\"\\n1000th abundant odd number:\")\nprint (\" \",(oddNumber - 2),\" proper divisor sum: \",dSum)\n \noddNumber = 1000000001\nfound = False\nwhile not found :\n dSum = divisorSum(oddNumber )\n if dSum > oddNumber :\n found = True\n print (\"\\nFirst abundant odd number > 1 000 000 000:\")\n print (\" \",oddNumber,\" proper divisor sum: \",dSum)\n oddNumber += 2"} {"title": "Accumulator factory", "language": "Python 2.x/3.x", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": ">>> def accumulator(sum):\n def f(n):\n f.sum += n\n return f.sum\n f.sum = sum\n return f\n\n>>> x = accumulator(1)\n>>> x(5)\n6\n>>> x(2.3)\n8.3000000000000007\n>>> x = accumulator(1)\n>>> x(5)\n6\n>>> x(2.3)\n8.3000000000000007\n>>> x2 = accumulator(3)\n>>> x2(5)\n8\n>>> x2(3.3)\n11.300000000000001\n>>> x(0)\n8.3000000000000007\n>>> x2(0)\n11.300000000000001"} {"title": "Accumulator factory", "language": "Python 3.x", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "def accumulator(sum):\n def f(n):\n nonlocal sum\n sum += n\n return sum\n return f\n\nx = accumulator(1)\nx(5)\nprint(accumulator(3))\nprint(x(2.3))"} {"title": "Accumulator factory", "language": "Python 2.5+", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "def accumulator(sum):\n while True:\n sum += yield sum\n\nx = accumulator(1)\nx.send(None)\nx.send(5)\nprint(accumulator(3))\nprint(x.send(2.3))"} {"title": "Achilles numbers", "language": "Python", "task": "{{Wikipedia|Achilles number}}\n\n\nAn '''Achilles number''' is a number that is powerful but imperfect. ''Named after Achilles, a hero of the Trojan war, who was also powerful but imperfect.''\n\n\nA positive integer '''n''' is a powerful number if, for every prime factor '''p''' of '''n''', '''p2''' is also a divisor.\n\nIn other words, every prime factor appears at least squared in the factorization.\n\nAll '''Achilles numbers''' are powerful. However, not all powerful numbers are '''Achilles numbers''': only those that cannot be represented as '''mk''', where '''m''' and '''k''' are positive integers greater than '''1'''.\n\n\nA '''''strong'' Achilles number''' is an '''Achilles number''' whose '''Euler totient ()''' is also an '''Achilles number'''.\n\n\n\n;E.G.\n\n'''108''' is a powerful number. Its prime factorization is '''22 x 33''', and thus its prime factors are '''2''' and '''3'''. Both '''22 = 4''' and '''32 = 9''' are divisors of '''108'''. However, '''108''' cannot be represented as '''mk''', where '''m''' and '''k''' are positive integers greater than '''1''', so '''108''' is an '''Achilles number'''.\n\n'''360''' is ''not'' an '''Achilles number''' because it is not powerful. One of its prime factors is '''5''' but '''360''' is not divisible by '''52 = 25'''.\n\nFinally, '''784''' is ''not'' an '''Achilles number'''. It is a powerful number, because not only are '''2''' and '''7''' its only prime factors, but also '''22 = 4''' and '''72 = 49''' are divisors of it. Nonetheless, it is a perfect power; its square root is an even integer, so it is ''not'' an '''Achilles number'''.\n\n\n'''500 = 22 x 53''' is a '''''strong'' Achilles number''' as its Euler totient, '''(500)''', is '''200 = 23 x 52''' which is ''also'' an '''Achilles number'''.\n\n\n\n;Task\n\n* Find and show the first 50 '''Achilles numbers'''.\n* Find and show at least the first 20 '''''strong'' Achilles numbers'''.\n* For at least 2 through 5, show the count of '''Achilles numbers''' with that many digits.\n\n\n;See also\n\n;* Wikipedia: Achilles number\n;* OEIS:A052486 - Achilles numbers - powerful but imperfect numbers\n;* OEIS:A194085 - Strong Achilles numbers: Achilles numbers m such that phi(m) is also an Achilles number\n;* Related task: Powerful numbers\n;* Related task: Totient function\n\n\n", "solution": "from math import gcd\nfrom sympy import factorint\n \ndef is_Achilles(n):\n p = factorint(n).values()\n return all(i > 1 for i in p) and gcd(*p) == 1\n\ndef is_strong_Achilles(n):\n return is_Achilles(n) and is_Achilles(totient(n))\n \ndef test_strong_Achilles(nachilles, nstrongachilles):\n # task 1\n print('First', nachilles, 'Achilles numbers:')\n n, found = 0, 0\n while found < nachilles:\n if is_Achilles(n):\n found += 1\n print(f'{n: 8,}', end='\\n' if found % 10 == 0 else '')\n n += 1\n\n # task 2\n print('\\nFirst', nstrongachilles, 'strong Achilles numbers:')\n n, found = 0, 0\n while found < nstrongachilles:\n if is_strong_Achilles(n):\n found += 1\n print(f'{n: 9,}', end='\\n' if found % 10 == 0 else '')\n n += 1\n\n # task 3\n print('\\nCount of Achilles numbers for various intervals:')\n intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]\n for interval in intervals:\n print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))\n\n\ntest_strong_Achilles(50, 100)\n"} {"title": "Aliquot sequence classifications", "language": "Python", "task": "An aliquot sequence of a positive integer K is defined recursively as the first member\nbeing K and subsequent members being the sum of the [[Proper divisors]] of the previous term.\n\n:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.\n\n:There are several classifications for non termination:\n:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.\n:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.\n:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.\n:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...\n:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.\n:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.\n\n:And finally:\n:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. \n\n\n;Task:\n# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.\n# Use it to display the classification and sequences of the numbers one to ten inclusive.\n# Use it to show the classification and sequences of the following integers, in order:\n:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.\n\nShow all output on this page.\n\n\n;Related tasks:\n* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).\n* [[Proper divisors]]\n* [[Amicable pairs]]\n\n", "solution": "from proper_divisors import proper_divs\nfrom functools import lru_cache\n\n\n@lru_cache()\ndef pdsum(n): \n return sum(proper_divs(n))\n \n \ndef aliquot(n, maxlen=16, maxterm=2**47):\n if n == 0:\n return 'terminating', [0]\n s, slen, new = [n], 1, n\n while slen <= maxlen and new < maxterm:\n new = pdsum(s[-1])\n if new in s:\n if s[0] == new:\n if slen == 1:\n return 'perfect', s\n elif slen == 2:\n return 'amicable', s\n else:\n return 'sociable of length %i' % slen, s\n elif s[-1] == new:\n return 'aspiring', s\n else:\n return 'cyclic back to %i' % new, s\n elif new == 0:\n return 'terminating', s + [0]\n else:\n s.append(new)\n slen += 1\n else:\n return 'non-terminating', s\n \nif __name__ == '__main__':\n for n in range(1, 11): \n print('%s: %r' % aliquot(n))\n print()\n for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: \n print('%s: %r' % aliquot(n))"} {"title": "Almkvist-Giullera formula for pi", "language": "Python", "task": "The Almkvist-Giullera formula for calculating 1/p2 is based on the Calabi-Yau\ndifferential equations of order 4 and 5, which were originally used to describe certain manifolds\nin string theory. \n\n\nThe formula is:\n::::: 1/p2 = (25/3) 0 ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1\n\n\nThis formula can be used to calculate the constant p-2, and thus to calculate p.\n\nNote that, because the product of all terms but the power of 1000 can be calculated as an integer,\nthe terms in the series can be separated into a large integer term:\n\n::::: (25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)\n\nmultiplied by a negative integer power of 10:\n\n::::: 10-(6n + 3) \n\n\n;Task:\n:* Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.\n:* Use the complete formula to calculate and print p to 70 decimal digits of precision.\n\n\n;Reference:\n:* Gert Almkvist and Jesus Guillera, Ramanujan-like series for 1/p2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.\n\n", "solution": "import mpmath as mp\n\nwith mp.workdps(72):\n\n def integer_term(n):\n p = 532 * n * n + 126 * n + 9\n return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)\n\n def exponent_term(n):\n return -(mp.mpf(\"6.0\") * n + 3)\n\n def nthterm(n):\n return integer_term(n) * mp.mpf(\"10.0\")**exponent_term(n)\n\n\n for n in range(10):\n print(\"Term \", n, ' ', int(integer_term(n)))\n\n\n def almkvist_guillera(floatprecision):\n summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')\n for n in range(100000000):\n nextadd = summed + nthterm(n)\n if abs(nextadd - summed) < 10.0**(-floatprecision):\n break\n\n summed = nextadd\n\n return nextadd\n\n\n print('\\n\u03c0 to 70 digits is ', end='')\n mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)\n print('mpmath \u03c0 is ', end='')\n mp.nprint(mp.pi, 71)\n"} {"title": "Amb", "language": "Python", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "import itertools as _itertools\n \nclass Amb(object):\n def __init__(self):\n self._names2values = {} # set of values for each global name\n self._func = None # Boolean constraint function\n self._valueiterator = None # itertools.product of names values\n self._funcargnames = None # Constraint parameter names\n \n def __call__(self, arg=None):\n if hasattr(arg, '__code__'): \n ##\n ## Called with a constraint function. \n ##\n globls = arg.__globals__ if hasattr(arg, '__globals__') else arg.func_globals\n # Names used in constraint\n argv = arg.__code__.co_varnames[:arg.__code__.co_argcount]\n for name in argv:\n if name not in self._names2values:\n assert name in globls, \\\n \"Global name %s not found in function globals\" % name\n self._names2values[name] = globls[name]\n # Gather the range of values of all names used in the constraint\n valuesets = [self._names2values[name] for name in argv]\n self._valueiterator = _itertools.product(*valuesets)\n self._func = arg\n self._funcargnames = argv\n return self\n elif arg is not None:\n ##\n ## Assume called with an iterable set of values\n ##\n arg = frozenset(arg)\n return arg\n else:\n ##\n ## blank call tries to return next solution\n ##\n return self._nextinsearch()\n \n def _nextinsearch(self):\n arg = self._func\n globls = arg.__globals__\n argv = self._funcargnames\n found = False\n for values in self._valueiterator:\n if arg(*values):\n # Set globals.\n found = True\n for n, v in zip(argv, values):\n globls[n] = v\n break\n if not found: raise StopIteration\n return values\n \n def __iter__(self):\n return self\n \n def __next__(self):\n return self()\n next = __next__ # Python 2\n \nif __name__ == '__main__':\n if True:\n amb = Amb()\n \n print(\"\\nSmall Pythagorean triples problem:\")\n x = amb(range(1,11))\n y = amb(range(1,11))\n z = amb(range(1,11))\n \n for _dummy in amb( lambda x, y, z: x*x + y*y == z*z ):\n print ('%s %s %s' % (x, y, z))\n \n \n if True:\n amb = Amb()\n \n print(\"\\nRosetta Code Amb problem:\")\n w1 = amb([\"the\", \"that\", \"a\"])\n w2 = amb([\"frog\", \"elephant\", \"thing\"])\n w3 = amb([\"walked\", \"treaded\", \"grows\"])\n w4 = amb([\"slowly\", \"quickly\"])\n \n for _dummy in amb( lambda w1, w2, w3, w4: \\\n w1[-1] == w2[0] and \\\n w2[-1] == w3[0] and \\\n w3[-1] == w4[0] ):\n print ('%s %s %s %s' % (w1, w2, w3, w4))\n \n if True:\n amb = Amb()\n \n print(\"\\nAmb problem from \"\n \"http://www.randomhacks.net/articles/2005/10/11/amb-operator:\")\n x = amb([1, 2, 3])\n y = amb([4, 5, 6])\n \n for _dummy in amb( lambda x, y: x * y != 8 ):\n print ('%s %s' % (x, y))"} {"title": "Amb", "language": "Python from Haskell", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "# joins :: String -> String -> Bool\ndef joins(a, b):\n return a[-1] == b[0]\n\n\nprint (\n [\n ' '.join([w1, w2, w3, w4])\n for w1 in ['the', 'that', 'a']\n for w2 in ['frog', 'elephant', 'thing']\n for w3 in ['walked', 'treaded', 'grows']\n for w4 in ['slowly', 'quickly']\n if joins(w1, w2) and joins(w2, w3) and joins(w3, w4)\n ]\n)"} {"title": "Anagrams/Deranged anagrams", "language": "Python", "task": "Two or more words are said to be anagrams if they have the same characters, but in a different order. \n\nBy analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.\n\n;Task\n\nUse the word list at unixdict to find and display the longest deranged anagram. \n\n\n;Related\n* [[Permutations/Derangements]]\n* Best shuffle\n\n{{Related tasks/Word plays}}\n\n\n\n", "solution": "import urllib.request\nfrom collections import defaultdict\nfrom itertools import combinations\n\ndef getwords(url='http://www.puzzlers.org/pub/wordlists/unixdict.txt'):\n return list(set(urllib.request.urlopen(url).read().decode().split()))\n\ndef find_anagrams(words):\n anagram = defaultdict(list) # map sorted chars to anagrams\n for word in words:\n anagram[tuple(sorted(word))].append( word )\n return dict((key, words) for key, words in anagram.items()\n if len(words) > 1)\n\ndef is_deranged(words):\n 'returns pairs of words that have no character in the same position'\n return [ (word1, word2)\n for word1,word2 in combinations(words, 2)\n if all(ch1 != ch2 for ch1, ch2 in zip(word1, word2)) ]\n\ndef largest_deranged_ana(anagrams):\n ordered_anagrams = sorted(anagrams.items(),\n key=lambda x:(-len(x[0]), x[0]))\n for _, words in ordered_anagrams:\n deranged_pairs = is_deranged(words)\n if deranged_pairs:\n return deranged_pairs\n return []\n\nif __name__ == '__main__':\n words = getwords('http://www.puzzlers.org/pub/wordlists/unixdict.txt')\n print(\"Word count:\", len(words))\n\n anagrams = find_anagrams(words)\n print(\"Anagram count:\", len(anagrams),\"\\n\")\n\n print(\"Longest anagrams with no characters in the same position:\")\n print(' ' + '\\n '.join(', '.join(pairs)\n for pairs in largest_deranged_ana(anagrams)))"} {"title": "Angle difference between two bearings", "language": "Python from C++", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "from __future__ import print_function\n \ndef getDifference(b1, b2):\n\tr = (b2 - b1) % 360.0\n\t# Python modulus has same sign as divisor, which is positive here,\n\t# so no need to consider negative case\n\tif r >= 180.0:\n\t\tr -= 360.0\n\treturn r\n \nif __name__ == \"__main__\":\n\tprint (\"Input in -180 to +180 range\")\n\tprint (getDifference(20.0, 45.0))\n\tprint (getDifference(-45.0, 45.0))\n\tprint (getDifference(-85.0, 90.0))\n\tprint (getDifference(-95.0, 90.0))\n\tprint (getDifference(-45.0, 125.0))\n\tprint (getDifference(-45.0, 145.0))\n\tprint (getDifference(-45.0, 125.0))\n\tprint (getDifference(-45.0, 145.0))\n\tprint (getDifference(29.4803, -88.6381))\n\tprint (getDifference(-78.3251, -159.036))\n \n\tprint (\"Input in wider range\")\n\tprint (getDifference(-70099.74233810938, 29840.67437876723))\n\tprint (getDifference(-165313.6666297357, 33693.9894517456))\n\tprint (getDifference(1174.8380510598456, -154146.66490124757))\n\tprint (getDifference(60175.77306795546, 42213.07192354373))"} {"title": "Angle difference between two bearings", "language": "Python 3.7", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "'''Difference between two bearings'''\n\nfrom math import (acos, cos, pi, sin)\n\n\n# bearingDelta :: Radians -> Radians -> Radians\ndef bearingDelta(ar):\n '''Difference between two bearings,\n expressed in radians.'''\n def go(br):\n [(ax, ay), (bx, by)] = [\n (sin(x), cos(x)) for x in [ar, br]\n ]\n # cross-product > 0 ?\n sign = +1 if 0 < ((ay * bx) - (by * ax)) else -1\n # sign * dot-product\n return sign * acos((ax * bx) + (ay * by))\n return lambda br: go(br)\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test and display'''\n\n # showMap :: Degrees -> Degrees -> String\n def showMap(da, db):\n return unwords(\n str(x).rjust(n) for n, x in\n [\n (22, str(da) + ' +'),\n (24, str(db) + ' -> '),\n (7, round(\n degrees(\n bearingDelta\n (radians(da))\n (radians(db))\n ), 2)\n )\n ]\n )\n\n print(__doc__ + ':')\n print(\n unlines(showMap(a, b) for a, b in [\n (20, 45),\n (-45, 45),\n (-85, 90),\n (-95, 90),\n (-45, 125),\n (-45, 145),\n (-70099.74233810938, 29840.67437876723),\n (-165313.6666297357, 33693.9894517456),\n (1174.8380510598456, -154146.66490124757),\n (60175.77306795546, 42213.07192354373)\n ]))\n\n\n# GENERIC ----------------------------------------------\n\n\n# radians :: Float x => Degrees x -> Radians x\ndef radians(x):\n '''Radians derived from degrees.'''\n return pi * x / 180\n\n\n# degrees :: Float x => Radians x -> Degrees x\ndef degrees(x):\n '''Degrees derived from radians.'''\n return 180 * x / pi\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single newline-delimited string derived\n from a list of strings.'''\n return '\\n'.join(xs)\n\n\n# unwords :: [String] -> String\ndef unwords(xs):\n '''A space-separated string derived from\n a list of words.'''\n return ' '.join(xs)\n\n\nif __name__ == '__main__':\n main()"} {"title": "Angle difference between two bearings", "language": "Python 3.6", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "\"\"\"\nDifference between two bearings\n\"\"\"\n\ndef delta_bearing(b1 , b2):\n\treturn ((b2-b1+540)%360)-180\n\ndataSet = [[20, 45], [-45, 45], [-85, 90], [-95, 90], [-45, 125], [-45, 145], \\\n\t[29.4803, -88.6381], [-78.3251, -159.036], \\\n\t[-70099.74233810938, 29840.67437876723], \\\n\t[-165313.6666297357, 33693.9894517456], \\\n\t[1174.8380510598456, -154146.66490124757], \\\n\t[60175.77306795546, 42213.07192354373]]\n\nprint('.{:-^19}.{:-^19}.{:-^9}.' .format(\" b1 \", \" b2 \", \" \u0394 b \" ))\nfor \u0394 in dataSet: \n\tprint('|{: > 19}|{: > 19}|{: > 9.4f}|' .format(\u0394[0], \u0394[1],delta_bearing(\u0394[0],\u0394[1])))"} {"title": "Anti-primes", "language": "Python", "task": "The anti-primes \n(or highly composite numbers, sequence A002182 in the OEIS) \nare the natural numbers with more factors than any smaller than itself.\n\n\n;Task:\nGenerate and show here, the first twenty anti-primes.\n\n\n;Related tasks:\n:* [[Factors of an integer]]\n:* [[Sieve of Eratosthenes]]\n\n", "solution": "from itertools import chain, count, cycle, islice, accumulate\n \ndef factors(n):\n def prime_powers(n):\n for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n if c*c > n: break\n if n%c: continue\n d,p = (), c\n while not n%c:\n n,p,d = n//c, p*c, d+(p,)\n yield d\n if n > 1: yield n,\n \n r = [1]\n for e in prime_powers(n):\n r += [a*b for a in r for b in e]\n return r\n \ndef antiprimes():\n mx = 0\n yield 1\n for c in count(2,2):\n if c >= 58: break\n ln = len(factors(c))\n if ln > mx:\n yield c\n mx = ln\n for c in count(60,30):\n ln = len(factors(c))\n if ln > mx:\n yield c\n mx = ln \n\nif __name__ == '__main__':\n print(*islice(antiprimes(), 40)))"} {"title": "Apply a digital filter (direct form II transposed)", "language": "Python", "task": "Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the \"direct form II transposed\" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]\n\n;Task:\n\nFilter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]\n\nThe signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]\n\n;See also:\n[Wikipedia on Butterworth filters]\n\n\n", "solution": "#!/bin/python\nfrom __future__ import print_function\nfrom scipy import signal\nimport matplotlib.pyplot as plt\n\nif __name__==\"__main__\":\n\tsig = [-0.917843918645,0.141984778794,1.20536903482,0.190286794412,-0.662370894973,-1.00700480494,\n\t\t-0.404707073677,0.800482325044,0.743500089861,1.01090520172,0.741527555207,\n\t\t0.277841675195,0.400833448236,-0.2085993586,-0.172842103641,-0.134316096293,\n\t\t0.0259303398477,0.490105989562,0.549391221511,0.9047198589]\n\n\t#Create an order 3 lowpass butterworth filter\n\t#Generated using b, a = signal.butter(3, 0.5)\n\ta = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]\n\tb = [0.16666667, 0.5, 0.5, 0.16666667]\n\n\t#Apply the filter to signal\n\tfilt = signal.lfilter(b, a, sig)\n\tprint (filt)\n\n\tplt.plot(sig, 'b')\n\tplt.plot(filt, 'r--')\n\tplt.show()"} {"title": "Approximate equality", "language": "Python", "task": "Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the\ndifference in floating point calculations between different language implementations becomes significant. \n\nFor example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by \nabout the 8th significant digit in base 10 arithmetic.\n\n\n;Task:\nCreate a function which returns true if two floating point numbers are approximately equal. \n\n\nThe function should allow for differences in the magnitude of numbers, so that, for example, \n'''100000000000000.01''' may be approximately equal to '''100000000000000.011''', \neven though '''100.01''' is not approximately equal to '''100.011'''.\n\nIf the language has such a feature in its standard library, this may be used instead of a custom function.\n\nShow the function results with comparisons on the following pairs of values:\n:# 100000000000000.01, 100000000000000.011 (note: should return ''true'')\n:# 100.01, 100.011 (note: should return ''false'')\n:# 10000000000000.001 / 10000.0, 1000000000.0000001000\n:# 0.001, 0.0010000001\n:# 0.000000000000000000000101, 0.0\n:# sqrt(2) * sqrt(2), 2.0\n:# -sqrt(2) * sqrt(2), -2.0\n:# 3.14159265358979323846, 3.14159265358979324\n\nAnswers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.\n\n\n__TOC__\n\n", "solution": "from numpy import sqrt\nfrom math import isclose\n\ntestvalues = [[100000000000000.01, 100000000000000.011],\n [100.01, 100.011],\n [10000000000000.001 / 10000.0, 1000000000.0000001000],\n [0.001, 0.0010000001],\n [0.000000000000000000000101, 0.0],\n [sqrt(2) * sqrt(2), 2.0],\n [-sqrt(2) * sqrt(2), -2.0],\n [3.14159265358979323846, 3.14159265358979324]]\n\nfor (x, y) in testvalues:\n maybenot = \"is\" if isclose(x, y) else \"is NOT\"\n print(x, maybenot, \"approximately equal to \", y)\n\n"} {"title": "Archimedean spiral", "language": "Python", "task": "The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. \n\n\nAn Archimedean spiral can be described by the equation:\n\n:\\, r=a+b\\theta\n\nwith real numbers ''a'' and ''b''.\n\n\n;Task\nDraw an Archimedean spiral.\n\n", "solution": "from turtle import *\nfrom math import *\ncolor(\"blue\")\ndown()\nfor i in range(200):\n t = i / 20 * pi\n x = (1 + 5 * t) * cos(t)\n y = (1 + 5 * t) * sin(t)\n goto(x, y)\nup()\ndone()"} {"title": "Arena storage pool", "language": "Python", "task": "Dynamically allocated objects take their memory from a [[heap]]. \n\nThe memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]].\n\nOften a call to allocator is denoted as\nP := new T\nwhere '''T''' is the type of an allocated object, and '''P''' is a [[reference]] to the object.\n\nThe storage pool chosen by the allocator can be determined by either:\n* the object type '''T'''\n* the type of pointer '''P'''\n\n\nIn the former case objects can be allocated only in one storage pool. \n\nIn the latter case objects of the type can be allocated in any storage pool or on the [[stack]].\n\n\n;Task:\nThe task is to show how allocators and user-defined storage pools are supported by the language. \n\nIn particular:\n# define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.\n# allocate some objects (e.g., integers) in the pool.\n\n\nExplain what controls the storage pool choice in the language.\n\n", "solution": "In Python:\n* Everything is an object.\n* Objects are dynamically allocated.\n* Unused objects are garbage collected.\n\nWhere objects appear from, or disappear to, is treated as an implementation detail.\n\nStatements, such as assignments, class and function definitions, and import statements can create objects and assign names to them which can be seen as assigning a reference to objects. Objects can also be referred to from other objects e.g. in collections such as lists.
\nWhen names go out of scope, or objects are explicitly destroyed, references to objects are diminished. Python's implementation keeps track of references to objects and marks objects that have no remaining references so that they become candidates for '[[wp:Garbage collection (computer science)|garbage collection]]' at a later time.\n\n"} {"title": "Arithmetic-geometric mean", "language": "Python", "task": "{{wikipedia|Arithmetic-geometric mean}}\n\n\n;Task:\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \\mathrm{agm}(a,g), and is equal to the limit of the sequence:\n: a_0 = a; \\qquad g_0 = g\n: a_{n+1} = \\tfrac{1}{2}(a_n + g_n); \\quad g_{n+1} = \\sqrt{a_n g_n}.\nSince the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n:\\mathrm{agm}(1,1/\\sqrt{2})\n \n\n;Also see:\n* mathworld.wolfram.com/Arithmetic-Geometric Mean\n\n", "solution": "from math import sqrt\n\ndef agm(a0, g0, tolerance=1e-10):\n \"\"\"\n Calculating the arithmetic-geometric mean of two numbers a0, g0.\n\n tolerance the tolerance for the converged \n value of the arithmetic-geometric mean\n (default value = 1e-10)\n \"\"\"\n an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0)\n while abs(an - gn) > tolerance:\n an, gn = (an + gn) / 2.0, sqrt(an * gn)\n return an\n\nprint agm(1, 1 / sqrt(2))"} {"title": "Arithmetic-geometric mean/Calculate Pi", "language": "Python from Ruby", "task": "Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \\pi.\n\nWith the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing:\n\n\\pi =\n\\frac{4\\; \\mathrm{agm}(1, 1/\\sqrt{2})^2}\n{1 - \\sum\\limits_{n=1}^{\\infty} 2^{n+1}(a_n^2-g_n^2)}\n\n\nThis allows you to make the approximation, for any large '''N''':\n\n\\pi \\approx\n\\frac{4\\; a_N^2}\n{1 - \\sum\\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)}\n\n\nThe purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \\pi.\n\n", "solution": "from decimal import *\n\nD = Decimal\ngetcontext().prec = 100\na = n = D(1)\ng, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5)\nfor i in range(18):\n x = [(a + g) * half, (a * g).sqrt()]\n var = x[0] - a\n z -= var * var * n\n n += n\n a, g = x \nprint(a * a / z)"} {"title": "Arithmetic derivative", "language": "Python", "task": "The '''arithmetic derivative''' of an integer (more specifically, the\n'''Lagarias arithmetic derivative''') is a function defined for integers, based on prime\nfactorization, by analogy with the product rule for the derivative of a function that is\nused in mathematical analysis. Accordingly, for natural numbers n, the arithmetic \nderivative D(n) is defined as follows:\n\n;*D(0) = D(1) = 0.\n;*D(p) = 1 for any prime p.\n;*D(mn) = D(m)n + mD(n) for any m,n N. (Leibniz rule for derivatives).\n\nAdditionally, for negative integers the arithmetic derivative may be defined as -D(-n) (n < 0).\n\n; Examples\n\nD(2) = 1 and D(3) = 1 (both are prime) so if mn = 2 * 3, D(6) = (1)(3) + (1)(2) = 5.\n\nD(9) = D(3)(3) + D(3)(3) = 6\n\nD(27) = D(3)*9 + D(9)*3 = 9 + 18 = 27\n\nD(30) = D(5)(6) + D(6)(5) = 6 + 5 * 5 = 31.\n\n; Task\n\nFind and show the arithmetic derivatives for -99 through 100.\n\n; Stretch task\n\nFind (the arithmetic derivative of 10^m) then divided by 7, where m is from 1 to 20.\n\n; See also\n\n;* OEIS:A003415 - a(n) = n' = arithmetic derivative of n.\n;*Wikipedia: Arithmetic Derivative\n\n\n", "solution": "from sympy.ntheory import factorint\n\ndef D(n):\n if n < 0:\n return -D(-n)\n elif n < 2:\n return 0\n else:\n fdict = factorint(n)\n if len(fdict) == 1 and 1 in fdict: # is prime\n return 1\n return sum([n * e // p for p, e in fdict.items()])\n\nfor n in range(-99, 101):\n print('{:5}'.format(D(n)), end='\\n' if n % 10 == 0 else '')\n\nprint()\nfor m in range(1, 21):\n print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))\n\n"} {"title": "Arithmetic evaluation", "language": "Python", "task": "Create a program which parses and evaluates arithmetic expressions.\n;Requirements:\n* An abstract-syntax tree (AST) for the expression must be created from parsing the input. \n* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) \n* The expression will be a string or list of symbols like \"(1+3)*7\". \n* The four symbols + - * / must be supported as binary operators with conventional precedence rules. \n* Precedence-control parentheses must also be supported.\n\n\n;Note:\nFor those who don't remember, mathematical precedence is as follows:\n* Parentheses\n* Multiplication/Division (left to right)\n* Addition/Subtraction (left to right)\n\n\n;C.f: \n* [[24 game Player]].\n* [[Parsing/RPN calculator algorithm]].\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "import operator\n\nclass AstNode(object):\n def __init__( self, opr, left, right ):\n self.opr = opr\n self.l = left\n self.r = right\n\n def eval(self):\n return self.opr(self.l.eval(), self.r.eval())\n\nclass LeafNode(object):\n def __init__( self, valStrg ):\n self.v = int(valStrg)\n\n def eval(self):\n return self.v\n\nclass Yaccer(object):\n def __init__(self):\n self.operstak = []\n self.nodestak =[]\n self.__dict__.update(self.state1)\n\n def v1( self, valStrg ):\n # Value String\n self.nodestak.append( LeafNode(valStrg))\n self.__dict__.update(self.state2)\n #print 'push', valStrg\n\n def o2( self, operchar ):\n # Operator character or open paren in state1\n def openParen(a,b):\n return 0\t\t# function should not be called\n\n opDict= { '+': ( operator.add, 2, 2 ),\n '-': (operator.sub, 2, 2 ),\n '*': (operator.mul, 3, 3 ),\n '/': (operator.div, 3, 3 ),\n '^': ( pow, 4, 5 ), # right associative exponentiation for grins\n '(': ( openParen, 0, 8 )\n }\n operPrecidence = opDict[operchar][2]\n self.redeuce(operPrecidence)\n\n self.operstak.append(opDict[operchar])\n self.__dict__.update(self.state1)\n # print 'pushop', operchar\n\n def syntaxErr(self, char ):\n # Open Parenthesis \n print 'parse error - near operator \"%s\"' %char\n\n def pc2( self,operchar ):\n # Close Parenthesis\n # reduce node until matching open paren found \n self.redeuce( 1 )\n if len(self.operstak)>0:\n self.operstak.pop()\t\t# pop off open parenthesis\n else:\n print 'Error - no open parenthesis matches close parens.'\n self.__dict__.update(self.state2)\n\n def end(self):\n self.redeuce(0)\n return self.nodestak.pop()\n\n def redeuce(self, precidence):\n while len(self.operstak)>0:\n tailOper = self.operstak[-1]\n if tailOper[1] < precidence: break\n\n tailOper = self.operstak.pop()\n vrgt = self.nodestak.pop()\n vlft= self.nodestak.pop()\n self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))\n # print 'reduce'\n\n state1 = { 'v': v1, 'o':syntaxErr, 'po':o2, 'pc':syntaxErr }\n state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr, 'pc':pc2 }\n\n\ndef Lex( exprssn, p ):\n bgn = None\n cp = -1\n for c in exprssn:\n cp += 1\n if c in '+-/*^()': # throw in exponentiation (^)for grins\n if bgn is not None:\n p.v(p, exprssn[bgn:cp])\n bgn = None\n if c=='(': p.po(p, c)\n elif c==')':p.pc(p, c)\n else: p.o(p, c)\n elif c in ' \\t':\n if bgn is not None:\n p.v(p, exprssn[bgn:cp])\n bgn = None\n elif c in '0123456789':\n if bgn is None:\n bgn = cp\n else:\n print 'Invalid character in expression'\n if bgn is not None:\n p.v(p, exprssn[bgn:cp])\n bgn = None\n \n if bgn is not None:\n p.v(p, exprssn[bgn:cp+1])\n bgn = None\n return p.end()\n\n\nexpr = raw_input(\"Expression:\")\nastTree = Lex( expr, Yaccer())\nprint expr, '=',astTree.eval()"} {"title": "Arithmetic numbers", "language": "Python", "task": "Definition\nA positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer.\n\nClearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5.\n\n;Example\n30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer. \n\n;Task\nCalculate and show here:\n\n1. The first 100 arithmetic numbers.\n\n2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000.\n\n3. How many of the first '''x''' arithmetic numbers are composite.\n\nNote that, technically, the arithmetic number '''1''' is neither prime nor composite.\n\n;Stretch\nCarry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000.\n\n;References\n\n* Wikipedia: Arithmetic number\n* OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer\n\n", "solution": "def factors(n: int):\n f = set([1, n])\n i = 2\n while True:\n j = n // i\n if j < i:\n break\n if i * j == n:\n f.add(i)\n f.add(j)\n i += 1\n return f\n\narithmetic_count = 0\ncomposite_count = 0\nn = 1\nwhile arithmetic_count <= 1000000:\n f = factors(n)\n if (sum(f)/len(f)).is_integer():\n arithmetic_count += 1\n if len(f) > 2:\n composite_count += 1\n if arithmetic_count <= 100:\n print(f'{n:3d} ', end='')\n if arithmetic_count % 10 == 0:\n print()\n if arithmetic_count in (1000, 10000, 100000, 1000000):\n print(f'\\n{arithmetic_count}th arithmetic number is {n}')\n print(f'Number of composite arithmetic numbers <= {n}: {composite_count}')\n n += 1"} {"title": "Ascending primes", "language": "Python", "task": "Generate and show all primes with strictly ascending decimal digits.\n\nAside: Try solving without peeking at existing solutions. I had a weird idea for generating\na prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial\nbut generating them quickly is at least mildly interesting.\nTip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is\nat least one significantly better and much faster way, needing a mere 511 odd/prime tests.\n\n\n;See also\n;* OEIS:A052015 - Primes with distinct digits in ascending order\n\n\n;Related:\n*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)\n*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)\n\n\n", "solution": "from sympy import isprime\n\ndef ascending(x=0):\n for y in range(x*10 + (x%10) + 1, x*10 + 10):\n yield from ascending(y)\n yield(y)\n\nprint(sorted(x for x in ascending() if isprime(x)))"} {"title": "Ascending primes", "language": "Python from Pascal", "task": "Generate and show all primes with strictly ascending decimal digits.\n\nAside: Try solving without peeking at existing solutions. I had a weird idea for generating\na prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial\nbut generating them quickly is at least mildly interesting.\nTip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is\nat least one significantly better and much faster way, needing a mere 511 odd/prime tests.\n\n\n;See also\n;* OEIS:A052015 - Primes with distinct digits in ascending order\n\n\n;Related:\n*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)\n*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)\n\n\n", "solution": "def isprime(n):\n if n == 2: return True\n if n == 1 or n % 2 == 0: return False\n root1 = int(n**0.5) + 1;\n for k in range(3, root1, 2):\n if n % k == 0: return False\n return True\n\nqueue = [k for k in range(1, 10)]\nprimes = []\n\nwhile queue:\n n = queue.pop(0)\n if isprime(n):\n primes.append(n)\n queue.extend(n * 10 + k for k in range(n % 10 + 1, 10))\n\nprint(primes)"} {"title": "Associative array/Merging", "language": "Python", "task": "Define two associative arrays, where one represents the following \"base\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 12.75\n|-\n| \"color\" || \"yellow\"\n|}\n\nAnd the other represents \"update\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\n", "solution": "As of Python 3.5, this can be solved with the dictionary unpacking operator.\n"} {"title": "Associative array/Merging", "language": "Python 3.5+", "task": "Define two associative arrays, where one represents the following \"base\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 12.75\n|-\n| \"color\" || \"yellow\"\n|}\n\nAnd the other represents \"update\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\n", "solution": "base = {\"name\":\"Rocket Skates\", \"price\":12.75, \"color\":\"yellow\"}\nupdate = {\"price\":15.25, \"color\":\"red\", \"year\":1974}\n\nresult = {**base, **update}\n\nprint(result)"} {"title": "Attractive numbers", "language": "Python 2.7.12", "task": "A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.\n\n\n;Example:\nThe number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.\n\n\n;Task:\nShow sequence items up to '''120'''.\n\n\n;Reference:\n:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.\n\n", "solution": "from sympy import sieve # library for primes\n\ndef get_pfct(n): \n\ti = 2; factors = []\n\twhile i * i <= n:\n\t\tif n % i:\n\t\t\ti += 1\n\t\telse:\n\t\t\tn //= i\n\t\t\tfactors.append(i)\n\tif n > 1:\n\t\tfactors.append(n)\n\treturn len(factors) \n\nsieve.extend(110) # first 110 primes...\nprimes=sieve._list\n\npool=[]\n\nfor each in xrange(0,121):\n\tpool.append(get_pfct(each))\n\nfor i,each in enumerate(pool):\n\tif each in primes:\n\t\tprint i,"} {"title": "Attractive numbers", "language": "Python 3.7", "task": "A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.\n\n\n;Example:\nThe number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.\n\n\n;Task:\nShow sequence items up to '''120'''.\n\n\n;Reference:\n:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.\n\n", "solution": "'''Attractive numbers'''\n\nfrom itertools import chain, count, takewhile\nfrom functools import reduce\n\n\n# attractiveNumbers :: () -> [Int]\ndef attractiveNumbers():\n '''A non-finite stream of attractive numbers.\n (OEIS A063989)\n '''\n return filter(\n compose(\n isPrime,\n len,\n primeDecomposition\n ),\n count(1)\n )\n\n\n# TEST ----------------------------------------------------\ndef main():\n '''Attractive numbers drawn from the range [1..120]'''\n for row in chunksOf(15)(list(\n takewhile(\n lambda x: 120 >= x,\n attractiveNumbers()\n )\n )):\n print(' '.join(map(\n compose(justifyRight(3)(' '), str),\n row\n )))\n\n\n# GENERAL FUNCTIONS ---------------------------------------\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n '''A series of lists of length n, subdividing the\n contents of xs. Where the length of xs is not evenly\n divible, the final list will be shorter than n.\n '''\n return lambda xs: reduce(\n lambda a, i: a + [xs[i:n + i]],\n range(0, len(xs), n), []\n ) if 0 < n else []\n\n\n# compose :: ((a -> a), ...) -> (a -> a)\ndef compose(*fs):\n '''Composition, from right to left,\n of a series of functions.\n '''\n return lambda x: reduce(\n lambda a, f: f(a),\n fs[::-1], x\n )\n\n\n# We only need light implementations\n# of prime functions here:\n\n# primeDecomposition :: Int -> [Int]\ndef primeDecomposition(n):\n '''List of integers representing the\n prime decomposition of n.\n '''\n def go(n, p):\n return [p] + go(n // p, p) if (\n 0 == n % p\n ) else []\n return list(chain.from_iterable(map(\n lambda p: go(n, p) if isPrime(p) else [],\n range(2, 1 + n)\n )))\n\n\n# isPrime :: Int -> Bool\ndef isPrime(n):\n '''True if n is prime.'''\n if n in (2, 3):\n return True\n if 2 > n or 0 == n % 2:\n return False\n if 9 > n:\n return True\n if 0 == n % 3:\n return False\n\n return not any(map(\n lambda x: 0 == n % x or 0 == n % (2 + x),\n range(5, 1 + int(n ** 0.5), 6)\n ))\n\n\n# justifyRight :: Int -> Char -> String -> String\ndef justifyRight(n):\n '''A string padded at left to length n,\n using the padding character c.\n '''\n return lambda c: lambda s: s.rjust(n, c)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Average loop length", "language": "Python from C", "task": "Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.\n\n\n;Task:\nWrite a program or a script that estimates, for each N, the average length until the first such repetition.\n\nAlso calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.\n\n\nThis problem comes from the end of Donald Knuth's Christmas tree lecture 2011.\n\nExample of expected output:\n\n N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.4992 1.5000 ( 0.05%)\n 3 1.8784 1.8889 ( 0.56%)\n 4 2.2316 2.2188 ( 0.58%)\n 5 2.4982 2.5104 ( 0.49%)\n 6 2.7897 2.7747 ( 0.54%)\n 7 3.0153 3.0181 ( 0.09%)\n 8 3.2429 3.2450 ( 0.07%)\n 9 3.4536 3.4583 ( 0.14%)\n 10 3.6649 3.6602 ( 0.13%)\n 11 3.8091 3.8524 ( 1.12%)\n 12 3.9986 4.0361 ( 0.93%)\n 13 4.2074 4.2123 ( 0.12%)\n 14 4.3711 4.3820 ( 0.25%)\n 15 4.5275 4.5458 ( 0.40%)\n 16 4.6755 4.7043 ( 0.61%)\n 17 4.8877 4.8579 ( 0.61%)\n 18 4.9951 5.0071 ( 0.24%)\n 19 5.1312 5.1522 ( 0.41%)\n 20 5.2699 5.2936 ( 0.45%)\n\n", "solution": "from __future__ import division # Only necessary for Python 2.X\nfrom math import factorial\nfrom random import randrange\n\nMAX_N = 20\nTIMES = 1000000\n\ndef analytical(n):\n\treturn sum(factorial(n) / pow(n, i) / factorial(n -i) for i in range(1, n+1))\n\ndef test(n, times):\n count = 0\n for i in range(times):\n x, bits = 1, 0\n while not (bits & x):\n count += 1\n bits |= x\n x = 1 << randrange(n)\n return count / times\n\nif __name__ == '__main__':\n print(\" n\\tavg\\texp.\\tdiff\\n-------------------------------\")\n for n in range(1, MAX_N+1):\n avg = test(n, TIMES)\n theory = analytical(n)\n diff = (avg / theory - 1) * 100\n print(\"%2d %8.4f %8.4f %6.3f%%\" % (n, avg, theory, diff))"} {"title": "Averages/Mean angle", "language": "Python 2.6+", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": ">>> from cmath import rect, phase\n>>> from math import radians, degrees\n>>> def mean_angle(deg):\n... return degrees(phase(sum(rect(1, radians(d)) for d in deg)/len(deg)))\n... \n>>> for angles in [[350, 10], [90, 180, 270, 360], [10, 20, 30]]:\n... print('The mean angle of', angles, 'is:', round(mean_angle(angles), 12), 'degrees')\n... \nThe mean angle of [350, 10] is: -0.0 degrees\nThe mean angle of [90, 180, 270, 360] is: -90.0 degrees\nThe mean angle of [10, 20, 30] is: 20.0 degrees\n>>> "} {"title": "Averages/Pythagorean means", "language": "Python 3", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "from operator import mul\nfrom functools import reduce\n\n\ndef amean(num):\n return sum(num) / len(num)\n\n\ndef gmean(num):\n return reduce(mul, num, 1)**(1 / len(num))\n\n\ndef hmean(num):\n return len(num) / sum(1 / n for n in num)\n\n\nnumbers = range(1, 11) # 1..10\na, g, h = amean(numbers), gmean(numbers), hmean(numbers)\nprint(a, g, h)\nassert a >= g >= h"} {"title": "Averages/Root mean square", "language": "Python 3", "task": "Task\n\nCompute the Root mean square of the numbers 1..10.\n\n\nThe ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''.\n\nThe RMS is calculated as the mean of the squares of the numbers, square-rooted:\n\n\n::: x_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. \n\n\n;See also\n\n{{Related tasks/Statistical measures}}\n\n\n", "solution": "from functools import (reduce)\nfrom math import (sqrt)\n\n\n# rootMeanSquare :: [Num] -> Float\ndef rootMeanSquare(xs):\n return sqrt(reduce(lambda a, x: a + x * x, xs, 0) / len(xs))\n\n\nprint(\n rootMeanSquare([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n)"} {"title": "Babbage problem", "language": "Python", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "# Lines that start by # are a comments:\n# they will be ignored by the machine\n\nn=0 # n is a variable and its value is 0\n\n# we will increase its value by one until\n# its square ends in 269,696\n\nwhile n**2 % 1000000 != 269696:\n\n # n**2 -> n squared\n # % -> 'modulo' or remainder after division\n # != -> not equal to\n \n n += 1 # += -> increase by a certain number\n\nprint(n) # prints n\n"} {"title": "Babbage problem", "language": "Python 3.7", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "'''Babbage problem'''\n\nfrom math import (floor, sqrt)\nfrom itertools import (islice)\n\n\n# squaresWithSuffix :: Int -> Gen [Int]\ndef squaresWithSuffix(n):\n '''Non finite stream of squares with a given suffix.'''\n stem = 10 ** len(str(n))\n i = 0\n while True:\n i = until(lambda x: isPerfectSquare(n + (stem * x)))(\n succ\n )(i)\n yield n + (stem * i)\n i = succ(i)\n\n\n# isPerfectSquare :: Int -> Bool\ndef isPerfectSquare(n):\n '''True if n is a perfect square.'''\n r = sqrt(n)\n return r == floor(r)\n\n\n# TEST ----------------------------------------------------\n\n# main :: IO ()\ndef main():\n '''Smallest positive integers whose squares end in the digits 269,696'''\n print(\n fTable(main.__doc__ + ':\\n')(\n lambda n: str(int(sqrt(n))) + '^2'\n )(repr)(identity)(\n take(10)(squaresWithSuffix(269696))\n )\n )\n\n\n# GENERIC -------------------------------------------------\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value.\n For numeric types, (1 +).\n '''\n return 1 + x if isinstance(x, int) else (\n chr(1 + ord(x))\n )\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n\n\n# until :: (a -> Bool) -> (a -> a) -> a -> a\ndef until(p):\n '''The result of repeatedly applying f until p holds.\n The initial seed value is x.\n '''\n def go(f, x):\n v = x\n while not p(v):\n v = f(v)\n return v\n return lambda f: lambda x: go(f, x)\n\n\n# FORMATTING ----------------------------------------------\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Babylonian spiral", "language": "Python", "task": "The '''Babylonian spiral''' is a sequence of points in the plane that are created so as to\ncontinuously minimally increase in vector length and minimally bend in vector direction,\nwhile always moving from point to point on strictly integral coordinates. Of the two criteria\nof length and angle, the length has priority.\n\n; Examples\n\nP(1) and P(2) are defined to be at (x = 0, y = 0) and (x = 0, y = 1). The first vector is\nfrom P(1) to P(2). It is vertical and of length 1. Note that the square of that length is 1.\n\nNext in sequence is the vector from P(2) to P(3). This should be the smallest distance to a\npoint with integral (x, y) which is longer than the last vector (that is, 1). It should also bend clockwise\nmore than zero radians, but otherwise to the least degree.\n\nThe point chosen for P(3) that fits criteria is (x = 1, y = 2). Note the length of the vector\nfrom P(2) to P(3) is 2, which squared is 2. The lengths of the vectors thus determined can be given by a sorted\nlist of possible sums of two integer squares, including 0 as a square.\n\n; Task\n\nFind and show the first 40 (x, y) coordinates of the Babylonian spiral.\n\n; Stretch task\n\nShow in your program how to calculate and plot the first 10000 points in the sequence. Your result\nshould look similar to the graph shown at the OEIS: [[File:From_oies_A@97346_A297347_plot2a.png]]\n\n; See also\n\n;* OEIS:A256111 - squared distance to the origin of the n-th vertex on a Babylonian Spiral.\n;* OEIS:A297346 - List of successive x-coordinates in the Babylonian Spiral.\n;* OEIS:A297347 - List of successive y-coordinates in the Babylonian Spiral.\n\n\n\n", "solution": "\"\"\" Rosetta Code task rosettacode.org/wiki/Babylonian_spiral \"\"\"\n\nfrom itertools import accumulate\nfrom math import isqrt, atan2, tau\nfrom matplotlib.pyplot import axis, plot, show\n\n\nsquare_cache = []\n\ndef babylonian_spiral(nsteps):\n \"\"\"\n Get the points for each step along a Babylonia spiral of `nsteps` steps.\n Origin is at (0, 0) with first step one unit in the positive direction along\n the vertical (y) axis. The other points are selected to have integer x and y\n coordinates, progressively concatenating the next longest vector with integer\n x and y coordinates on the grid. The direction change of the new vector is\n chosen to be nonzero and clockwise in a direction that minimizes the change\n in direction from the previous vector.\n \n See also: oeis.org/A256111, oeis.org/A297346, oeis.org/A297347\n \"\"\"\n if len(square_cache) <= nsteps:\n square_cache.extend([x * x for x in range(len(square_cache), nsteps)])\n xydeltas = [(0, 0), (0, 1)]\n \u03b4squared = 1\n for _ in range(nsteps - 2):\n x, y = xydeltas[-1]\n \u03b8 = atan2(y, x)\n candidates = []\n while not candidates:\n \u03b4squared += 1\n for i, a in enumerate(square_cache):\n if a > \u03b4squared // 2:\n break\n for j in range(isqrt(\u03b4squared) + 1, 0, -1):\n b = square_cache[j]\n if a + b < \u03b4squared:\n break\n if a + b == \u03b4squared:\n candidates.extend([(i, j), (-i, j), (i, -j), (-i, -j), (j, i), (-j, i),\n (j, -i), (-j, -i)])\n\n p = min(candidates, key=lambda d: (\u03b8 - atan2(d[1], d[0])) % tau)\n xydeltas.append(p)\n\n return list(accumulate(xydeltas, lambda a, b: (a[0] + b[0], a[1] + b[1])))\n\n\npoints10000 = babylonian_spiral(10000)\nprint(\"The first 40 Babylonian spiral points are:\")\nfor i, p in enumerate(points10000[:40]):\n print(str(p).ljust(10), end = '\\n' if (i + 1) % 10 == 0 else '')\n\n# stretch portion of task\nplot(*zip(*points10000), color=\"navy\", linewidth=0.2)\naxis('scaled')\nshow()\n"} {"title": "Balanced brackets", "language": "Python", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": ">>> def gen(N):\n... txt = ['[', ']'] * N\n... random.shuffle( txt )\n... return ''.join(txt)\n... \n>>> def balanced(txt):\n... braced = 0\n... for ch in txt:\n... if ch == '[': braced += 1\n... if ch == ']':\n... braced -= 1\n... if braced < 0: return False\n... return braced == 0\n... \n>>> for txt in (gen(N) for N in range(10)):\n... print (\"%-22r is%s balanced\" % (txt, '' if balanced(txt) else ' not'))\n... \n'' is balanced\n'[]' is balanced\n'[][]' is balanced\n'][[[]]' is not balanced\n'[]][[][]' is not balanced\n'[][[][]]][' is not balanced\n'][]][][[]][[' is not balanced\n'[[]]]]][]][[[[' is not balanced\n'[[[[]][]]][[][]]' is balanced\n'][[][[]]][]]][[[[]' is not balanced"} {"title": "Balanced brackets", "language": "Python 3.2", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": ">>> from itertools import accumulate\n>>> from random import shuffle\n>>> def gen(n):\n... txt = list('[]' * n)\n... shuffle(txt)\n... return ''.join(txt)\n...\n>>> def balanced(txt):\n... brackets = ({'[': 1, ']': -1}.get(ch, 0) for ch in txt)\n... return all(x>=0 for x in accumulate(brackets))\n...\n>>> for txt in (gen(N) for N in range(10)):\n... print (\"%-22r is%s balanced\" % (txt, '' if balanced(txt) else ' not'))\n...\n'' is balanced\n'][' is not balanced\n'[]][' is not balanced\n']][[[]' is not balanced\n'][[][][]' is not balanced\n'[[[][][]]]' is balanced\n'][[[][][]][]' is not balanced\n'][]][][[]][[][' is not balanced\n'][[]]][][[]][[[]' is not balanced\n'][[][[]]]][[[]][][' is not balanced"} {"title": "Balanced ternary", "language": "Python from Common Lisp", "task": "Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1. \n\n\n;Examples:\nDecimal 11 = 32 + 31 - 30, thus it can be written as \"++-\"\n\nDecimal 6 = 32 - 31 + 0 x 30, thus it can be written as \"+-0\"\n\n\n;Task:\nImplement balanced ternary representation of integers with the following:\n# Support arbitrarily large integers, both positive and negative;\n# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).\n# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.\n# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.\n# Make your implementation efficient, with a reasonable definition of \"efficient\" (and with a reasonable definition of \"reasonable\").\n\n\n'''Test case''' With balanced ternaries ''a'' from string \"+-0++0+\", ''b'' from native integer -436, ''c'' \"+-++-\":\n* write out ''a'', ''b'' and ''c'' in decimal notation;\n* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.\n\n\n'''Note:''' The pages floating point balanced ternary.\n\n", "solution": "class BalancedTernary:\n # Represented as a list of 0, 1 or -1s, with least significant digit first.\n\n str2dig = {'+': 1, '-': -1, '0': 0} # immutable\n dig2str = {1: '+', -1: '-', 0: '0'} # immutable\n table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) # immutable\n\n def __init__(self, inp):\n if isinstance(inp, str):\n self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)]\n elif isinstance(inp, int):\n self.digits = self._int2ternary(inp)\n elif isinstance(inp, BalancedTernary):\n self.digits = list(inp.digits)\n elif isinstance(inp, list):\n if all(d in (0, 1, -1) for d in inp):\n self.digits = list(inp)\n else:\n raise ValueError(\"BalancedTernary: Wrong input digits.\")\n else:\n raise TypeError(\"BalancedTernary: Wrong constructor input.\")\n\n @staticmethod\n def _int2ternary(n):\n if n == 0: return []\n if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3)\n if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3)\n if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3)\n\n def to_int(self):\n return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0)\n\n def __repr__(self):\n if not self.digits: return \"0\"\n return \"\".join(BalancedTernary.dig2str[d] for d in reversed(self.digits))\n\n @staticmethod\n def _neg(digs):\n return [-d for d in digs]\n\n def __neg__(self):\n return BalancedTernary(BalancedTernary._neg(self.digits))\n\n @staticmethod\n def _add(a, b, c=0):\n if not (a and b):\n if c == 0:\n return a or b\n else:\n return BalancedTernary._add([c], a or b)\n else:\n (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c]\n res = BalancedTernary._add(a[1:], b[1:], c)\n # trim leading zeros\n if res or d != 0:\n return [d] + res\n else:\n return res\n\n def __add__(self, b):\n return BalancedTernary(BalancedTernary._add(self.digits, b.digits))\n\n def __sub__(self, b):\n return self + (-b)\n\n @staticmethod\n def _mul(a, b):\n if not (a and b):\n return []\n else:\n if a[0] == -1: x = BalancedTernary._neg(b)\n elif a[0] == 0: x = []\n elif a[0] == 1: x = b\n else: assert False\n y = [0] + BalancedTernary._mul(a[1:], b)\n return BalancedTernary._add(x, y)\n\n def __mul__(self, b):\n return BalancedTernary(BalancedTernary._mul(self.digits, b.digits))\n\n\ndef main():\n a = BalancedTernary(\"+-0++0+\")\n print \"a:\", a.to_int(), a\n\n b = BalancedTernary(-436)\n print \"b:\", b.to_int(), b\n\n c = BalancedTernary(\"+-++-\")\n print \"c:\", c.to_int(), c\n\n r = a * (b - c)\n print \"a * (b - c):\", r.to_int(), r\n\nmain()"} {"title": "Barnsley fern", "language": "Python", "task": "A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).\n\n\n;Task:\nCreate this fractal fern, using the following transformations:\n* f1 (chosen 1% of the time)\n xn + 1 = 0\n yn + 1 = 0.16 yn\n\n* f2 (chosen 85% of the time)\n xn + 1 = 0.85 xn + 0.04 yn\n yn + 1 = -0.04 xn + 0.85 yn + 1.6\n\n* f3 (chosen 7% of the time)\n xn + 1 = 0.2 xn - 0.26 yn\n yn + 1 = 0.23 xn + 0.22 yn + 1.6\n\n* f4 (chosen 7% of the time)\n xn + 1 = -0.15 xn + 0.28 yn\n yn + 1 = 0.26 xn + 0.24 yn + 0.44.\n\nStarting position: x = 0, y = 0\n\n", "solution": "import random\nfrom PIL import Image\n\n\nclass BarnsleyFern(object):\n def __init__(self, img_width, img_height, paint_color=(0, 150, 0),\n bg_color=(255, 255, 255)):\n self.img_width, self.img_height = img_width, img_height\n self.paint_color = paint_color\n self.x, self.y = 0, 0\n self.age = 0\n\n self.fern = Image.new('RGB', (img_width, img_height), bg_color)\n self.pix = self.fern.load()\n self.pix[self.scale(0, 0)] = paint_color\n\n def scale(self, x, y):\n h = (x + 2.182)*(self.img_width - 1)/4.8378\n k = (9.9983 - y)*(self.img_height - 1)/9.9983\n return h, k\n\n def transform(self, x, y):\n rand = random.uniform(0, 100)\n if rand < 1:\n return 0, 0.16*y\n elif 1 <= rand < 86:\n return 0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.6\n elif 86 <= rand < 93:\n return 0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6\n else:\n return -0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44\n\n def iterate(self, iterations):\n for _ in range(iterations):\n self.x, self.y = self.transform(self.x, self.y)\n self.pix[self.scale(self.x, self.y)] = self.paint_color\n self.age += iterations\n\nfern = BarnsleyFern(500, 500)\nfern.iterate(1000000)\nfern.fern.show()\n"} {"title": "Base64 decode data", "language": "Python", "task": "See [[Base64 encode data]]. \n\nNow write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. \n\nWhen working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.\n\n", "solution": "import base64\ndata = 'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g='\nprint(base64.b64decode(data).decode('utf-8'))\n"} {"title": "Bell numbers", "language": "Python 2.7", "task": "Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.\n\n\n;So:\n\n:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''\n\n:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''\n\n:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''\n\n:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''\n\n: and so on.\n\n\nA simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.\n\n\n;Task:\n\nWrite a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence. \n\nIf you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.\n\n\n;See also:\n\n:* '''OEIS:A000110 Bell or exponential numbers'''\n:* '''OEIS:A011971 Aitken's array'''\n\n", "solution": "def bellTriangle(n):\n tri = [None] * n\n for i in xrange(n):\n tri[i] = [0] * i\n tri[1][0] = 1\n for i in xrange(2, n):\n tri[i][0] = tri[i - 1][i - 2]\n for j in xrange(1, i):\n tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1]\n return tri\n\ndef main():\n bt = bellTriangle(51)\n print \"First fifteen and fiftieth Bell numbers:\"\n for i in xrange(1, 16):\n print \"%2d: %d\" % (i, bt[i][0])\n print \"50:\", bt[50][0]\n print\n print \"The first ten rows of Bell's triangle:\"\n for i in xrange(1, 11):\n print bt[i]\n\nmain()"} {"title": "Bell numbers", "language": "Python 3.7", "task": "Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.\n\n\n;So:\n\n:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''\n\n:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''\n\n:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''\n\n:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''\n\n: and so on.\n\n\nA simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.\n\n\n;Task:\n\nWrite a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence. \n\nIf you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.\n\n\n;See also:\n\n:* '''OEIS:A000110 Bell or exponential numbers'''\n:* '''OEIS:A011971 Aitken's array'''\n\n", "solution": "'''Bell numbers'''\n\nfrom itertools import accumulate, chain, islice\nfrom operator import add, itemgetter\nfrom functools import reduce\n\n\n# bellNumbers :: [Int]\ndef bellNumbers():\n '''Bell or exponential numbers.\n A000110\n '''\n return map(itemgetter(0), bellTriangle())\n\n\n# bellTriangle :: [[Int]]\ndef bellTriangle():\n '''Bell triangle.'''\n return map(\n itemgetter(1),\n iterate(\n compose(\n bimap(last)(identity),\n list, uncurry(scanl(add))\n )\n )((1, [1]))\n )\n\n\n# ------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Tests'''\n showIndex = compose(repr, succ, itemgetter(0))\n showValue = compose(repr, itemgetter(1))\n print(\n fTable(\n 'First fifteen Bell numbers:'\n )(showIndex)(showValue)(identity)(list(\n enumerate(take(15)(bellNumbers()))\n ))\n )\n\n print('\\nFiftieth Bell number:')\n bells = bellNumbers()\n drop(49)(bells)\n print(\n next(bells)\n )\n\n print(\n fTable(\n \"\\nFirst 10 rows of Bell's triangle:\"\n )(showIndex)(showValue)(identity)(list(\n enumerate(take(10)(bellTriangle()))\n ))\n )\n\n\n# ------------------------ GENERIC ------------------------\n\n# bimap :: (a -> b) -> (c -> d) -> (a, c) -> (b, d)\ndef bimap(f):\n '''Tuple instance of bimap.\n A tuple of the application of f and g to the\n first and second values respectively.\n '''\n def go(g):\n def gox(x):\n return (f(x), g(x))\n return gox\n return go\n\n\n# compose :: ((a -> a), ...) -> (a -> a)\ndef compose(*fs):\n '''Composition, from right to left,\n of a series of functions.\n '''\n def go(f, g):\n def fg(x):\n return f(g(x))\n return fg\n return reduce(go, fs, identity)\n\n\n# drop :: Int -> [a] -> [a]\n# drop :: Int -> String -> String\ndef drop(n):\n '''The sublist of xs beginning at\n (zero-based) index n.\n '''\n def go(xs):\n if isinstance(xs, (list, tuple, str)):\n return xs[n:]\n else:\n take(n)(xs)\n return xs\n return go\n\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def gox(xShow):\n def gofx(fxShow):\n def gof(f):\n def goxs(xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n\n def arrowed(x, y):\n return y.rjust(w, ' ') + ' -> ' + fxShow(f(x))\n return s + '\\n' + '\\n'.join(\n map(arrowed, xs, ys)\n )\n return goxs\n return gof\n return gofx\n return gox\n\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# iterate :: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n '''An infinite list of repeated\n applications of f to x.\n '''\n def go(x):\n v = x\n while True:\n yield v\n v = f(v)\n return go\n\n\n# last :: [a] -> a\ndef last(xs):\n '''The last element of a non-empty list.'''\n return xs[-1]\n\n\n# scanl :: (b -> a -> b) -> b -> [a] -> [b]\ndef scanl(f):\n '''scanl is like reduce, but returns a succession of\n intermediate values, building from the left.\n '''\n def go(a):\n def g(xs):\n return accumulate(chain([a], xs), f)\n return g\n return go\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value.\n For numeric types, (1 +).\n '''\n return 1 + x\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n def go(xs):\n return (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n return go\n\n\n# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n '''A function over a tuple,\n derived from a curried function.\n '''\n def go(tpl):\n return f(tpl[0])(tpl[1])\n return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Benford's law", "language": "Python", "task": "{{Wikipedia|Benford's_law}}\n\n\n'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. \n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. \n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit d (d \\in \\{1, \\ldots, 9\\}) occurs with probability\n\n:::: P(d) = \\log_{10}(d+1)-\\log_{10}(d) = \\log_{10}\\left(1+\\frac{1}{d}\\right)\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. \n\nYou can generate them or load them from a file; whichever is easiest. \n\nDisplay your actual vs expected distribution.\n\n\n''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n;See also:\n* numberphile.com.\n* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.\n\n", "solution": "from __future__ import division\nfrom itertools import islice, count\nfrom collections import Counter\nfrom math import log10\nfrom random import randint\n\nexpected = [log10(1+1/d) for d in range(1,10)]\n\ndef fib():\n a,b = 1,1\n while True:\n yield a\n a,b = b,a+b\n\n# powers of 3 as a test sequence\ndef power_of_threes():\n return (3**k for k in count(0))\n\ndef heads(s):\n for a in s: yield int(str(a)[0])\n\ndef show_dist(title, s):\n c = Counter(s)\n size = sum(c.values())\n res = [c[d]/size for d in range(1,10)]\n\n print(\"\\n%s Benfords deviation\" % title)\n for r, e in zip(res, expected):\n print(\"%5.1f%% %5.1f%% %5.1f%%\" % (r*100., e*100., abs(r - e)*100.))\n\ndef rand1000():\n while True: yield randint(1,9999)\n\nif __name__ == '__main__':\n show_dist(\"fibbed\", islice(heads(fib()), 1000))\n show_dist(\"threes\", islice(heads(power_of_threes()), 1000))\n\n # just to show that not all kind-of-random sets behave like that\n show_dist(\"random\", islice(heads(rand1000()), 10000))"} {"title": "Best shuffle", "language": "Python", "task": "Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. \n\nA shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.\n\nDisplay the result as follows: \n\n original string, shuffled string, (score) \n\nThe score gives the number of positions whose character value did ''not'' change. \n\n\n;Example:\n tree, eetr, (0)\n\n\n;Test cases:\n abracadabra\n seesaw\n elk\n grrrrrr\n up\n a\n\n\n;Related tasks\n* [[Anagrams/Deranged anagrams]]\n* [[Permutations/Derangements]]\n\n\n\n", "solution": "#!/usr/bin/env python\n\ndef best_shuffle(s):\n # Count the supply of characters.\n from collections import defaultdict\n count = defaultdict(int)\n for c in s:\n count[c] += 1\n\n # Shuffle the characters.\n r = []\n for x in s:\n # Find the best character to replace x.\n best = None\n rankb = -2\n for c, rankc in count.items():\n # Prefer characters with more supply.\n # (Save characters with less supply.)\n # Avoid identical characters.\n if c == x: rankc = -1\n if rankc > rankb:\n best = c\n rankb = rankc\n\n # Add character to list. Remove it from supply.\n r.append(best)\n count[best] -= 1\n if count[best] >= 0: del count[best]\n\n # If the final letter became stuck (as \"ababcd\" became \"bacabd\",\n # and the final \"d\" became stuck), then fix it.\n i = len(s) - 1\n if r[i] == s[i]:\n for j in range(i):\n if r[i] != s[j] and r[j] != s[i]:\n r[i], r[j] = r[j], r[i]\n break\n\n # Convert list to string. PEP 8, \"Style Guide for Python Code\",\n # suggests that ''.join() is faster than + when concatenating\n # many strings. See http://www.python.org/dev/peps/pep-0008/\n r = ''.join(r)\n\n score = sum(x == y for x, y in zip(r, s))\n\n return (r, score)\n\nfor s in \"abracadabra\", \"seesaw\", \"elk\", \"grrrrrr\", \"up\", \"a\":\n shuffled, score = best_shuffle(s)\n print(\"%s, %s, (%d)\" % (s, shuffled, score))"} {"title": "Bin given limits", "language": "Python", "task": "You are given a list of n ascending, unique numbers which are to form limits\nfor n+1 bins which count how many of a large set of input numbers fall in the\nrange of each bin.\n\n(Assuming zero-based indexing)\n\n bin[0] counts how many inputs are < limit[0]\n bin[1] counts how many inputs are >= limit[0] and < limit[1]\n ..''\n bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]\n bin[n] counts how many inputs are >= limit[n-1]\n\n;Task:\nThe task is to create a function that given the ascending limits and a stream/\nlist of numbers, will return the bins; together with another function that\ngiven the same list of limits and the binning will ''print the limit of each bin\ntogether with the count of items that fell in the range''.\n\nAssume the numbers to bin are too large to practically sort.\n\n;Task examples:\nPart 1: Bin using the following limits the given input data\n\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n\nPart 2: Bin using the following limits the given input data\n\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n\nShow output here, on this page.\n", "solution": "from bisect import bisect_right\n\ndef bin_it(limits: list, data: list) -> list:\n \"Bin data according to (ascending) limits.\"\n bins = [0] * (len(limits) + 1) # adds under/over range bins too\n for d in data:\n bins[bisect_right(limits, d)] += 1\n return bins\n\ndef bin_print(limits: list, bins: list) -> list:\n print(f\" < {limits[0]:3} := {bins[0]:3}\")\n for lo, hi, count in zip(limits, limits[1:], bins[1:]):\n print(f\">= {lo:3} .. < {hi:3} := {count:3}\")\n print(f\">= {limits[-1]:3} := {bins[-1]:3}\")\n\n\nif __name__ == \"__main__\":\n print(\"RC FIRST EXAMPLE\\n\")\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n bins = bin_it(limits, data)\n bin_print(limits, bins)\n\n print(\"\\nRC SECOND EXAMPLE\\n\")\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n bins = bin_it(limits, data)\n bin_print(limits, bins)"} {"title": "Bioinformatics/Global alignment", "language": "Python from Go", "task": "Global alignment is designed to search for highly similar regions in two or more DNA sequences, where the\nsequences appear in the same order and orientation, fitting the sequences in as pieces in a puzzle.\n\nCurrent DNA sequencers find the sequence for multiple small segments of DNA which have mostly randomly formed by splitting a much larger DNA molecule into shorter segments. When re-assembling such segments of DNA sequences into a larger sequence to form, for example, the DNA coding for the relevant gene, the overlaps between multiple shorter sequences are commonly used to decide how the longer sequence is to be assembled. For example, \"AAGATGGA\", GGAGCGCATC\", and \"ATCGCAATAAGGA\" can be assembled into the sequence \"AAGATGGAGCGCATCGCAATAAGGA\" by noting that \"GGA\" is at the tail of the first string and head of the second string and \"ATC\" likewise is at the tail\nof the second and head of the third string.\n\nWhen looking for the best global alignment in the output strings produced by DNA sequences, there are\ntypically a large number of such overlaps among a large number of sequences. In such a case, the ordering\nthat results in the shortest common superstring is generrally preferred.\n\nFinding such a supersequence is an NP-hard problem, and many algorithms have been proposed to\nshorten calculations, especially when many very long sequences are matched.\n\nThe shortest common superstring as used in bioinfomatics here differs from the string task\n[[Shortest_common_supersequence]]. In that task, a supersequence\nmay have other characters interposed as long as the characters of each subsequence appear in order,\nso that (abcbdab, abdcaba) -> abdcabdab. In this task, (abcbdab, abdcaba) -> abcbdabdcaba.\n\n\n;Task:\n:* Given N non-identical strings of characters A, C, G, and T representing N DNA sequences, find the shortest DNA sequence containing all N sequences.\n\n:* Handle cases where two sequences are identical or one sequence is entirely contained in another.\n\n:* Print the resulting sequence along with its size (its base count) and a count of each base in the sequence.\n\n:* Find the shortest common superstring for the following four examples:\n: \n (\"TA\", \"AAG\", \"TA\", \"GAA\", \"TA\")\n\n (\"CATTAGGG\", \"ATTAG\", \"GGG\", \"TA\")\n\n (\"AAGAUGGA\", \"GGAGCGCAUC\", \"AUCGCAAUAAGGA\")\n\n (\"ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT\",\n \"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT\",\n \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\",\n \"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC\",\n \"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT\",\n \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC\",\n \"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT\",\n \"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n \"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA\")\n\n;Related tasks:\n:* Bioinformatics base count.\n:* Bioinformatics sequence mutation.\n\n", "solution": "import os\n\nfrom collections import Counter\nfrom functools import reduce\nfrom itertools import permutations\n\nBASES = (\"A\", \"C\", \"G\", \"T\")\n\n\ndef deduplicate(sequences):\n \"\"\"Return the set of sequences with those that are a substring\n of others removed too.\"\"\"\n sequences = set(sequences)\n duplicates = set()\n\n for s, t in permutations(sequences, 2):\n if s != t and s in t:\n duplicates.add(s)\n\n return sequences - duplicates\n\n\ndef smash(s, t):\n \"\"\"Return `s` concatenated with `t`. The longest suffix of `s`\n that matches a prefix of `t` will be removed.\"\"\"\n for i in range(len(s)):\n if t.startswith(s[i:]):\n return s[:i] + t\n return s + t\n\n\ndef shortest_superstring(sequences):\n \"\"\"Return the shortest superstring covering all sequences. If\n there are multiple shortest superstrings, an arbitrary\n superstring is returned.\"\"\"\n sequences = deduplicate(sequences)\n shortest = \"\".join(sequences)\n\n for perm in permutations(sequences):\n superstring = reduce(smash, perm)\n if len(superstring) < len(shortest):\n shortest = superstring\n\n return shortest\n\n\ndef shortest_superstrings(sequences):\n \"\"\"Return a list of all shortest superstrings that cover\n `sequences`.\"\"\"\n sequences = deduplicate(sequences)\n\n shortest = set([\"\".join(sequences)])\n shortest_length = sum(len(s) for s in sequences)\n\n for perm in permutations(sequences):\n superstring = reduce(smash, perm)\n superstring_length = len(superstring)\n if superstring_length < shortest_length:\n shortest.clear()\n shortest.add(superstring)\n shortest_length = superstring_length\n elif superstring_length == shortest_length:\n shortest.add(superstring)\n\n return shortest\n\n\ndef print_report(sequence):\n \"\"\"Writes a report to stdout for the given DNA sequence.\"\"\"\n buf = [f\"Nucleotide counts for {sequence}:\\n\"]\n\n counts = Counter(sequence)\n for base in BASES:\n buf.append(f\"{base:>10}{counts.get(base, 0):>12}\")\n\n other = sum(v for k, v in counts.items() if k not in BASES)\n buf.append(f\"{'Other':>10}{other:>12}\")\n\n buf.append(\" \" * 5 + \"_\" * 17)\n buf.append(f\"{'Total length':>17}{sum(counts.values()):>5}\")\n\n print(os.linesep.join(buf), \"\\n\")\n\n\nif __name__ == \"__main__\":\n test_cases = [\n (\"TA\", \"AAG\", \"TA\", \"GAA\", \"TA\"),\n (\"CATTAGGG\", \"ATTAG\", \"GGG\", \"TA\"),\n (\"AAGAUGGA\", \"GGAGCGCAUC\", \"AUCGCAAUAAGGA\"),\n (\n \"ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT\",\n \"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT\",\n \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\",\n \"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC\",\n \"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT\",\n \"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC\",\n \"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT\",\n \"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n \"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n \"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA\",\n ),\n ]\n\n for case in test_cases:\n for superstring in shortest_superstrings(case):\n print_report(superstring)\n\n # or ..\n #\n # for case in test_cases:\n # print_report(shortest_superstring(case))\n #\n # .. if you don't want all possible shortest superstrings.\n"} {"title": "Bioinformatics/Sequence mutation", "language": "Python", "task": "Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:\n# Choosing a random base position in the sequence.\n# Mutate the sequence by doing one of either:\n## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)\n## '''D'''elete the chosen base at the position.\n## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.\n# Randomly generate a test DNA sequence of at least 200 bases\n# \"Pretty print\" the sequence and a count of its size, and the count of each base in the sequence\n# Mutate the sequence ten times.\n# \"Pretty print\" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.\n\n;Extra credit:\n* Give more information on the individual mutations applied.\n* Allow mutations to be weighted and/or chosen.\n", "solution": "import random\nfrom collections import Counter\n\ndef basecount(dna):\n return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n for i, part in enumerate(seq_split(dna, n)):\n print(f\"{i*n:>5}: {part}\")\n print(\"\\n BASECOUNT:\")\n tot = 0\n for base, count in basecount(dna):\n print(f\" {base:>3}: {count}\")\n tot += count\n base, count = 'TOT', tot\n print(f\" {base:>3}= {count}\")\n\ndef seq_mutate(dna, count=1, kinds=\"IDSSSS\", choice=\"ATCG\" ):\n mutation = []\n k2txt = dict(I='Insert', D='Delete', S='Substitute')\n for _ in range(count):\n kind = random.choice(kinds)\n index = random.randint(0, len(dna))\n if kind == 'I': # Insert\n dna = dna[:index] + random.choice(choice) + dna[index:]\n elif kind == 'D' and dna: # Delete\n dna = dna[:index] + dna[index+1:]\n elif kind == 'S' and dna: # Substitute\n dna = dna[:index] + random.choice(choice) + dna[index+1:]\n mutation.append((k2txt[kind], index))\n return dna, mutation\n\nif __name__ == '__main__':\n length = 250\n print(\"SEQUENCE:\")\n sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length))\n seq_pp(sequence)\n print(\"\\n\\nMUTATIONS:\")\n mseq, m = seq_mutate(sequence, 10)\n for kind, index in m:\n print(f\" {kind:>10} @{index}\")\n print()\n seq_pp(mseq)"} {"title": "Bioinformatics/base count", "language": "Python", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "from collections import Counter\n\ndef basecount(dna):\n return sorted(Counter(dna).items())\n\ndef seq_split(dna, n=50):\n return [dna[i: i+n] for i in range(0, len(dna), n)]\n\ndef seq_pp(dna, n=50):\n for i, part in enumerate(seq_split(dna, n)):\n print(f\"{i*n:>5}: {part}\")\n print(\"\\n BASECOUNT:\")\n tot = 0\n for base, count in basecount(dna):\n print(f\" {base:>3}: {count}\")\n tot += count\n base, count = 'TOT', tot\n print(f\" {base:>3}= {count}\")\n \nif __name__ == '__main__':\n print(\"SEQUENCE:\")\n sequence = '''\\\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\\\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\\\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\\\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\\\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\\\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\\\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\\\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\\\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\\\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT'''\n seq_pp(sequence)\n"} {"title": "Bioinformatics/base count", "language": "Python 3.10.5 ", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "\"\"\"\n\tPython 3.10.5 (main, Jun 6 2022, 18:49:26) [GCC 12.1.0] on linux\n\n\tCreated on Wed 2022/08/17 11:19:31\n\t\n\"\"\"\n\n\ndef main ():\n\n\tdef DispCount () :\n\n\t return f'\\n\\nBases :\\n\\n' + f''.join ( [ f'{i} =\\t{D [ i ]:4d}\\n' for i in sorted ( BoI ) ] )\n\n\n\tS =\t'CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG' \\\n\t\t'AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT' \\\n\t\t'CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA' \\\n\t\t'TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG' \\\n\t\t'TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT'\n\n\tAll = set( S ) \n\t\n\tBoI = set ( [ \"A\",\"C\",\"G\",\"T\" ] )\n\t\n\tother = All - BoI\n\t\n\tD = { k : S.count ( k ) for k in All }\n\t\n\tprint ( 'Sequence:\\n\\n')\n\n\tprint ( ''.join ( [ f'{k:4d} : {S [ k: k + 50 ]}\\n' for k in range ( 0, len ( S ), 50 ) ] ) )\n\n\tprint ( f'{DispCount ()} \\n------------')\n\n\tprint ( '' if ( other == set () ) else f'Other\\t{sum ( [ D [ k ] for k in sorted ( other ) ] ):4d}\\n\\n' )\n\n\tprint ( f'\u03a3 = \\t {sum ( [ D [ k ] for k in sorted ( All ) ] ) } \\n============\\n')\n\t\n\tpass\n\n\ndef test ():\n\n\tpass\n\n\n## START\n\nLIVE = True\n\nif ( __name__ == '__main__' ) :\n\n\tmain () if LIVE else test ()\n\n\n"} {"title": "Bioinformatics/base count", "language": "Python 3.7", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "'''Bioinformatics \u2013 base count'''\n\nfrom itertools import count\nfrom functools import reduce\n\n\n# genBankFormatWithBaseCounts :: String -> String\ndef genBankFormatWithBaseCounts(sequence):\n '''DNA Sequence displayed in a subset of the GenBank format.\n See example at foot of:\n https://www.genomatix.de/online_help/help/sequence_formats.html\n '''\n ks, totals = zip(*baseCounts(sequence))\n ns = list(map(str, totals))\n w = 2 + max(map(len, ns))\n\n return '\\n'.join([\n 'DEFINITION len=' + str(sum(totals)),\n 'BASE COUNT ' + ''.join(\n n.rjust(w) + ' ' + k.lower() for (k, n)\n in zip(ks, ns)\n ),\n 'ORIGIN'\n ] + [\n str(i).rjust(9) + ' ' + k for i, k\n in zip(\n count(1, 60),\n [\n ' '.join(row) for row in\n chunksOf(6)(chunksOf(10)(sequence))\n ]\n )\n ] + ['//'])\n\n\n# baseCounts :: String -> Zip [(String, Int)]\ndef baseCounts(baseString):\n '''Sums for each base type in the given sequence string, with\n a fifth sum for any characters not drawn from {A, C, G, T}.'''\n bases = {\n 'A': 0,\n 'C': 1,\n 'G': 2,\n 'T': 3\n }\n return zip(\n list(bases.keys()) + ['Other'],\n foldl(\n lambda a: compose(\n nthArrow(succ)(a),\n flip(curry(bases.get))(4)\n )\n )((0, 0, 0, 0, 0))(baseString)\n )\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Base counts and sequence displayed in GenBank format\n '''\n print(\n genBankFormatWithBaseCounts('''\\\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\\\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\\\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\\\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\\\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\\\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\\\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\\\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\\\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\\\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT''')\n )\n\n\n# ------------------------ GENERIC -------------------------\n\n# chunksOf :: Int -> [a] -> [[a]]\ndef chunksOf(n):\n '''A series of lists of length n, subdividing the\n contents of xs. Where the length of xs is not evenly\n divible, the final list will be shorter than n.\n '''\n return lambda xs: reduce(\n lambda a, i: a + [xs[i:n + i]],\n range(0, len(xs), n), []\n ) if 0 < n else []\n\n\n# compose :: ((a -> a), ...) -> (a -> a)\ndef compose(*fs):\n '''Composition, from right to left,\n of a series of functions.\n '''\n def go(f, g):\n def fg(x):\n return f(g(x))\n return fg\n return reduce(go, fs, lambda x: x)\n\n\n# curry :: ((a, b) -> c) -> a -> b -> c\ndef curry(f):\n '''A curried function derived\n from an uncurried function.\n '''\n return lambda x: lambda y: f(x, y)\n\n\n# flip :: (a -> b -> c) -> b -> a -> c\ndef flip(f):\n '''The (curried or uncurried) function f with its\n arguments reversed.\n '''\n return lambda a: lambda b: f(b)(a)\n\n\n# foldl :: (a -> b -> a) -> a -> [b] -> a\ndef foldl(f):\n '''Left to right reduction of a list,\n using the binary operator f, and\n starting with an initial value a.\n '''\n def go(acc, xs):\n return reduce(lambda a, x: f(a)(x), xs, acc)\n return lambda acc: lambda xs: go(acc, xs)\n\n\n# nthArrow :: (a -> b) -> Tuple -> Int -> Tuple\ndef nthArrow(f):\n '''A simple function lifted to one which applies\n to a tuple, transforming only its nth value.\n '''\n def go(v, n):\n return v if n > len(v) else [\n x if n != i else f(x)\n for i, x in enumerate(v)\n ]\n return lambda tpl: lambda n: tuple(go(tpl, n))\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value.\n For numeric types, (1 +).\n '''\n return 1 + x\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Biorhythms", "language": "Python", "task": "For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in \"Things to Do with your Pocket Calculator\" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.\n\nIt's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives - specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!\n\nTo compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in [[Days between dates]] are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys. \n\nThe three cycles and their lengths are as follows:\n:::{| class=\"wikitable\"\n! Cycle \n! Length\n|- \n|Physical \n| 23 days\n|- \n|Emotional \n| 28 days\n|- \n|Mental \n| 33 days\n|}\n\nThe first half of each cycle is in \"plus\" territory, with a peak at the quarter-way point; the second half in \"minus\" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the ''k''th day of an ''n''-day cycle by computing '''sin( 2p''k'' / ''n'' )'''. The days where a cycle crosses the axis in either direction are called \"critical\" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.\n\nThe task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. \"up and rising\", \"peak\", \"up but falling\", \"critical\", \"down and falling\", \"valley\", \"down but rising\"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.\n\nExample run of my Raku implementation:\nraku br.raku 1943-03-09 1972-07-11\n", "solution": "\"\"\"\n\nPython implementation of\n\nhttp://rosettacode.org/wiki/Biorhythms\n\n\"\"\"\n\nfrom datetime import date, timedelta\nfrom math import floor, sin, pi\n\ndef biorhythms(birthdate,targetdate):\n \"\"\"\n Print out biorhythm data for targetdate assuming you were\n born on birthdate.\n \n birthdate and targetdata are strings in this format:\n \n YYYY-MM-DD e.g. 1964-12-26\n \"\"\"\n \n # print dates\n \n print(\"Born: \"+birthdate+\" Target: \"+targetdate) \n \n # convert to date types - Python 3.7 or later\n \n birthdate = date.fromisoformat(birthdate)\n targetdate = date.fromisoformat(targetdate)\n \n # days between\n \n days = (targetdate - birthdate).days\n \n print(\"Day: \"+str(days))\n \n # cycle logic - mostly from Julia example\n \n cycle_labels = [\"Physical\", \"Emotional\", \"Mental\"]\n cycle_lengths = [23, 28, 33]\n quadrants = [(\"up and rising\", \"peak\"), (\"up but falling\", \"transition\"),\n (\"down and falling\", \"valley\"), (\"down but rising\", \"transition\")]\n \n for i in range(3):\n label = cycle_labels[i]\n length = cycle_lengths[i]\n position = days % length\n quadrant = int(floor((4 * position) / length))\n percentage = int(round(100 * sin(2 * pi * position / length),0))\n transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)\n trend, next = quadrants[quadrant]\n \n if percentage > 95:\n description = \"peak\"\n elif percentage < -95:\n description = \"valley\"\n elif abs(percentage) < 5:\n description = \"critical transition\"\n else:\n description = str(percentage)+\"% (\"+trend+\", next \"+next+\" \"+str(transition_date)+\")\"\n print(label+\" day \"+str(position)+\": \"+description)\n \n \nbiorhythms(\"1943-03-09\",\"1972-07-11\")\n"} {"title": "Bitcoin/address validation", "language": "Python", "task": "Write a program that takes a bitcoin address as argument, \nand checks whether or not this address is valid.\n\nA bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:\n:::* 0 zero\n:::* O uppercase oh\n:::* I uppercase eye\n:::* l lowercase ell\n\n\nWith this encoding, a bitcoin address encodes 25 bytes:\n* the first byte is the version number, which will be zero for this task ;\n* the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;\n* the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes.\n\n\nTo check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.\n\nThe program can either return a boolean value or throw an exception when not valid.\n\nYou can use a digest library for [[SHA-256]].\n\n\n;Example of a bitcoin address:\n\n 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\n\n\nIt doesn't belong to anyone and is part of the test suite of the bitcoin software. \nYou can change a few characters in this string and check that it'll fail the test.\n\n", "solution": "from hashlib import sha256\n\ndigits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\ndef decode_base58(bc, length):\n n = 0\n for char in bc:\n n = n * 58 + digits58.index(char)\n return n.to_bytes(length, 'big')\ndef check_bc(bc):\n try:\n bcbytes = decode_base58(bc, 25)\n return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]\n except Exception:\n return False\n\nprint(check_bc('1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i'))\nprint(check_bc(\"17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j\"))"} {"title": "Bitcoin/public point to address", "language": "Python", "task": "elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion.\n\nThe encoding steps are:\n* take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ;\n* add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ;\n* compute the [[SHA-256]] of this string ;\n* compute the [[RIPEMD-160]] of this SHA-256 digest ;\n* compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in [[bitcoin/address validation]] ;\n* Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum\n\nThe base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I.\n\nHere is an example public point:\nX = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\nY = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\n\nThe corresponding address should be:\n16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM\n\nNb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1.\n\n''Extra credit:'' add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve\n", "solution": "#!/usr/bin/env python3\n\nimport binascii\nimport functools\nimport hashlib\n\ndigits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\ndef b58(n):\n return b58(n//58) + digits58[n%58:n%58+1] if n else b''\n\ndef public_point_to_address(x, y):\n c = b'\\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)\n r = hashlib.new('ripemd160')\n r.update(hashlib.sha256(c).digest())\n c = b'\\x00' + r.digest()\n d = hashlib.sha256(hashlib.sha256(c).digest()).digest()\n return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))\n\nif __name__ == '__main__':\n print(public_point_to_address(\n b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',\n b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))"} {"title": "Bitwise IO", "language": "Python", "task": "The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of\nbits, most significant bit first. While the output of a asciiprint \"STRING\" is the ASCII byte sequence\n\"S\", \"T\", \"R\", \"I\", \"N\", \"G\", the output of a \"print\" of the bits sequence\n0101011101010 (13 bits) must be 0101011101010; real I/O is performed always\n''quantized'' by byte (avoiding endianness issues and relying on underlying\nbuffering for performance), therefore you must obtain as output the bytes\n0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50.\n\nAs test, you can implement a '''rough''' (e.g. don't care about error handling or\nother issues) compression/decompression program for ASCII sequences\nof bytes, i.e. bytes for which the most significant bit is always unused, so that you can write\nseven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).\n\nThese bit oriented I/O functions can be used to implement compressors and\ndecompressors; e.g. Dynamic and Static Huffman encodings use variable length\nbits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words''\nnine (or more) bits long.\n\n* Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.\n* Errors handling is not mandatory\n\n", "solution": "class BitWriter(object):\n def __init__(self, f):\n self.accumulator = 0\n self.bcount = 0\n self.out = f\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.flush()\n\n def __del__(self):\n try:\n self.flush()\n except ValueError: # I/O operation on closed file.\n pass\n\n def _writebit(self, bit):\n if self.bcount == 8:\n self.flush()\n if bit > 0:\n self.accumulator |= 1 << 7-self.bcount\n self.bcount += 1\n\n def writebits(self, bits, n):\n while n > 0:\n self._writebit(bits & 1 << n-1)\n n -= 1\n\n def flush(self):\n self.out.write(bytearray([self.accumulator]))\n self.accumulator = 0\n self.bcount = 0\n\n\nclass BitReader(object):\n def __init__(self, f):\n self.input = f\n self.accumulator = 0\n self.bcount = 0\n self.read = 0\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n pass\n\n def _readbit(self):\n if not self.bcount:\n a = self.input.read(1)\n if a:\n self.accumulator = ord(a)\n self.bcount = 8\n self.read = len(a)\n rv = (self.accumulator & (1 << self.bcount-1)) >> self.bcount-1\n self.bcount -= 1\n return rv\n\n def readbits(self, n):\n v = 0\n while n > 0:\n v = (v << 1) | self._readbit()\n n -= 1\n return v\n\nif __name__ == '__main__':\n import os\n import sys\n # Determine this module's name from it's file name and import it.\n module_name = os.path.splitext(os.path.basename(__file__))[0]\n bitio = __import__(module_name)\n\n with open('bitio_test.dat', 'wb') as outfile:\n with bitio.BitWriter(outfile) as writer:\n chars = '12345abcde'\n for ch in chars:\n writer.writebits(ord(ch), 7)\n\n with open('bitio_test.dat', 'rb') as infile:\n with bitio.BitReader(infile) as reader:\n chars = []\n while True:\n x = reader.readbits(7)\n if not reader.read: # End-of-file?\n break\n chars.append(chr(x))\n print(''.join(chars))\n"} {"title": "Box the compass", "language": "Python", "task": "Avast me hearties!\nThere be many a land lubber that knows naught of the pirate ways and gives direction by degree!\nThey know not how to box the compass! \n\n\n;Task description:\n# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.\n# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:\n:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).\n\n\n;Notes;\n* The headings and indices can be calculated from this pseudocode:\nfor i in 0..32 inclusive:\n heading = i * 11.25\n case i %3:\n if 1: heading += 5.62; break\n if 2: heading -= 5.62; break\n end\n index = ( i mod 32) + 1\n* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..\n\n", "solution": "majors = 'north east south west'.split()\nmajors *= 2 # no need for modulo later\nquarter1 = 'N,N by E,N-NE,NE by N,NE,NE by E,E-NE,E by N'.split(',')\nquarter2 = [p.replace('NE','EN') for p in quarter1]\n\ndef degrees2compasspoint(d):\n d = (d % 360) + 360/64\n majorindex, minor = divmod(d, 90.)\n majorindex = int(majorindex)\n minorindex = int( (minor*4) // 45 )\n p1, p2 = majors[majorindex: majorindex+2]\n if p1 in {'north', 'south'}:\n q = quarter1\n else:\n q = quarter2\n return q[minorindex].replace('N', p1).replace('E', p2).capitalize()\n\nif __name__ == '__main__':\n for i in range(33):\n d = i * 11.25\n m = i % 3\n if m == 1: d += 5.62\n elif m == 2: d -= 5.62\n n = i % 32 + 1\n print( '%2i %-18s %7.2f\u00b0' % (n, degrees2compasspoint(d), d) )"} {"title": "Boyer-Moore string search", "language": "Python", "task": "This algorithm is designed for pattern searching on certain types of devices which are backtracking-unfriendly such as Tape drives and Hard disks.\n\nIt works by first caching a segment of data from storage and match it against the pattern from the highest position backward to the lowest. If the matching fails, it will cache next segment of data and move the start point forward to skip the portion of data which will definitely fail to match. This continues until we successfully match the pattern or the pointer exceeds the data length.\n\nFollow this link for more information about this algorithm.\n\nTo properly test this algorithm, it would be good to search for a string which contains repeated subsequences, such as alfalfa and the text being searched should not only include a match but that match should be preceded by words which partially match, such as alfredo, behalf, calfskin, halfhearted, malfunction or severalfold.\n", "solution": "\"\"\"\nThis version uses ASCII for case-sensitive matching. For Unicode you may want to match in UTF-8\nbytes instead of creating a 0x10FFFF-sized table.\n\"\"\"\n\nfrom typing import List\n\nALPHABET_SIZE = 256\n\ndef alphabet_index(c: str) -> int:\n \"\"\"Return the index of the given ASCII character. \"\"\"\n val = ord(c)\n assert 0 <= val < ALPHABET_SIZE\n return val\n\ndef match_length(S: str, idx1: int, idx2: int) -> int:\n \"\"\"Return the length of the match of the substrings of S beginning at idx1 and idx2.\"\"\"\n if idx1 == idx2:\n return len(S) - idx1\n match_count = 0\n while idx1 < len(S) and idx2 < len(S) and S[idx1] == S[idx2]:\n match_count += 1\n idx1 += 1\n idx2 += 1\n return match_count\n\ndef fundamental_preprocess(S: str) -> List[int]:\n \"\"\"Return Z, the Fundamental Preprocessing of S.\n\n Z[i] is the length of the substring beginning at i which is also a prefix of S.\n This pre-processing is done in O(n) time, where n is the length of S.\n \"\"\"\n if len(S) == 0: # Handles case of empty string\n return []\n if len(S) == 1: # Handles case of single-character string\n return [1]\n z = [0 for x in S]\n z[0] = len(S)\n z[1] = match_length(S, 0, 1)\n for i in range(2, 1 + z[1]): # Optimization from exercise 1-5\n z[i] = z[1] - i + 1\n # Defines lower and upper limits of z-box\n l = 0\n r = 0\n for i in range(2 + z[1], len(S)):\n if i <= r: # i falls within existing z-box\n k = i - l\n b = z[k]\n a = r - i + 1\n if b < a: # b ends within existing z-box\n z[i] = b\n else: # b ends at or after the end of the z-box, we need to do an explicit match to the right of the z-box\n z[i] = a + match_length(S, a, r + 1)\n l = i\n r = i + z[i] - 1\n else: # i does not reside within existing z-box\n z[i] = match_length(S, 0, i)\n if z[i] > 0:\n l = i\n r = i + z[i] - 1\n return z\n\ndef bad_character_table(S: str) -> List[List[int]]:\n \"\"\"\n Generates R for S, which is an array indexed by the position of some character c in the\n ASCII table. At that index in R is an array of length |S|+1, specifying for each\n index i in S (plus the index after S) the next location of character c encountered when\n traversing S from right to left starting at i. This is used for a constant-time lookup\n for the bad character rule in the Boyer-Moore string search algorithm, although it has\n a much larger size than non-constant-time solutions.\n \"\"\"\n if len(S) == 0:\n return [[] for a in range(ALPHABET_SIZE)]\n R = [[-1] for a in range(ALPHABET_SIZE)]\n alpha = [-1 for a in range(ALPHABET_SIZE)]\n for i, c in enumerate(S):\n alpha[alphabet_index(c)] = i\n for j, a in enumerate(alpha):\n R[j].append(a)\n return R\n\ndef good_suffix_table(S: str) -> List[int]:\n \"\"\"\n Generates L for S, an array used in the implementation of the strong good suffix rule.\n L[i] = k, the largest position in S such that S[i:] (the suffix of S starting at i) matches\n a suffix of S[:k] (a substring in S ending at k). Used in Boyer-Moore, L gives an amount to\n shift P relative to T such that no instances of P in T are skipped and a suffix of P[:L[i]]\n matches the substring of T matched by a suffix of P in the previous match attempt.\n Specifically, if the mismatch took place at position i-1 in P, the shift magnitude is given\n by the equation len(P) - L[i]. In the case that L[i] = -1, the full shift table is used.\n Since only proper suffixes matter, L[0] = -1.\n \"\"\"\n L = [-1 for c in S]\n N = fundamental_preprocess(S[::-1]) # S[::-1] reverses S\n N.reverse()\n for j in range(0, len(S) - 1):\n i = len(S) - N[j]\n if i != len(S):\n L[i] = j\n return L\n\ndef full_shift_table(S: str) -> List[int]:\n \"\"\"\n Generates F for S, an array used in a special case of the good suffix rule in the Boyer-Moore\n string search algorithm. F[i] is the length of the longest suffix of S[i:] that is also a\n prefix of S. In the cases it is used, the shift magnitude of the pattern P relative to the\n text T is len(P) - F[i] for a mismatch occurring at i-1.\n \"\"\"\n F = [0 for c in S]\n Z = fundamental_preprocess(S)\n longest = 0\n for i, zv in enumerate(reversed(Z)):\n longest = max(zv, longest) if zv == i + 1 else longest\n F[-i - 1] = longest\n return F\n\ndef string_search(P, T) -> List[int]:\n \"\"\"\n Implementation of the Boyer-Moore string search algorithm. This finds all occurrences of P\n in T, and incorporates numerous ways of pre-processing the pattern to determine the optimal\n amount to shift the string and skip comparisons. In practice it runs in O(m) (and even\n sublinear) time, where m is the length of T. This implementation performs a case-sensitive\n search on ASCII characters. P must be ASCII as well.\n \"\"\"\n if len(P) == 0 or len(T) == 0 or len(T) < len(P):\n return []\n\n matches = []\n\n # Preprocessing\n R = bad_character_table(P)\n L = good_suffix_table(P)\n F = full_shift_table(P)\n\n k = len(P) - 1 # Represents alignment of end of P relative to T\n previous_k = -1 # Represents alignment in previous phase (Galil's rule)\n while k < len(T):\n i = len(P) - 1 # Character to compare in P\n h = k # Character to compare in T\n while i >= 0 and h > previous_k and P[i] == T[h]: # Matches starting from end of P\n i -= 1\n h -= 1\n if i == -1 or h == previous_k: # Match has been found (Galil's rule)\n matches.append(k - len(P) + 1)\n k += len(P) - F[1] if len(P) > 1 else 1\n else: # No match, shift by max of bad character and good suffix rules\n char_shift = i - R[alphabet_index(T[h])][i]\n if i + 1 == len(P): # Mismatch happened on first attempt\n suffix_shift = 1\n elif L[i + 1] == -1: # Matched suffix does not appear anywhere in P\n suffix_shift = len(P) - F[i + 1]\n else: # Matched suffix appears in P\n suffix_shift = len(P) - 1 - L[i + 1]\n shift = max(char_shift, suffix_shift)\n previous_k = k if shift >= i + 1 else previous_k # Galil's rule\n k += shift\n return matches\n\nTEXT1 = 'InhisbookseriesTheArtofComputerProgrammingpublishedbyAddisonWesleyDKnuthusesanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguagestoillustratetheconceptsandalgorithmsastheyarepresented'\nTEXT2 = \"Nearby farms grew a half acre of alfalfa on the dairy's behalf, with bales of all that alfalfa exchanged for milk.\"\nPAT1, PAT2, PAT3 = 'put', 'and', 'alfalfa'\n\nprint(\"Found\", PAT1, \"at:\", string_search(PAT1, TEXT1))\nprint(\"Found\", PAT2, \"at:\", string_search(PAT2, TEXT1))\nprint(\"Found\", PAT3, \"at:\", string_search(PAT3, TEXT2))\n"} {"title": "Brazilian numbers", "language": "Python", "task": "Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.\n\nBrazilian numbers are defined as:\n\nThe set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.\n\n\n;E.G.:\n\n:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.\n:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.\n:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.\n:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.\n:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.\n:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.\n:* ''and so on...''\n\n\nAll even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.\nMore common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''\nThe only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. \nAll prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2\n\n;Task:\n\nWrite a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;\n\n:* the first '''20''' Brazilian numbers;\n:* the first '''20 odd''' Brazilian numbers;\n:* the first '''20 prime''' Brazilian numbers;\n\n\n;See also:\n\n:* '''OEIS:A125134 - Brazilian numbers'''\n:* '''OEIS:A257521 - Odd Brazilian numbers'''\n:* '''OEIS:A085104 - Prime Brazilian numbers'''\n\n", "solution": "'''Brazilian numbers'''\n\nfrom itertools import count, islice\n\n\n# isBrazil :: Int -> Bool\ndef isBrazil(n):\n '''True if n is a Brazilian number,\n in the sense of OEIS:A125134.\n '''\n return 7 <= n and (\n 0 == n % 2 or any(\n map(monoDigit(n), range(2, n - 1))\n )\n )\n\n\n# monoDigit :: Int -> Int -> Bool\ndef monoDigit(n):\n '''True if all the digits of n,\n in the given base, are the same.\n '''\n def go(base):\n def g(b, n):\n (q, d) = divmod(n, b)\n\n def p(qr):\n return d != qr[1] or 0 == qr[0]\n\n def f(qr):\n return divmod(qr[0], b)\n return d == until(p)(f)(\n (q, d)\n )[1]\n return g(base, n)\n return go\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''First 20 members each of:\n OEIS:A125134\n OEIS:A257521\n OEIS:A085104\n '''\n for kxs in ([\n (' ', count(1)),\n (' odd ', count(1, 2)),\n (' prime ', primes())\n ]):\n print(\n 'First 20' + kxs[0] + 'Brazilians:\\n' +\n showList(take(20)(filter(isBrazil, kxs[1]))) + '\\n'\n )\n\n\n# ------------------- GENERIC FUNCTIONS --------------------\n\n# primes :: [Int]\ndef primes():\n ''' Non finite sequence of prime numbers.\n '''\n n = 2\n dct = {}\n while True:\n if n in dct:\n for p in dct[n]:\n dct.setdefault(n + p, []).append(p)\n del dct[n]\n else:\n yield n\n dct[n * n] = [n]\n n = 1 + n\n\n\n# showList :: [a] -> String\ndef showList(xs):\n '''Stringification of a list.'''\n return '[' + ','.join(str(x) for x in xs) + ']'\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n def go(xs):\n return (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n return go\n\n\n# until :: (a -> Bool) -> (a -> a) -> a -> a\ndef until(p):\n '''The result of repeatedly applying f until p holds.\n The initial seed value is x.\n '''\n def go(f):\n def g(x):\n v = x\n while not p(v):\n v = f(v)\n return v\n return g\n return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Break OO privacy", "language": "Python", "task": "Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. \nThe intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. \nThe intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.\n\nNote that cheating on your type system is almost universally regarded \nas unidiomatic at best, and poor programming practice at worst. \nNonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.\n", "solution": ">>> class MyClassName:\n\t__private = 123\n\tnon_private = __private * 2\n\n\t\n>>> mine = MyClassName()\n>>> mine.non_private\n246\n>>> mine.__private\nTraceback (most recent call last):\n File \"\", line 1, in \n mine.__private\nAttributeError: 'MyClassName' object has no attribute '__private'\n>>> mine._MyClassName__private\n123\n>>> "} {"title": "Brilliant numbers", "language": "Python", "task": "'''Brilliant numbers''' are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers '''that both have the same number of digits when expressed in base 10'''.\n\n''Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.''\n \n\n\n;E.G.\n* '''3 x 3''' (9) is a brilliant number. \n* '''2 x 7''' (14) is a brilliant number.\n* '''113 x 691''' (78083) is a brilliant number.\n* '''2 x 31''' (62) is semiprime, but is '''not''' a brilliant number (different number of digits in the two factors).\n\n\n\n;Task\n* Find and display the first 100 brilliant numbers.\n* For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).\n\n\n;Stretch\n* Continue for larger orders of magnitude.\n\n\n;See also\n;* Numbers Aplenty - Brilliant numbers\n;* OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits\n", "solution": "from primesieve.numpy import primes\nfrom math import isqrt\nimport numpy as np\n\nmax_order = 9\nblocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)]\n\ndef smallest_brilliant(lb):\n pos = 1\n root = isqrt(lb)\n\n for blk in blocks:\n n = len(blk)\n if blk[-1]*blk[-1] < lb:\n pos += n*(n + 1)//2\n continue\n\n i = np.searchsorted(blk, root, 'left')\n i += blk[i]*blk[i] < lb\n\n if not i:\n return blk[0]*blk[0], pos\n\n p = blk[:i + 1]\n q = (lb - 1)//p\n idx = np.searchsorted(blk, q, 'right')\n\n sel = idx < n\n p, idx = p[sel], idx[sel]\n q = blk[idx]\n\n sel = q >= p\n p, q, idx = p[sel], q[sel], idx[sel]\n\n pos += np.sum(idx - np.arange(len(idx)))\n return np.min(p*q), pos\n\nres = []\np = 0\nfor i in range(100):\n p, _ = smallest_brilliant(p + 1)\n res.append(p)\n\nprint(f'first 100 are {res}')\n\nfor i in range(max_order*2):\n thresh = 10**i\n p, pos = smallest_brilliant(thresh)\n print(f'Above 10^{i:2d}: {p:20d} at #{pos}')"} {"title": "Burrows\u2013Wheeler transform", "language": "Python", "task": "{{Wikipedia|Burrows-Wheeler_transform}}\n\n\nThe Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. \n\nThis is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. \n\nMore importantly, the transformation is reversible, without needing to store any additional data. \n\nThe BWT is thus a \"free\" method of improving the efficiency of text compression algorithms, costing only some extra computation.\n\n\nSource: Burrows-Wheeler transform\n\n", "solution": "def bwt(s):\n \"\"\"Apply Burrows-Wheeler transform to input string.\"\"\"\n assert \"\\002\" not in s and \"\\003\" not in s, \"Input string cannot contain STX and ETX characters\"\n s = \"\\002\" + s + \"\\003\" # Add start and end of text marker\n table = sorted(s[i:] + s[:i] for i in range(len(s))) # Table of rotations of string\n last_column = [row[-1:] for row in table] # Last characters of each row\n return \"\".join(last_column) # Convert list of characters into string\n\n\ndef ibwt(r):\n \"\"\"Apply inverse Burrows-Wheeler transform.\"\"\"\n table = [\"\"] * len(r) # Make empty table\n for i in range(len(r)):\n table = sorted(r[i] + table[i] for i in range(len(r))) # Add a column of r\n s = [row for row in table if row.endswith(\"\\003\")][0] # Find the correct row (ending in ETX)\n return s.rstrip(\"\\003\").strip(\"\\002\") # Get rid of start and end markers\n"} {"title": "CSV data manipulation", "language": "Python", "task": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\nSuggestions\n\n Show how to add a column, headed 'SUM', of the sums of the rows.\n If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\n\n", "solution": "import fileinput\n\nchangerow, changecolumn, changevalue = 2, 4, '\"Spam\"'\n\nwith fileinput.input('csv_data_manipulation.csv', inplace=True) as f:\n for line in f:\n if fileinput.filelineno() == changerow:\n fields = line.rstrip().split(',')\n fields[changecolumn-1] = changevalue\n line = ','.join(fields) + '\\n'\n print(line, end='')"} {"title": "CSV to HTML translation", "language": "Python", "task": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be ''escaped'' when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via preferably; CSS if you must).\n\n", "solution": "from csv import DictReader\nfrom xml.etree import ElementTree as ET\n\ndef csv2html_robust(txt, header=True, attr=None):\n # Use DictReader because, despite what the docs say, reader() doesn't\n # return an object with .fieldnames\n # (DictReader expects an iterable that returns lines, so split on \\n)\n reader = DictReader(txt.split('\\n'))\n\n table = ET.Element(\"TABLE\", **attr.get('TABLE', {}))\n thead_tr = ET.SubElement(\n ET.SubElement(table, \"THEAD\", **attr.get('THEAD', {})),\n \"TR\")\n tbody = ET.SubElement(table, \"TBODY\", **attr.get('TBODY', {}))\n\n if header:\n for name in reader.fieldnames:\n ET.SubElement(thead_tr, \"TD\").text = name\n\n for row in reader:\n tr_elem = ET.SubElement(tbody, \"TR\", **attr.get('TR', {}))\n\n # Use reader.fieldnames to query `row` in the correct order.\n # (`row` isn't an OrderedDict prior to Python 3.6)\n for field in reader.fieldnames:\n td_elem = ET.SubElement(tr_elem, \"TD\", **attr.get('TD', {}))\n td_elem.text = row[field]\n\n return ET.tostring(table, method='html')\n\nhtmltxt = csv2html_robust(csvtxt, True, {\n 'TABLE': {'border': \"1\", 'summary': \"csv2html extra program output\"},\n 'THEAD': {'bgcolor': \"yellow\"},\n 'TBODY': {'bgcolor': \"orange\"}\n})\n\nprint(htmltxt.decode('utf8'))"} {"title": "Calculating the value of e", "language": "Python", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "import math\n#Implementation of Brother's formula\ne0 = 0\ne = 2\nn = 0\nfact = 1\nwhile(e-e0 > 1e-15):\n\te0 = e\n\tn += 1\n\tfact *= 2*n*(2*n+1)\n\te += (2.*n+2)/fact\n\nprint \"Computed e = \"+str(e)\nprint \"Real e = \"+str(math.e)\nprint \"Error = \"+str(math.e-e)\nprint \"Number of iterations = \"+str(n)"} {"title": "Calculating the value of e", "language": "Python 3.7", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "'''Calculating an approximate value for e'''\n\nfrom itertools import (accumulate, chain)\nfrom functools import (reduce)\nfrom operator import (mul)\n\n\n# eApprox :: () -> Float\ndef eApprox():\n '''Approximation to the value of e.'''\n return reduce(\n lambda a, x: a + 1 / x,\n scanl(mul)(1)(\n range(1, 18)\n ),\n 0\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test'''\n\n print(\n eApprox()\n )\n\n\n# GENERIC ABSTRACTIONS ------------------------------------\n\n# scanl is like reduce, but returns a succession of\n# intermediate values, building from the left.\n# See, for example, under `scan` in the Lists chapter of\n# the language-independent Bird & Wadler 1988.\n\n# scanl :: (b -> a -> b) -> b -> [a] -> [b]\ndef scanl(f):\n '''scanl is like reduce, but returns a succession of\n intermediate values, building from the left.'''\n return lambda a: lambda xs: (\n accumulate(chain([a], xs), f)\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Calkin-Wilf sequence", "language": "Python", "task": "The '''Calkin-Wilf sequence''' contains every nonnegative rational number exactly once. \n\nIt can be calculated recursively as follows:\n\n {{math|a1}} = {{math|1}} \n {{math|an+1}} = {{math|1/(2an+1-an)}} for n > 1 \n\n\n;Task part 1:\n* Show on this page terms 1 through 20 of the Calkin-Wilf sequence.\n\nTo avoid floating point error, you may want to use a rational number data type.\n\n\nIt is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. \nIt only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:\n\n {{math|[a0; a1, a2, ..., an]}} = {{math|[a0; a1, a2 ,..., an-1, 1]}} \n\n\n;Example:\nThe fraction '''9/4''' has odd continued fraction representation {{math|2; 3, 1}}, giving a binary representation of '''100011''', \nwhich means '''9/4''' appears as the '''35th''' term of the sequence.\n\n\n;Task part 2:\n* Find the position of the number '''83116''''''/''''''51639''' in the Calkin-Wilf sequence.\n\n\n;See also:\n* Wikipedia entry: Calkin-Wilf tree\n* [[Continued fraction]]\n* [[Continued fraction/Arithmetic/Construct from rational number]]\n\n", "solution": "from fractions import Fraction\nfrom math import floor\nfrom itertools import islice, groupby\n\n\ndef cw():\n a = Fraction(1)\n while True:\n yield a\n a = 1 / (2 * floor(a) + 1 - a)\n\ndef r2cf(rational):\n num, den = rational.numerator, rational.denominator\n while den:\n num, (digit, den) = den, divmod(num, den)\n yield digit\n\ndef get_term_num(rational):\n ans, dig, pwr = 0, 1, 0\n for n in r2cf(rational):\n for _ in range(n):\n ans |= dig << pwr\n pwr += 1\n dig ^= 1\n return ans\n\n \nif __name__ == '__main__':\n print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))\n x = Fraction(83116, 51639)\n print(f\"\\n{x} is the {get_term_num(x):_}'th term.\")"} {"title": "Call a function", "language": "Python", "task": "Demonstrate the different syntax and semantics provided for calling a function. \n\n\nThis may include:\n:* Calling a function that requires no arguments\n:* Calling a function with a fixed number of arguments\n:* Calling a function with optional arguments\n:* Calling a function with a variable number of arguments\n:* Calling a function with named arguments\n:* Using a function in statement context\n:* Using a function in first-class context within an expression\n:* Obtaining the return value of a function\n:* Distinguishing built-in functions and user-defined functions\n:* Distinguishing subroutines and functions\n;* Stating whether arguments are passed by value or by reference\n;* Is partial application possible and how\n\n\nThis task is ''not'' about defining functions.\n\n", "solution": "def no_args():\n pass\n# call\nno_args()\n\ndef fixed_args(x, y):\n print('x=%r, y=%r' % (x, y))\n# call\nfixed_args(1, 2) # x=1, y=2\n\n## Can also called them using the parameter names, in either order:\nfixed_args(y=2, x=1)\n\n## Can also \"apply\" fixed_args() to a sequence:\nmyargs=(1,2) # tuple\nfixed_args(*myargs)\n\ndef opt_args(x=1):\n print(x)\n# calls\nopt_args() # 1\nopt_args(3.141) # 3.141\n\ndef var_args(*v):\n print(v)\n# calls\t\nvar_args(1, 2, 3) # (1, 2, 3)\nvar_args(1, (2,3)) # (1, (2, 3))\nvar_args() # ()\n\n## Named arguments\nfixed_args(y=2, x=1) # x=1, y=2\n\n## As a statement\nif 1:\n no_args()\n\n## First-class within an expression\nassert no_args() is None\n\ndef return_something():\n return 1\nx = return_something()\n\ndef is_builtin(x):\n\tprint(x.__name__ in dir(__builtins__))\n# calls\nis_builtin(pow) # True\nis_builtin(is_builtin) # False\n\n# Very liberal function definition\n\ndef takes_anything(*args, **kwargs):\n for each in args:\n print(each)\n for key, value in sorted(kwargs.items()):\n print(\"%s:%s\" % (key, value))\n # Passing those to another, wrapped, function:\n wrapped_fn(*args, **kwargs)\n # (Function being wrapped can have any parameter list\n # ... that doesn't have to match this prototype)\n\n## A subroutine is merely a function that has no explicit\n## return statement and will return None.\n\n## Python uses \"Call by Object Reference\".\n## See, for example, http://www.python-course.eu/passing_arguments.php\n\n## For partial function application see:\n## http://rosettacode.org/wiki/Partial_function_application#Python"} {"title": "Canonicalize CIDR", "language": "Python from Perl", "task": "Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. \n\nThat is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.\n\n\n;Example:\nGiven '''87.70.141.1/22''', your code should output '''87.70.140.0/22'''\n\n\n;Explanation:\nAn Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.\n\nIn general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.\n\nThe example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.\n\n\n;More examples for testing\n\n 36.18.154.103/12 - 36.16.0.0/12\n 62.62.197.11/29 - 62.62.197.8/29\n 67.137.119.181/4 - 64.0.0.0/4\n 161.214.74.21/24 - 161.214.74.0/24\n 184.232.176.184/18 - 184.232.128.0/18\n\n\n", "solution": "#!/usr/bin/env python\n# canonicalize a CIDR block specification:\n# make sure none of the host bits are set\n\nimport sys\nfrom socket import inet_aton, inet_ntoa\nfrom struct import pack, unpack\n\nargs = sys.argv[1:]\nif len(args) == 0:\n args = sys.stdin.readlines()\n\nfor cidr in args:\n # IP in dotted-decimal / bits in network part\n dotted, size_str = cidr.split('/')\n size = int(size_str)\n\n numeric = unpack('!I', inet_aton(dotted))[0] # IP as an integer\n binary = f'{numeric:#034b}' # then as a padded binary string\n prefix = binary[:size + 2] # just the network part\n # (34 and +2 are to account\n # for leading '0b')\n\n canon_binary = prefix + '0' * (32 - size) # replace host part with all zeroes\n canon_numeric = int(canon_binary, 2) # convert back to integer\n canon_dotted = inet_ntoa(pack('!I',\n (canon_numeric))) # and then to dotted-decimal\n print(f'{canon_dotted}/{size}') # output result"} {"title": "Cantor set", "language": "Python", "task": "Draw a Cantor set.\n\n\nSee details at this Wikipedia webpage: Cantor set\n\n", "solution": "WIDTH = 81\nHEIGHT = 5\n\nlines=[]\ndef cantor(start, len, index):\n seg = len / 3\n if seg == 0:\n return None\n for it in xrange(HEIGHT-index):\n i = index + it\n for jt in xrange(seg):\n j = start + seg + jt\n pos = i * WIDTH + j\n lines[pos] = ' '\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n return None\n\nlines = ['*'] * (WIDTH*HEIGHT)\ncantor(0, WIDTH, 1)\n\nfor i in xrange(HEIGHT):\n beg = WIDTH * i\n print ''.join(lines[beg : beg+WIDTH])"} {"title": "Cantor set", "language": "Python 3.7", "task": "Draw a Cantor set.\n\n\nSee details at this Wikipedia webpage: Cantor set\n\n", "solution": "'''A Cantor set generator, and two different\n representations of its output.\n'''\n\nfrom itertools import (islice, chain)\nfrom fractions import Fraction\nfrom functools import (reduce)\n\n\n# ----------------------- CANTOR SET -----------------------\n\n# cantor :: Generator [[(Fraction, Fraction)]]\ndef cantor():\n '''A non-finite stream of successive Cantor\n partitions of the line, in the form of\n lists of fraction pairs.\n '''\n def go(xy):\n (x, y) = xy\n third = Fraction(y - x, 3)\n return [(x, x + third), (y - third, y)]\n\n return iterate(\n concatMap(go)\n )(\n [(0, 1)]\n )\n\n\n# fractionLists :: [(Fraction, Fraction)] -> String\ndef fractionLists(xs):\n '''A fraction pair representation of a\n Cantor-partitioned line.\n '''\n def go(xy):\n return ', '.join(map(showRatio, xy))\n return ' '.join('(' + go(x) + ')' for x in xs)\n\n\n# intervalBars :: [(Fraction, Fraction)] -> String\ndef intervalBars(w):\n '''A block diagram representation of a\n Cantor-partitioned line.\n '''\n def go(xs):\n def show(a, tpl):\n [x, y] = [int(w * r) for r in tpl]\n return (\n y,\n (' ' * (x - a)) + ('\u2588' * (y - x))\n )\n return mapAccumL(show)(0)(xs)\n return lambda xs: ''.join(go(xs)[1])\n\n\n# -------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Testing the generation of successive\n Cantor subdivisions of the line, and\n displaying them both as lines of fraction\n pairs and as graphic interval bars.\n '''\n xs = list(islice(cantor(), 4))\n w = max(xy[1].denominator for xy in xs[-1])\n print(\n '\\n'.join(map(fractionLists, xs)),\n '\\n'\n )\n print(\n '\\n'.join(map(intervalBars(w), xs))\n )\n\n\n# ------------------------ GENERIC -------------------------\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).'''\n return lambda xs: list(\n chain.from_iterable(map(f, xs))\n )\n\n\n# iterate :: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n '''An infinite list of repeated\n applications of f to x.\n '''\n def go(x):\n v = x\n while True:\n yield v\n v = f(v)\n return go\n\n\n# mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\ndef mapAccumL(f):\n '''A tuple of an accumulation and a list derived by a\n combined map and fold,\n with accumulation from left to right.\n '''\n def go(a, x):\n tpl = f(a[0], x)\n return (tpl[0], a[1] + [tpl[1]])\n return lambda acc: lambda xs: (\n reduce(go, xs, (acc, []))\n )\n\n\n# showRatio :: Ratio -> String\ndef showRatio(r):\n '''String representation of the ratio r.'''\n d = r.denominator\n return str(r.numerator) + (\n '/' + str(d) if 1 != d else ''\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Cartesian product of two or more lists", "language": "Python", "task": "Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} x {} = {}\n:: {} x {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}\n:: {1, 2, 3} x {30} x {500, 100}\n:: {1, 2, 3} x {} x {500, 100}\n\n\n", "solution": "import itertools\n\ndef cp(lsts):\n return list(itertools.product(*lsts))\n\nif __name__ == '__main__':\n from pprint import pprint as pp\n \n for lists in [[[1,2],[3,4]], [[3,4],[1,2]], [[], [1, 2]], [[1, 2], []],\n ((1776, 1789), (7, 12), (4, 14, 23), (0, 1)),\n ((1, 2, 3), (30,), (500, 100)),\n ((1, 2, 3), (), (500, 100))]:\n print(lists, '=>')\n pp(cp(lists), indent=2)\n"} {"title": "Casting out nines", "language": "Python", "task": "Task (in three parts):\n\n\n;Part 1\nWrite a procedure (say \\mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.\n\nNote that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.\n\nWith that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be \"casting out nines\", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.\n\n;Part 2\nNotwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:\n: Consider the statement \"318682 is 101558 + 217124 and squared is 101558217124\" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).\n: note that 318682 has the same checksum as (101558 + 217124);\n: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);\n: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.\n\nDemonstrate that your procedure can be used to generate or filter a range of numbers with the property \\mathit{co9}(k) = \\mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;Part 3\nConsidering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:\n: \\mathit{co9}(x) is the residual of x mod 9;\n: the procedure can be extended to bases other than 9.\n\nDemonstrate your algorithm by generating or filtering a range of numbers with the property k%(\\mathit{Base}-1) == (k^2)%(\\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;related tasks\n* [[First perfect square in base N with N unique digits]]\n* [[Kaprekar numbers]]\n\n", "solution": "# Casting out Nines\n#\n# Nigel Galloway: June 27th., 2012,\n#\ndef CastOut(Base=10, Start=1, End=999999):\n ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)]\n x,y = divmod(Start, Base-1)\n while True:\n for n in ran:\n k = (Base-1)*x + n\n if k < Start:\n continue\n if k > End:\n return\n yield k\n x += 1\n\nfor V in CastOut(Base=16,Start=1,End=255):\n print(V, end=' ')"} {"title": "Catalan numbers/Pascal's triangle", "language": "Python from C++", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": ">>> n = 15\n>>> t = [0] * (n + 2)\n>>> t[1] = 1\n>>> for i in range(1, n + 1):\n\tfor j in range(i, 1, -1): t[j] += t[j - 1]\n\tt[i + 1] = t[i]\n\tfor j in range(i + 1, 1, -1): t[j] += t[j - 1]\n\tprint(t[i+1] - t[i], end=' ')\n\n\t\n1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 \n>>> "} {"title": "Catalan numbers/Pascal's triangle", "language": "Python 2.7", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "def catalan_number(n):\n nm = dm = 1\n for k in range(2, n+1):\n nm, dm = ( nm*(n+k), dm*k )\n return nm/dm\n \nprint [catalan_number(n) for n in range(1, 16)]\n \n[1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]"} {"title": "Catalan numbers/Pascal's triangle", "language": "Python 3.7", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "'''Catalan numbers from Pascal's triangle'''\n\nfrom itertools import (islice)\nfrom operator import (add)\n\n\n# nCatalans :: Int -> [Int]\ndef nCatalans(n):\n '''The first n Catalan numbers,\n derived from Pascal's triangle.'''\n\n # diff :: [Int] -> Int\n def diff(xs):\n '''Difference between the first two items in the list,\n if its length is more than one.\n Otherwise, the first (only) item in the list.'''\n return (\n xs[0] - (xs[1] if 1 < len(xs) else 0)\n ) if xs else None\n return list(map(\n compose(diff)(uncurry(drop)),\n enumerate(map(fst, take(n)(\n everyOther(\n pascalTriangle()\n )\n )))\n ))\n\n\n# pascalTriangle :: Gen [[Int]]\ndef pascalTriangle():\n '''A non-finite stream of\n Pascal's triangle rows.'''\n return iterate(nextPascal)([1])\n\n\n# nextPascal :: [Int] -> [Int]\ndef nextPascal(xs):\n '''A row of Pascal's triangle\n derived from a preceding row.'''\n return zipWith(add)([0] + xs)(xs + [0])\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''First 16 Catalan numbers.'''\n\n print(\n nCatalans(16)\n )\n\n\n# GENERIC -------------------------------------------------\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# drop :: Int -> [a] -> [a]\n# drop :: Int -> String -> String\ndef drop(n):\n '''The sublist of xs beginning at\n (zero-based) index n.'''\n def go(xs):\n if isinstance(xs, list):\n return xs[n:]\n else:\n take(n)(xs)\n return xs\n return lambda xs: go(xs)\n\n\n# everyOther :: Gen [a] -> Gen [a]\ndef everyOther(g):\n '''Every other item of a generator stream.'''\n while True:\n yield take(1)(g)\n take(1)(g) # Consumed, not yielded.\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First component of a pair.'''\n return tpl[0]\n\n\n# iterate :: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n '''An infinite list of repeated applications of f to x.'''\n def go(x):\n v = x\n while True:\n yield v\n v = f(v)\n return lambda x: go(x)\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.'''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, list)\n else list(islice(xs, n))\n )\n\n\n# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n '''A function over a tuple\n derived from a curried function.'''\n return lambda xy: f(xy[0])(\n xy[1]\n )\n\n\n# zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]\ndef zipWith(f):\n '''A list constructed by zipping with a\n custom function, rather than with the\n default tuple constructor.'''\n return lambda xs: lambda ys: (\n list(map(f, xs, ys))\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Catamorphism", "language": "Python", "task": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism\n\n", "solution": ">>> # Python 2.X\n>>> from operator import add\n>>> listoflists = [['the', 'cat'], ['sat', 'on'], ['the', 'mat']]\n>>> help(reduce)\nHelp on built-in function reduce in module __builtin__:\n\nreduce(...)\n reduce(function, sequence[, initial]) -> value\n \n Apply a function of two arguments cumulatively to the items of a sequence,\n from left to right, so as to reduce the sequence to a single value.\n For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n of the sequence in the calculation, and serves as a default when the\n sequence is empty.\n\n>>> reduce(add, listoflists, [])\n['the', 'cat', 'sat', 'on', 'the', 'mat']\n>>> "} {"title": "Chaocipher", "language": "Python", "task": "Description:\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\n\n;Task:\nCode the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.\n\n", "solution": "# Python3 implementation of Chaocipher \n# left wheel = ciphertext wheel\n# right wheel = plaintext wheel\n\ndef main():\n # letters only! makealpha(key) helps generate lalpha/ralpha. \n lalpha = \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\"\n ralpha = \"PTLNBQDEOYSFAVZKGJRIHWXUMC\"\n msg = \"WELLDONEISBETTERTHANWELLSAID\"\n\n print(\"L:\", lalpha)\n print(\"R:\", ralpha)\n print(\"I:\", msg)\n print(\"O:\", do_chao(msg, lalpha, ralpha, 1, 0), \"\\n\")\n \n do_chao(msg, lalpha, ralpha, 1, 1)\n\ndef do_chao(msg, lalpha, ralpha, en=1, show=0):\n msg = correct_case(msg)\n out = \"\" \n if show:\n print(\"=\"*54) \n print(10*\" \" + \"left:\" + 21*\" \" + \"right: \")\n print(\"=\"*54) \n print(lalpha, ralpha, \"\\n\")\n for L in msg:\n if en:\n lalpha, ralpha = rotate_wheels(lalpha, ralpha, L)\n out += lalpha[0]\n else:\n ralpha, lalpha = rotate_wheels(ralpha, lalpha, L)\n out += ralpha[0]\n lalpha, ralpha = scramble_wheels(lalpha, ralpha)\n if show:\n print(lalpha, ralpha) \n return out\n \ndef makealpha(key=\"\"):\n alpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n z = set()\n key = [x.upper() for x in (key + alpha[::-1])\n if not (x.upper() in z or z.add(x.upper()))]\n return \"\".join(key)\n\ndef correct_case(string):\n return \"\".join([s.upper() for s in string if s.isalpha()])\n\ndef permu(alp, num):\n alp = alp[:num], alp[num:]\n return \"\".join(alp[::-1])\n\ndef rotate_wheels(lalph, ralph, key):\n newin = ralph.index(key)\n return permu(lalph, newin), permu(ralph, newin) \n\ndef scramble_wheels(lalph, ralph):\n # LEFT = cipher wheel \n # Cycle second[1] through nadir[14] forward\n lalph = list(lalph)\n lalph = \"\".join([*lalph[0],\n *lalph[2:14],\n lalph[1],\n *lalph[14:]])\n \n # RIGHT = plain wheel \n # Send the zenith[0] character to the end[25],\n # cycle third[2] through nadir[14] characters forward\n ralph = list(ralph)\n ralph = \"\".join([*ralph[1:3],\n *ralph[4:15],\n ralph[3],\n *ralph[15:],\n ralph[0]])\n return lalph, ralph\n\nmain()"} {"title": "Chaocipher", "language": "Python 3.7", "task": "Description:\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\n\n;Task:\nCode the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.\n\n", "solution": "'''Chaocipher'''\n\nfrom itertools import chain, cycle, islice\n\n\n# chao :: String -> String -> Bool -> String -> String\ndef chao(l):\n '''Chaocipher encoding or decoding for the given\n left and right 'wheels'.\n A ciphertext is returned if the boolean flag\n is True, and a plaintext if the flag is False.\n '''\n def go(l, r, plain, xxs):\n if xxs:\n (src, dst) = (l, r) if plain else (r, l)\n (x, xs) = (xxs[0], xxs[1:])\n\n def chaoProcess(n):\n return [dst[n]] + go(\n shifted(1)(14)(rotated(n, l)),\n compose(shifted(2)(14))(shifted(0)(26))(\n rotated(n, r)\n ),\n plain,\n xs\n )\n\n return maybe('')(chaoProcess)(\n elemIndex(x)(src)\n )\n else:\n return []\n return lambda r: lambda plain: lambda xxs: concat(go(\n l, r, plain, xxs\n ))\n\n\n# rotated :: Int -> [a] -> [a]\ndef rotated(z, s):\n '''Rotation of string s by z characters.'''\n return take(len(s))(\n drop(z)(\n cycle(s)\n )\n )\n\n\n# shifted :: Int -> Int -> [a] -> [a]\ndef shifted(src):\n '''The string s with a set of its characters cyclically\n shifted from a source index to a destination index.\n '''\n def go(dst, s):\n (a, b) = splitAt(dst)(s)\n (x, y) = splitAt(src)(a)\n return concat([x, rotated(1, y), b])\n return lambda dst: lambda s: go(dst, s)\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Print the plain text, followed by\n a corresponding cipher text,\n and a decode of that cipher text.\n '''\n chaoWheels = chao(\n \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\"\n )(\n \"PTLNBQDEOYSFAVZKGJRIHWXUMC\"\n )\n plainText = \"WELLDONEISBETTERTHANWELLSAID\"\n cipherText = chaoWheels(False)(plainText)\n\n print(plainText)\n print(cipherText)\n print(\n chaoWheels(True)(cipherText)\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# concat :: [[a]] -> [a]\n# concat :: [String] -> String\ndef concat(xs):\n '''The concatenation of all the elements\n in a list or iterable.\n '''\n def f(ys):\n zs = list(chain(*ys))\n return ''.join(zs) if isinstance(ys[0], str) else zs\n\n return (\n f(xs) if isinstance(xs, list) else (\n chain.from_iterable(xs)\n )\n ) if xs else []\n\n\n# drop :: Int -> [a] -> [a]\n# drop :: Int -> String -> String\ndef drop(n):\n '''The sublist of xs beginning at\n (zero-based) index n.\n '''\n def go(xs):\n if isinstance(xs, (list, tuple, str)):\n return xs[n:]\n else:\n take(n)(xs)\n return xs\n return lambda xs: go(xs)\n\n\n# elemIndex :: Eq a => a -> [a] -> Maybe Int\ndef elemIndex(x):\n '''Just the index of the first element in xs\n which is equal to x,\n or Nothing if there is no such element.\n '''\n def go(xs):\n try:\n return Just(xs.index(x))\n except ValueError:\n return Nothing()\n return lambda xs: go(xs)\n\n\n# maybe :: b -> (a -> b) -> Maybe a -> b\ndef maybe(v):\n '''Either the default value v, if m is Nothing,\n or the application of f to x,\n where m is Just(x).\n '''\n return lambda f: lambda m: v if None is m or m.get('Nothing') else (\n f(m.get('Just'))\n )\n\n\n# splitAt :: Int -> [a] -> ([a], [a])\ndef splitAt(n):\n '''A tuple pairing the prefix of length n\n with the rest of xs.\n '''\n return lambda xs: (xs[0:n], xs[n:])\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, (list, tuple))\n else list(islice(xs, n))\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Chaos game", "language": "Python", "task": "The Chaos Game is a method of generating the attractor of an iterated function system (IFS). \n\nOne of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.\n\n\n;Task\nPlay the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.\n\nAfter a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.\n\n\n;See also\n* The Game of Chaos\n\n", "solution": "import argparse\nimport random\nimport shapely.geometry as geometry\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\ndef main(args):\n # Styles\n plt.style.use(\"ggplot\")\n\n # Creating figure\n fig = plt.figure()\n line, = plt.plot([], [], \".\")\n\n # Limit axes\n plt.xlim(0, 1)\n plt.ylim(0, 1)\n\n # Titles\n title = \"Chaos Game\"\n plt.title(title)\n fig.canvas.set_window_title(title)\n\n # Getting data\n data = get_data(args.frames)\n\n # Creating animation\n line_ani = animation.FuncAnimation(\n fig=fig,\n func=update_line,\n frames=args.frames,\n fargs=(data, line),\n interval=args.interval,\n repeat=False\n )\n\n # To save the animation install ffmpeg and uncomment\n # line_ani.save(\"chaos_game.gif\")\n\n plt.show()\n\n\ndef get_data(n):\n \"\"\"\n Get data to plot\n \"\"\"\n leg = 1\n triangle = get_triangle(leg)\n cur_point = gen_point_within_poly(triangle)\n data = []\n for _ in range(n):\n data.append((cur_point.x, cur_point.y))\n cur_point = next_point(triangle, cur_point)\n return data\n\n\ndef get_triangle(n):\n \"\"\"\n Create right triangle\n \"\"\"\n ax = ay = 0.0\n a = ax, ay\n\n bx = 0.5 * n\n by = 0.75 * (n ** 2)\n b = bx, by\n\n cx = n\n cy = 0.0\n c = cx, cy\n\n triangle = geometry.Polygon([a, b, c])\n return triangle\n\n\ndef gen_point_within_poly(poly):\n \"\"\"\n Generate random point inside given polygon\n \"\"\"\n minx, miny, maxx, maxy = poly.bounds\n while True:\n x = random.uniform(minx, maxx)\n y = random.uniform(miny, maxy)\n point = geometry.Point(x, y)\n if point.within(poly):\n return point\n\n\ndef next_point(poly, point):\n \"\"\"\n Generate next point according to chaos game rules\n \"\"\"\n vertices = poly.boundary.coords[:-1] # Last point is the same as the first one\n random_vertex = geometry.Point(random.choice(vertices))\n line = geometry.linestring.LineString([point, random_vertex])\n return line.centroid\n\n\ndef update_line(num, data, line):\n \"\"\"\n Update line with new points\n \"\"\"\n new_data = zip(*data[:num]) or [(), ()]\n line.set_data(new_data)\n return line,\n\n\nif __name__ == \"__main__\":\n arg_parser = argparse.ArgumentParser(description=\"Chaos Game by Suenweek (c) 2017\")\n arg_parser.add_argument(\"-f\", dest=\"frames\", type=int, default=1000)\n arg_parser.add_argument(\"-i\", dest=\"interval\", type=int, default=10)\n\n main(arg_parser.parse_args())\n\n"} {"title": "Check Machin-like formulas", "language": "Python", "task": "Machin-like formulas are useful for efficiently computing numerical approximations for \\pi\n\n\n;Task:\nVerify the following Machin-like formulas are correct by calculating the value of '''tan''' (''right hand side)'' for each equation using exact arithmetic and showing they equal '''1''':\n\n: {\\pi\\over4} = \\arctan{1\\over2} + \\arctan{1\\over3} \n: {\\pi\\over4} = 2 \\arctan{1\\over3} + \\arctan{1\\over7}\n: {\\pi\\over4} = 4 \\arctan{1\\over5} - \\arctan{1\\over239}\n: {\\pi\\over4} = 5 \\arctan{1\\over7} + 2 \\arctan{3\\over79}\n: {\\pi\\over4} = 5 \\arctan{29\\over278} + 7 \\arctan{3\\over79}\n: {\\pi\\over4} = \\arctan{1\\over2} + \\arctan{1\\over5} + \\arctan{1\\over8} \n: {\\pi\\over4} = 4 \\arctan{1\\over5} - \\arctan{1\\over70} + \\arctan{1\\over99} \n: {\\pi\\over4} = 5 \\arctan{1\\over7} + 4 \\arctan{1\\over53} + 2 \\arctan{1\\over4443}\n: {\\pi\\over4} = 6 \\arctan{1\\over8} + 2 \\arctan{1\\over57} + \\arctan{1\\over239}\n: {\\pi\\over4} = 8 \\arctan{1\\over10} - \\arctan{1\\over239} - 4 \\arctan{1\\over515}\n: {\\pi\\over4} = 12 \\arctan{1\\over18} + 8 \\arctan{1\\over57} - 5 \\arctan{1\\over239}\n: {\\pi\\over4} = 16 \\arctan{1\\over21} + 3 \\arctan{1\\over239} + 4 \\arctan{3\\over1042}\n: {\\pi\\over4} = 22 \\arctan{1\\over28} + 2 \\arctan{1\\over443} - 5 \\arctan{1\\over1393} - 10 \\arctan{1\\over11018}\n: {\\pi\\over4} = 22 \\arctan{1\\over38} + 17 \\arctan{7\\over601} + 10 \\arctan{7\\over8149}\n: {\\pi\\over4} = 44 \\arctan{1\\over57} + 7 \\arctan{1\\over239} - 12 \\arctan{1\\over682} + 24 \\arctan{1\\over12943}\n: {\\pi\\over4} = 88 \\arctan{1\\over172} + 51 \\arctan{1\\over239} + 32 \\arctan{1\\over682} + 44 \\arctan{1\\over5357} + 68 \\arctan{1\\over12943}\n\nand confirm that the following formula is ''incorrect'' by showing '''tan''' (''right hand side)'' is ''not'' '''1''':\n\n: {\\pi\\over4} = 88 \\arctan{1\\over172} + 51 \\arctan{1\\over239} + 32 \\arctan{1\\over682} + 44 \\arctan{1\\over5357} + 68 \\arctan{1\\over12944}\n\nThese identities are useful in calculating the values:\n: \\tan(a + b) = {\\tan(a) + \\tan(b) \\over 1 - \\tan(a) \\tan(b)}\n\n: \\tan\\left(\\arctan{a \\over b}\\right) = {a \\over b}\n\n: \\tan(-a) = -\\tan(a)\n\nYou can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input.\n\nNote: to formally prove the formula correct, it would have to be shown that ''{-3 pi \\over 4} < right hand side < {5 pi \\over 4}'' due to ''\\tan()'' periodicity.\n\n\n", "solution": "import re\nfrom fractions import Fraction\nfrom pprint import pprint as pp\n\n\nequationtext = '''\\\n pi/4 = arctan(1/2) + arctan(1/3) \n pi/4 = 2*arctan(1/3) + arctan(1/7)\n pi/4 = 4*arctan(1/5) - arctan(1/239)\n pi/4 = 5*arctan(1/7) + 2*arctan(3/79)\n pi/4 = 5*arctan(29/278) + 7*arctan(3/79)\n pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8) \n pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99) \n pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)\n pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)\n pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)\n pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)\n pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)\n pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)\n pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)\n pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)\n pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)\n pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)\n'''\n\ndef parse_eqn(equationtext=equationtext):\n eqn_re = re.compile(r\"\"\"(?mx)\n (?P ^ \\s* pi/4 \\s* = \\s*)? # LHS of equation\n (?: # RHS\n \\s* (?P [+-])? \\s* \n (?: (?P \\d+) \\s* \\*)? \n \\s* arctan\\( (?P \\d+) / (?P \\d+)\n )\"\"\")\n\n found = eqn_re.findall(equationtext)\n machins, part = [], []\n for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):\n if lhs and part:\n machins.append(part)\n part = []\n part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1),\n Fraction(int(numer), (int(denom) if denom else 1)) ) )\n machins.append(part)\n return machins\n\n\ndef tans(xs):\n xslen = len(xs)\n if xslen == 1:\n return tanEval(*xs[0])\n aa, bb = xs[:xslen//2], xs[xslen//2:]\n a, b = tans(aa), tans(bb)\n return (a + b) / (1 - a * b)\n\ndef tanEval(coef, f):\n if coef == 1:\n return f\n if coef < 0:\n return -tanEval(-coef, f)\n ca = coef // 2\n cb = coef - ca\n a, b = tanEval(ca, f), tanEval(cb, f)\n return (a + b) / (1 - a * b)\n\n\nif __name__ == '__main__':\n machins = parse_eqn()\n #pp(machins, width=160)\n for machin, eqn in zip(machins, equationtext.split('\\n')):\n ans = tans(machin)\n print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))"} {"title": "Check input device is a terminal", "language": "Python", "task": "Demonstrate how to check whether the input device is a terminal or not.\n\n\n;Related task:\n* [[Check output device is a terminal]]\n\n", "solution": "from sys import stdin\nif stdin.isatty():\n print(\"Input comes from tty.\")\nelse:\n print(\"Input doesn't come from tty.\")"} {"title": "Check output device is a terminal", "language": "Python", "task": "Demonstrate how to check whether the output device is a terminal or not.\n\n\n;Related task:\n* [[Check input device is a terminal]]\n\n", "solution": "from sys import stdout\nif stdout.isatty():\n print 'The output device is a teletype. Or something like a teletype.'\nelse:\n print 'The output device isn\\'t like a teletype.'"} {"title": "Cheryl's birthday", "language": "Python 3", "task": "Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.\n\nCheryl gave them a list of ten possible dates:\n May 15, May 16, May 19\n June 17, June 18\n July 14, July 16\n August 14, August 15, August 17\n\nCheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.\n 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n 3) Albert: Then I also know when Cheryl's birthday is.\n\n\n;Task\nWrite a computer program to deduce, by successive elimination, Cheryl's birthday.\n\n\n;Related task:\n* [[Sum and Product Puzzle]]\n\n\n;References\n* Wikipedia article of the same name.\n* Tuple Relational Calculus\n\n", "solution": "'''Cheryl's Birthday'''\n\nfrom itertools import groupby\nfrom re import split\n\n\n# main :: IO ()\ndef main():\n '''Derivation of the date.'''\n\n month, day = 0, 1\n print(\n # (3 :: A \"Then I also know\")\n # (A's month contains only one remaining day)\n uniquePairing(month)(\n # (2 :: B \"I know now\")\n # (B's day is paired with only one remaining month)\n uniquePairing(day)(\n # (1 :: A \"I know that Bernard does not know\")\n # (A's month is not among those with unique days)\n monthsWithUniqueDays(False)([\n # 0 :: Cheryl's list:\n tuple(x.split()) for x in\n split(\n ', ',\n 'May 15, May 16, May 19, ' +\n 'June 17, June 18, ' +\n 'July 14, July 16, ' +\n 'Aug 14, Aug 15, Aug 17'\n )\n ])\n )\n )\n )\n\n\n# ------------------- QUERY FUNCTIONS --------------------\n\n# monthsWithUniqueDays :: Bool -> [(Month, Day)] -> [(Month, Day)]\ndef monthsWithUniqueDays(blnInclude):\n '''The subset of months with (or without) unique days.\n '''\n def go(xs):\n month, day = 0, 1\n months = [fst(x) for x in uniquePairing(day)(xs)]\n return [\n md for md in xs\n if blnInclude or not (md[month] in months)\n ]\n return go\n\n\n# uniquePairing :: DatePart -> [(Month, Day)] -> [(Month, Day)]\ndef uniquePairing(i):\n '''Subset of months (or days) with a unique intersection.\n '''\n def go(xs):\n def inner(md):\n dct = md[i]\n uniques = [\n k for k in dct.keys()\n if 1 == len(dct[k])\n ]\n return [tpl for tpl in xs if tpl[i] in uniques]\n return inner\n return ap(bindPairs)(go)\n\n\n# bindPairs :: [(Month, Day)] ->\n# ((Dict String [String], Dict String [String])\n# -> [(Month, Day)]) -> [(Month, Day)]\ndef bindPairs(xs):\n '''List monad injection operator for lists\n of (Month, Day) pairs.\n '''\n return lambda f: f(\n (\n dictFromPairs(xs),\n dictFromPairs(\n [(b, a) for (a, b) in xs]\n )\n )\n )\n\n\n# dictFromPairs :: [(Month, Day)] -> Dict Text [Text]\ndef dictFromPairs(xs):\n '''A dictionary derived from a list of\n month day pairs.\n '''\n return {\n k: [snd(x) for x in m] for k, m in groupby(\n sorted(xs, key=fst), key=fst\n )\n }\n\n\n# ----------------------- GENERIC ------------------------\n\n# ap :: (a -> b -> c) -> (a -> b) -> a -> c\ndef ap(f):\n '''Applicative instance for functions.\n '''\n def go(g):\n def fxgx(x):\n return f(x)(\n g(x)\n )\n return fxgx\n return go\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First component of a pair.\n '''\n return tpl[0]\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second component of a pair.\n '''\n return tpl[1]\n\n\nif __name__ == '__main__':\n main()"} {"title": "Chinese remainder theorem", "language": "Python", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "# Python 2.7\ndef chinese_remainder(n, a):\n sum = 0\n prod = reduce(lambda a, b: a*b, n)\n\n for n_i, a_i in zip(n, a):\n p = prod / n_i\n sum += a_i * mul_inv(p, n_i) * p\n return sum % prod\n\n\ndef mul_inv(a, b):\n b0 = b\n x0, x1 = 0, 1\n if b == 1: return 1\n while a > 1:\n q = a / b\n a, b = b, a%b\n x0, x1 = x1 - q * x0, x0\n if x1 < 0: x1 += b0\n return x1\n\nif __name__ == '__main__':\n n = [3, 5, 7]\n a = [2, 3, 2]\n print chinese_remainder(n, a)"} {"title": "Chinese remainder theorem", "language": "Python 3.7", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "'''Chinese remainder theorem'''\n\nfrom operator import (add, mul)\nfrom functools import reduce\n\n\n# cnRemainder :: [Int] -> [Int] -> Either String Int\ndef cnRemainder(ms):\n '''Chinese remainder theorem.\n (moduli, residues) -> Either explanation or solution\n '''\n def go(ms, rs):\n mp = numericProduct(ms)\n cms = [(mp // x) for x in ms]\n\n def possibleSoln(invs):\n return Right(\n sum(map(\n mul,\n cms, map(mul, rs, invs)\n )) % mp\n )\n return bindLR(\n zipWithEither(modMultInv)(cms)(ms)\n )(possibleSoln)\n\n return lambda rs: go(ms, rs)\n\n\n# modMultInv :: Int -> Int -> Either String Int\ndef modMultInv(a, b):\n '''Modular multiplicative inverse.'''\n x, y = eGcd(a, b)\n return Right(x) if 1 == (a * x + b * y) else (\n Left('no modular inverse for ' + str(a) + ' and ' + str(b))\n )\n\n\n# egcd :: Int -> Int -> (Int, Int)\ndef eGcd(a, b):\n '''Extended greatest common divisor.'''\n def go(a, b):\n if 0 == b:\n return (1, 0)\n else:\n q, r = divmod(a, b)\n (s, t) = go(b, r)\n return (t, s - q * t)\n return go(a, b)\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Tests of soluble and insoluble cases.'''\n\n print(\n fTable(\n __doc__ + ':\\n\\n (moduli, residues) -> ' + (\n 'Either solution or explanation\\n'\n )\n )(repr)(\n either(compose(quoted(\"'\"))(curry(add)('No solution: ')))(\n compose(quoted(' '))(repr)\n )\n )(uncurry(cnRemainder))([\n ([10, 4, 12], [11, 12, 13]),\n ([11, 12, 13], [10, 4, 12]),\n ([10, 4, 9], [11, 22, 19]),\n ([3, 5, 7], [2, 3, 2]),\n ([2, 3, 2], [3, 5, 7])\n ])\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.'''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n# any :: (a -> Bool) -> [a] -> Bool\n\n\ndef any_(p):\n '''True if p(x) holds for at least\n one item in xs.'''\n def go(xs):\n for x in xs:\n if p(x):\n return True\n return False\n return lambda xs: go(xs)\n\n\n# bindLR (>>=) :: Either a -> (a -> Either b) -> Either b\ndef bindLR(m):\n '''Either monad injection operator.\n Two computations sequentially composed,\n with any value produced by the first\n passed as an argument to the second.'''\n return lambda mf: (\n mf(m.get('Right')) if None is m.get('Left') else m\n )\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# curry :: ((a, b) -> c) -> a -> b -> c\ndef curry(f):\n '''A curried function derived\n from an uncurried function.'''\n return lambda a: lambda b: f(a, b)\n\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.'''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function ->\n fx display function ->\n f -> value list -> tabular string.'''\n def go(xShow, fxShow, f, xs):\n w = max(map(compose(len)(xShow), xs))\n return s + '\\n' + '\\n'.join([\n xShow(x).rjust(w, ' ') + (' -> ') + fxShow(f(x))\n for x in xs\n ])\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# numericProduct :: [Num] -> Num\ndef numericProduct(xs):\n '''The arithmetic product of all numbers in xs.'''\n return reduce(mul, xs, 1)\n\n\n# partitionEithers :: [Either a b] -> ([a],[b])\ndef partitionEithers(lrs):\n '''A list of Either values partitioned into a tuple\n of two lists, with all Left elements extracted\n into the first list, and Right elements\n extracted into the second list.\n '''\n def go(a, x):\n ls, rs = a\n r = x.get('Right')\n return (ls + [x.get('Left')], rs) if None is r else (\n ls, rs + [r]\n )\n return reduce(go, lrs, ([], []))\n\n\n# quoted :: Char -> String -> String\ndef quoted(c):\n '''A string flanked on both sides\n by a specified quote character.\n '''\n return lambda s: c + s + c\n\n\n# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n '''A function over a tuple,\n derived from a curried function.'''\n return lambda xy: f(xy[0])(xy[1])\n\n\n# zipWithEither :: (a -> b -> Either String c)\n# -> [a] -> [b] -> Either String [c]\ndef zipWithEither(f):\n '''Either a list of results if f succeeds with every pair\n in the zip of xs and ys, or an explanatory string\n if any application of f returns no result.\n '''\n def go(xs, ys):\n ls, rs = partitionEithers(map(f, xs, ys))\n return Left(ls[0]) if ls else Right(rs)\n return lambda xs: lambda ys: go(xs, ys)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Chinese zodiac", "language": "Python from Ruby", "task": "Determine the Chinese zodiac sign and related associations for a given year.\nTraditionally, the Chinese have counted years using two lists of labels, one of length 10 (the \"celestial stems\") and one of length 12 (the \"terrestrial branches\"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.\n\nThe celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.\n\nThus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.\n\n;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\n;Requisite information:\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. \n* Each element gets two consecutive years; a yang followed by a yin.\n* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.\n\nThus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. \n\n;Information for optional task:\n* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).\n", "solution": "# coding: utf-8\n\nfrom __future__ import print_function\nfrom datetime import datetime\n\npinyin = {\n '\u7532': 'ji\u0103',\n '\u4e59': 'y\u012d',\n '\u4e19': 'b\u012dng',\n '\u4e01': 'd\u012bng',\n '\u620a': 'w\u00f9',\n '\u5df1': 'j\u012d',\n '\u5e9a': 'g\u0113ng',\n '\u8f9b': 'x\u012bn',\n '\u58ec': 'r\u00e9n',\n '\u7678': 'g\u016di',\n\n '\u5b50': 'z\u012d',\n '\u4e11': 'ch\u014fu',\n '\u5bc5': 'y\u00edn',\n '\u536f': 'm\u0103o',\n '\u8fb0': 'ch\u00e9n',\n '\u5df3': 's\u00ec',\n '\u5348': 'w\u016d',\n '\u672a': 'w\u00e8i',\n '\u7533': 'sh\u0113n',\n '\u9149': 'y\u014fu',\n '\u620c': 'x\u016b',\n '\u4ea5': 'h\u00e0i'\n}\n\nanimals = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake',\n 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig']\nelements = ['Wood', 'Fire', 'Earth', 'Metal', 'Water']\n\ncelestial = ['\u7532', '\u4e59', '\u4e19', '\u4e01', '\u620a', '\u5df1', '\u5e9a', '\u8f9b', '\u58ec', '\u7678']\nterrestrial = ['\u5b50', '\u4e11', '\u5bc5', '\u536f', '\u8fb0', '\u5df3', '\u5348', '\u672a', '\u7533', '\u9149', '\u620c', '\u4ea5']\naspects = ['yang', 'yin']\n\n\ndef calculate(year):\n BASE = 4\n year = int(year)\n cycle_year = year - BASE\n stem_number = cycle_year % 10\n stem_han = celestial[stem_number]\n stem_pinyin = pinyin[stem_han]\n element_number = stem_number // 2\n element = elements[element_number]\n branch_number = cycle_year % 12\n branch_han = terrestrial[branch_number]\n branch_pinyin = pinyin[branch_han]\n animal = animals[branch_number]\n aspect_number = cycle_year % 2\n aspect = aspects[aspect_number]\n index = cycle_year % 60 + 1\n print(\"{}: {}{} ({}-{}, {} {}; {} - year {} of the cycle)\"\n .format(year, stem_han, branch_han,\n stem_pinyin, branch_pinyin, element, animal, aspect, index))\n\n\ncurrent_year = datetime.now().year\nyears = [1935, 1938, 1968, 1972, 1976, current_year]\nfor year in years:\n calculate(year)"} {"title": "Chinese zodiac", "language": "Python 3.7", "task": "Determine the Chinese zodiac sign and related associations for a given year.\nTraditionally, the Chinese have counted years using two lists of labels, one of length 10 (the \"celestial stems\") and one of length 12 (the \"terrestrial branches\"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.\n\nThe celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.\n\nThus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.\n\n;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\n;Requisite information:\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. \n* Each element gets two consecutive years; a yang followed by a yin.\n* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.\n\nThus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. \n\n;Information for optional task:\n* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).\n", "solution": "'''Chinese zodiac'''\n\nfrom functools import (reduce)\nfrom datetime import datetime\n\n\n# TRADITIONAL STRINGS -------------------------------------\n\n# zodiacNames :: Dict\ndef zodiacNames():\n '''\u5929\u5e72 tiangan \u2013 10 heavenly stems\n \u5730\u652f dizhi \u2013 12 terrestrial branches\n \u4e94\u884c wuxing \u2013 5 elements\n \u751f\u8096 shengxiao \u2013 12 symbolic animals\n \u9634\u9633 yinyang - dark and light\n '''\n return dict(\n zip(\n ['tian', 'di', 'wu', 'sx', 'yy'],\n map(\n lambda tpl: list(\n zip(* [tpl[0]] + list(\n map(\n lambda x: x.split(),\n tpl[1:])\n ))\n ),\n [\n # \u5929\u5e72 tiangan \u2013 10 heavenly stems\n ('\u7532\u4e59\u4e19\u4e01\u620a\u5df1\u5e9a\u8f9b\u58ec\u7678',\n 'ji\u0103 y\u012d b\u012dng d\u012bng w\u00f9 j\u012d g\u0113ng x\u012bn r\u00e9n g\u016di'),\n\n # \u5730\u652f dizhi \u2013 12 terrestrial branches\n ('\u5b50\u4e11\u5bc5\u536f\u8fb0\u5df3\u5348\u672a\u7533\u9149\u620c\u4ea5',\n 'z\u012d ch\u014fu y\u00edn m\u0103o ch\u00e9n s\u00ec w\u016d w\u00e8i sh\u0113n y\u014fu x\u016b h\u00e0i'),\n\n # \u4e94\u884c wuxing \u2013 5 elements\n ('\u6728\u706b\u571f\u91d1\u6c34',\n 'm\u00f9 hu\u01d2 t\u01d4 j\u012bn shu\u01d0',\n 'wood fire earth metal water'),\n\n # \u5341\u4e8c\u751f\u8096 shengxiao \u2013 12 symbolic animals\n ('\u9f20\u725b\u864e\u5154\u9f8d\u86c7\u99ac\u7f8a\u7334\u9e21\u72d7\u8c6c',\n 'sh\u01d4 ni\u00fa h\u01d4 t\u00f9 l\u00f3ng sh\u00e9 m\u01ce y\u00e1ng h\u00f3u j\u012b g\u01d2u zh\u016b',\n 'rat ox tiger rabbit dragon snake horse goat ' +\n 'monkey rooster dog pig'\n ),\n\n # \u9634\u9633 yinyang\n ('\u9633\u9634', 'y\u00e1ng y\u012bn')\n ]\n )))\n\n\n# zodiacYear :: Dict -> [[String]]\ndef zodiacYear(dct):\n '''A string of strings containing the\n Chinese zodiac tokens for a given year.\n '''\n def tokens(y):\n iYear = y - 4\n iStem = iYear % 10\n iBranch = iYear % 12\n (hStem, pStem) = dct['tian'][iStem]\n (hBranch, pBranch) = dct['di'][iBranch]\n yy = iYear % 2\n return [\n [str(y), '', ''],\n [\n hStem + hBranch,\n pStem + pBranch,\n str((iYear % 60) + 1) + '/60'\n ],\n list(dct['wu'][iStem // 2]),\n list(dct['sx'][iBranch]),\n list(dct['yy'][int(yy)]) + ['dark' if yy else 'light']\n ]\n return lambda year: tokens(year)\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Writing out wiki tables displaying Chinese zodiac\n details for a given list of years.\n '''\n print('\\n'.join(\n list(map(\n zodiacTable(zodiacNames()),\n [\n 1935, 1938, 1949,\n 1968, 1972, 1976,\n datetime.now().year\n ]\n ))\n ))\n\n\n# WIKI TABLES --------------------------------------------\n\n# zodiacTable :: Dict -> Int -> String\ndef zodiacTable(tokens):\n '''A wiki table displaying Chinese zodiac\n details for a a given year.\n '''\n return lambda y: wikiTable({\n 'class': 'wikitable',\n 'colwidth': '70px'\n })(transpose(zodiacYear(tokens)(y)))\n\n\n# wikiTable :: Dict -> [[a]] -> String\ndef wikiTable(opts):\n '''List of lists rendered as a wiki table string.'''\n def colWidth():\n return 'width:' + opts['colwidth'] + '; ' if (\n 'colwidth' in opts\n ) else ''\n\n def cellStyle():\n return opts['cell'] if 'cell' in opts else ''\n\n return lambda rows: '{| ' + reduce(\n lambda a, k: (\n a + k + '=\"' + opts[k] + '\" ' if k in opts else a\n ),\n ['class', 'style'],\n ''\n ) + '\\n' + '\\n|-\\n'.join(\n '\\n'.join(\n ('|' if (0 != i and ('cell' not in opts)) else (\n '|style=\"' + colWidth() + cellStyle() + '\"|'\n )) + (\n str(x) or ' '\n ) for x in row\n ) for i, row in enumerate(rows)\n ) + '\\n|}\\n\\n'\n\n\n# GENERIC -------------------------------------------------\n\n# transpose :: Matrix a -> Matrix a\ndef transpose(m):\n '''The rows and columns of the argument transposed.\n (The matrix containers and rows can be lists or tuples).'''\n if m:\n inner = type(m[0])\n z = zip(*m)\n return (type(m))(\n map(inner, z) if tuple != inner else z\n )\n else:\n return m\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Church numerals", "language": "Python 3.7", "task": "In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.\n\n* '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.\n* '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)'''\n* '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))'''\n* and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.\n\n\nArithmetic operations on natural numbers can be similarly represented as functions on Church numerals.\n\nIn your language define:\n\n* Church Zero,\n* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),\n* functions for Addition, Multiplication and Exponentiation over Church numerals,\n* a function to convert integers to corresponding Church numerals,\n* and a function to convert Church numerals to corresponding integers.\n\n\nYou should:\n\n* Derive Church numerals three and four in terms of Church zero and a Church successor function.\n* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,\n* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,\n* convert each result back to an integer, and return it or print it to the console.\n\n\n", "solution": "'''Church numerals'''\n\nfrom itertools import repeat\nfrom functools import reduce\n\n\n# ----- CHURCH ENCODINGS OF NUMERALS AND OPERATIONS ------\n\ndef churchZero():\n '''The identity function.\n No applications of any supplied f\n to its argument.\n '''\n return lambda f: identity\n\n\ndef churchSucc(cn):\n '''The successor of a given\n Church numeral. One additional\n application of f. Equivalent to\n the arithmetic addition of one.\n '''\n return lambda f: compose(f)(cn(f))\n\n\ndef churchAdd(m):\n '''The arithmetic sum of two Church numerals.'''\n return lambda n: lambda f: compose(m(f))(n(f))\n\n\ndef churchMult(m):\n '''The arithmetic product of two Church numerals.'''\n return lambda n: compose(m)(n)\n\n\ndef churchExp(m):\n '''Exponentiation of Church numerals. m^n'''\n return lambda n: n(m)\n\n\ndef churchFromInt(n):\n '''The Church numeral equivalent of\n a given integer.\n '''\n return lambda f: (\n foldl\n (compose)\n (identity)\n (replicate(n)(f))\n )\n\n\n# OR, alternatively:\ndef churchFromInt_(n):\n '''The Church numeral equivalent of a given\n integer, by explicit recursion.\n '''\n if 0 == n:\n return churchZero()\n else:\n return churchSucc(churchFromInt(n - 1))\n\n\ndef intFromChurch(cn):\n '''The integer equivalent of a\n given Church numeral.\n '''\n return cn(succ)(0)\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n 'Tests'\n\n cThree = churchFromInt(3)\n cFour = churchFromInt(4)\n\n print(list(map(intFromChurch, [\n churchAdd(cThree)(cFour),\n churchMult(cThree)(cFour),\n churchExp(cFour)(cThree),\n churchExp(cThree)(cFour),\n ])))\n\n\n# ------------------ GENERIC FUNCTIONS -------------------\n\n# compose (flip (.)) :: (a -> b) -> (b -> c) -> a -> c\ndef compose(f):\n '''A left to right composition of two\n functions f and g'''\n return lambda g: lambda x: g(f(x))\n\n\n# foldl :: (a -> b -> a) -> a -> [b] -> a\ndef foldl(f):\n '''Left to right reduction of a list,\n using the binary operator f, and\n starting with an initial value a.\n '''\n def go(acc, xs):\n return reduce(lambda a, x: f(a)(x), xs, acc)\n return lambda acc: lambda xs: go(acc, xs)\n\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# replicate :: Int -> a -> [a]\ndef replicate(n):\n '''A list of length n in which every\n element has the value x.\n '''\n return lambda x: repeat(x, n)\n\n\n# succ :: Enum a => a -> a\ndef succ(x):\n '''The successor of a value.\n For numeric types, (1 +).\n '''\n return 1 + x if isinstance(x, int) else (\n chr(1 + ord(x))\n )\n\n\nif __name__ == '__main__':\n main()"} {"title": "Circles of given radius through two points", "language": "Python", "task": "2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points. \n;Exceptions:\n# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.\n# If the points are too far apart then no circles can be drawn.\n\n\n;Task detail:\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.\n* Show here the output for the following inputs:\n\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n\n\n;Related task:\n* [[Total circles area]].\n\n\n;See also:\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel\n\n", "solution": "from collections import namedtuple\nfrom math import sqrt\n\nPt = namedtuple('Pt', 'x, y')\nCircle = Cir = namedtuple('Circle', 'x, y, r')\n\ndef circles_from_p1p2r(p1, p2, r):\n 'Following explanation at http://mathforum.org/library/drmath/view/53027.html'\n if r == 0.0:\n raise ValueError('radius of zero')\n (x1, y1), (x2, y2) = p1, p2\n if p1 == p2:\n raise ValueError('coincident points gives infinite number of Circles')\n # delta x, delta y between points\n dx, dy = x2 - x1, y2 - y1\n # dist between points\n q = sqrt(dx**2 + dy**2)\n if q > 2.0*r:\n raise ValueError('separation of points > diameter')\n # halfway point\n x3, y3 = (x1+x2)/2, (y1+y2)/2\n # distance along the mirror line\n d = sqrt(r**2-(q/2)**2)\n # One answer\n c1 = Cir(x = x3 - d*dy/q,\n y = y3 + d*dx/q,\n r = abs(r))\n # The other answer\n c2 = Cir(x = x3 + d*dy/q,\n y = y3 - d*dx/q,\n r = abs(r))\n return c1, c2\n\nif __name__ == '__main__':\n for p1, p2, r in [(Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 2.0),\n (Pt(0.0000, 2.0000), Pt(0.0000, 0.0000), 1.0),\n (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 2.0),\n (Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 0.5),\n (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 0.0)]:\n print('Through points:\\n %r,\\n %r\\n and radius %f\\nYou can construct the following circles:'\n % (p1, p2, r))\n try:\n print(' %r\\n %r\\n' % circles_from_p1p2r(p1, p2, r))\n except ValueError as v:\n print(' ERROR: %s\\n' % (v.args[0],))"} {"title": "Cistercian numerals", "language": "Python", "task": "Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.\n\n;How they work\nAll Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:\n\n:* The '''upper-right''' quadrant represents the '''ones''' place.\n:* The '''upper-left''' quadrant represents the '''tens''' place.\n:* The '''lower-right''' quadrant represents the '''hundreds''' place.\n:* The '''lower-left''' quadrant represents the '''thousands''' place.\n\nPlease consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]\n\n;Task\n\n:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).\n\n:* Use the routine to show the following Cistercian numerals:\n\n::* 0\n::* 1\n::* 20\n::* 300\n::* 4000\n::* 5555\n::* 6789\n::* And a number of your choice!\n\n;Notes\nDue to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.\n\n;See also\n\n:* '''Numberphile - The Forgotten Number System'''\n:* '''dcode.fr - Online Cistercian numeral converter'''\n", "solution": "# -*- coding: utf-8 -*-\n\"\"\"\nSome UTF-8 chars used:\n \n\u203e\t8254\t203E\t‾\tOVERLINE\n\u2503\t9475\t2503\t \tBOX DRAWINGS HEAVY VERTICAL\n\u2571\t9585\t2571\t \tBOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT\n\u2572\t9586\t2572\t \tBOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT\n\u25f8\t9720\t25F8\t \tUPPER LEFT TRIANGLE\n\u25f9\t9721\t25F9\t \tUPPER RIGHT TRIANGLE\n\u25fa\t9722\t25FA\t \tLOWER LEFT TRIANGLE\n\u25fb\t9723\t25FB\t \tWHITE MEDIUM SQUARE\n\u25ff\t9727\t25FF\t \tLOWER RIGHT TRIANGLE\n\n\"\"\"\n\n#%% digit sections\n\ndef _init():\n \"digit sections for forming numbers\"\n digi_bits = \"\"\"\n#0 1 2 3 4 5 6 7 8 9\n#\n . \u203e _ \u2572 \u2571 \u25f8 .| \u203e| _| \u25fb\n#\n . \u203e _ \u2571 \u2572 \u25f9 |. |\u203e |_ \u25fb\n#\n . _ \u203e \u2571 \u2572 \u25fa .| _| \u203e| \u25fb\n#\n . _ \u203e \u2572 \u2571 \u25ff |. |_ |\u203e \u25fb\n \n\"\"\".strip()\n\n lines = [[d.replace('.', ' ') for d in ln.strip().split()]\n for ln in digi_bits.strip().split('\\n')\n if '#' not in ln]\n formats = '<2 >2 <2 >2'.split()\n digits = [[f\"{dig:{f}}\" for dig in line]\n for f, line in zip(formats, lines)]\n\n return digits\n\n_digits = _init()\n\n\n#%% int to 3-line strings\ndef _to_digits(n):\n assert 0 <= n < 10_000 and int(n) == n\n \n return [int(digit) for digit in f\"{int(n):04}\"][::-1]\n\ndef num_to_lines(n):\n global _digits\n d = _to_digits(n)\n lines = [\n ''.join((_digits[1][d[1]], '\u2503', _digits[0][d[0]])),\n ''.join((_digits[0][ 0], '\u2503', _digits[0][ 0])),\n ''.join((_digits[3][d[3]], '\u2503', _digits[2][d[2]])),\n ]\n \n return lines\n\ndef cjoin(c1, c2, spaces=' '):\n return [spaces.join(by_row) for by_row in zip(c1, c2)]\n\n#%% main\nif __name__ == '__main__':\n #n = 6666\n #print(f\"Arabic {n} to Cistercian:\\n\")\n #print('\\n'.join(num_to_lines(n)))\n \n for pow10 in range(4): \n step = 10 ** pow10\n print(f'\\nArabic {step}-to-{9*step} by {step} in Cistercian:\\n')\n lines = num_to_lines(step)\n for n in range(step*2, step*10, step):\n lines = cjoin(lines, num_to_lines(n))\n print('\\n'.join(lines))\n \n\n numbers = [0, 5555, 6789, 6666]\n print(f'\\nArabic {str(numbers)[1:-1]} in Cistercian:\\n')\n lines = num_to_lines(numbers[0])\n for n in numbers[1:]:\n lines = cjoin(lines, num_to_lines(n))\n print('\\n'.join(lines))"} {"title": "Closures/Value capture", "language": "Python", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "funcs = []\nfor i in range(10):\n funcs.append((lambda i: lambda: i * i)(i))\nprint funcs[3]() # prints 9"} {"title": "Colorful numbers", "language": "Python", "task": "A '''colorful number''' is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.\n\n\n;E.G.\n\n24753 is a colorful number. 2, 4, 7, 5, 3, (2x4)8, (4x7)28, (7x5)35, (5x3)15, (2x4x7)56, (4x7x5)140, (7x5x3)105, (2x4x7x5)280, (4x7x5x3)420, (2x4x7x5x3)840\n\nEvery product is unique.\n\n\n2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2x3)'''6''', (3x4)12, (4x6)24, (2x3x4)48, (3x4x6)72, (2x3x4x6)144\n\nThe product '''6''' is repeated.\n\n\nSingle digit numbers '''are''' considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.\n\n\n;Task\n\n* Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.\n* Use that routine to find all of the colorful numbers less than 100.\n* Use that routine to find the largest possible colorful number.\n\n\n;Stretch\n\n* Find and display the count of colorful numbers in each order of magnitude.\n* Find and show the total count of '''all''' colorful numbers.\n\n\n''Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.''\n\n", "solution": "from math import prod\n\nlargest = [0]\n\ndef iscolorful(n):\n if 0 <= n < 10:\n return True\n dig = [int(c) for c in str(n)]\n if 1 in dig or 0 in dig or len(dig) > len(set(dig)):\n return False\n products = list(set(dig))\n for i in range(len(dig)):\n for j in range(i+2, len(dig)+1):\n p = prod(dig[i:j])\n if p in products:\n return False\n products.append(p)\n\n largest[0] = max(n, largest[0])\n return True\n\nprint('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')\nfor i in range(1, 101, 25):\n for j in range(25):\n if iscolorful(i + j):\n print(f'{i + j: 5,}', end='')\n print()\n\ncsum = 0\nfor i in range(8):\n j = 0 if i == 0 else 10**i\n k = 10**(i+1) - 1\n n = sum(iscolorful(x) for x in range(j, k+1))\n csum += n\n print(f'The count of colorful numbers between {j} and {k} is {n}.')\n\nprint(f'The largest possible colorful number is {largest[0]}.')\nprint(f'The total number of colorful numbers is {csum}.')\n"} {"title": "Colour bars/Display", "language": "Python", "task": "Display a series of vertical color bars across the width of the display. \n\nThe color bars should either use:\n:::* the system palette, or \n:::* the sequence of colors: \n::::::* black\n::::::* red\n::::::* green\n::::::* blue\n::::::* magenta\n::::::* cyan\n::::::* yellow\n::::::* white\n\n", "solution": "#!/usr/bin/env python\n#vertical coloured stripes in window in Python 2.7.1\n\nfrom livewires import *\n\nhoriz=640; vert=480\nbegin_graphics(width=horiz,height=vert,title=\"v_stripes\",background=Colour.black)\nNameColors=[\"black\",\"red\",\"green\",\"dark_blue\",\"purple\",\"blue\",\"yellow\",\"white\"]\nstepik=horiz/len(NameColors)\n\nfor index,each in enumerate(NameColors):\n\tExcStrng=\"set_colour(Colour.\"+each+\")\"\n\texec ExcStrng\n\tbox(index*stepik,0,(index+1)*stepik,vert,filled=1)\n\nwhile keys_pressed() != ['x']: # press x key to terminate program\n\tpass\n\nend_graphics()\n"} {"title": "Colour pinstripe/Printer", "language": "Python", "task": "The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.\n\nAfter the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).\n\nNote that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.\n\nOptionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.\n\n", "solution": "from turtle import *\nfrom PIL import Image\nimport time\nimport subprocess\n\n\"\"\"\n\nOnly works on Windows. Assumes that you have Ghostscript\ninstalled and in your path.\n\nhttps://www.ghostscript.com/download/gsdnld.html\n\nHard coded to 100 pixels per inch.\n\n\"\"\"\n\ncolors = [\"black\", \"red\", \"green\", \"blue\", \"magenta\", \"cyan\", \"yellow\", \"white\"]\n\nscreen = getscreen()\n\n# width and height in pixels\n# aspect ratio for 11 by 8.5 paper\n\ninch_width = 11.0\ninch_height = 8.5\n\npixels_per_inch = 100\n\npix_width = int(inch_width*pixels_per_inch)\npix_height = int(inch_height*pixels_per_inch)\n\nscreen.setup (width=pix_width, height=pix_height, startx=0, starty=0)\n\nscreen.screensize(pix_width,pix_height)\n\n# center is 0,0\n\n# get coordinates of the edges\n\nleft_edge = -screen.window_width()//2\n\nright_edge = screen.window_width()//2\n\nbottom_edge = -screen.window_height()//2\n\ntop_edge = screen.window_height()//2\n\n# draw quickly\n\nscreen.delay(0)\nscreen.tracer(5)\n\nfor inch in range(int(inch_width)-1):\n line_width = inch + 1\n pensize(line_width)\n colornum = 0\n\n min_x = left_edge + (inch * pixels_per_inch)\n max_x = left_edge + ((inch+1) * pixels_per_inch)\n \n for y in range(bottom_edge,top_edge,line_width):\n penup()\n pencolor(colors[colornum])\n colornum = (colornum + 1) % len(colors)\n setposition(min_x,y)\n pendown()\n setposition(max_x,y)\n \nscreen.getcanvas().postscript(file=\"striped.eps\")\n\n# convert to jpeg\n# won't work without Ghostscript.\n\nim = Image.open(\"striped.eps\")\nim.save(\"striped.jpg\")\n\n# Got idea from http://rosettacode.org/wiki/Colour_pinstripe/Printer#Go\n \nsubprocess.run([\"mspaint\", \"/pt\", \"striped.jpg\"])\n"} {"title": "Comma quibbling", "language": "Python", "task": "Comma quibbling is a task originally set by Eric Lippert in his blog.\n\n\n;Task:\n\nWrite a function to generate a string output which is the concatenation of input words from a list/sequence where:\n# An input of no words produces the output string of just the two brace characters \"{}\".\n# An input of just one word, e.g. [\"ABC\"], produces the output string of the word inside the two braces, e.g. \"{ABC}\".\n# An input of two words, e.g. [\"ABC\", \"DEF\"], produces the output string of the two words inside the two braces with the words separated by the string \" and \", e.g. \"{ABC and DEF}\".\n# An input of three or more words, e.g. [\"ABC\", \"DEF\", \"G\", \"H\"], produces the output string of all but the last word separated by \", \" with the last word separated by \" and \" and all within braces; e.g. \"{ABC, DEF, G and H}\".\n\n\nTest your function with the following series of inputs showing your output here on this page:\n* [] # (No input words).\n* [\"ABC\"]\n* [\"ABC\", \"DEF\"]\n* [\"ABC\", \"DEF\", \"G\", \"H\"]\n\n\nNote: Assume words are non-empty strings of uppercase characters for this task.\n\n", "solution": ">>> def strcat(sequence):\n return '{%s}' % ', '.join(sequence)[::-1].replace(',', 'dna ', 1)[::-1]\n\n>>> for seq in ([], [\"ABC\"], [\"ABC\", \"DEF\"], [\"ABC\", \"DEF\", \"G\", \"H\"]):\n print('Input: %-24r -> Output: %r' % (seq, strcat(seq)))\n\n\t\nInput: [] -> Output: '{}'\nInput: ['ABC'] -> Output: '{ABC}'\nInput: ['ABC', 'DEF'] -> Output: '{ABC and DEF}'\nInput: ['ABC', 'DEF', 'G', 'H'] -> Output: '{ABC, DEF, G and H}'\n>>> "} {"title": "Command-line arguments", "language": "Python", "task": "{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].\nSee also [[Program name]].\n\nFor parsing command line arguments intelligently, see [[Parsing command-line arguments]].\n\nExample command line:\n\n myprogram -c \"alpha beta\" -h \"gamma\"\n\n", "solution": "import sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)"} {"title": "Compare a list of strings", "language": "Python", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "from operator import (eq, lt)\n\n\nxs = [\"alpha\", \"beta\", \"gamma\", \"delta\", \"epsilon\", \"zeta\",\n \"eta\", \"theta\", \"iota\", \"kappa\", \"lambda\", \"mu\"]\n\nys = [\"alpha\", \"beta\", \"gamma\", \"delta\", \"epsilon\", \"zeta\",\n \"eta\", \"theta\", \"iota\", \"kappa\", \"lambda\", \"mu\"]\n\naz = sorted(xs)\n\nprint (\n all(map(eq, xs, ys)),\n\n all(map(lt, xs, xs[1:])),\n\n all(map(lt, az, az[1:]))\n)"} {"title": "Compiler/AST interpreter", "language": "Python", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n\n\n__TOC__\n\n", "solution": "from __future__ import print_function\nimport sys, shlex, operator\n\nnd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \\\nnd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \\\nnd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)\n\nall_syms = {\n \"Identifier\" : nd_Ident, \"String\" : nd_String,\n \"Integer\" : nd_Integer, \"Sequence\" : nd_Sequence,\n \"If\" : nd_If, \"Prtc\" : nd_Prtc,\n \"Prts\" : nd_Prts, \"Prti\" : nd_Prti,\n \"While\" : nd_While, \"Assign\" : nd_Assign,\n \"Negate\" : nd_Negate, \"Not\" : nd_Not,\n \"Multiply\" : nd_Mul, \"Divide\" : nd_Div,\n \"Mod\" : nd_Mod, \"Add\" : nd_Add,\n \"Subtract\" : nd_Sub, \"Less\" : nd_Lss,\n \"LessEqual\" : nd_Leq, \"Greater\" : nd_Gtr,\n \"GreaterEqual\": nd_Geq, \"Equal\" : nd_Eql,\n \"NotEqual\" : nd_Neq, \"And\" : nd_And,\n \"Or\" : nd_Or}\n\ninput_file = None\nglobals = {}\n\n#*** show error and exit\ndef error(msg):\n print(\"%s\" % (msg))\n exit(1)\n\nclass Node:\n def __init__(self, node_type, left = None, right = None, value = None):\n self.node_type = node_type\n self.left = left\n self.right = right\n self.value = value\n\n#***\ndef make_node(oper, left, right = None):\n return Node(oper, left, right)\n\n#***\ndef make_leaf(oper, n):\n return Node(oper, value = n)\n\n#***\ndef fetch_var(var_name):\n n = globals.get(var_name, None)\n if n == None:\n globals[var_name] = n = 0\n return n\n\n#***\ndef interp(x):\n global globals\n\n if x == None: return None\n elif x.node_type == nd_Integer: return int(x.value)\n elif x.node_type == nd_Ident: return fetch_var(x.value)\n elif x.node_type == nd_String: return x.value\n\n elif x.node_type == nd_Assign:\n globals[x.left.value] = interp(x.right)\n return None\n elif x.node_type == nd_Add: return interp(x.left) + interp(x.right)\n elif x.node_type == nd_Sub: return interp(x.left) - interp(x.right)\n elif x.node_type == nd_Mul: return interp(x.left) * interp(x.right)\n # use C like division semantics\n # another way: abs(x) / abs(y) * cmp(x, 0) * cmp(y, 0)\n elif x.node_type == nd_Div: return int(float(interp(x.left)) / interp(x.right))\n elif x.node_type == nd_Mod: return int(float(interp(x.left)) % interp(x.right))\n elif x.node_type == nd_Lss: return interp(x.left) < interp(x.right)\n elif x.node_type == nd_Gtr: return interp(x.left) > interp(x.right)\n elif x.node_type == nd_Leq: return interp(x.left) <= interp(x.right)\n elif x.node_type == nd_Geq: return interp(x.left) >= interp(x.right)\n elif x.node_type == nd_Eql: return interp(x.left) == interp(x.right)\n elif x.node_type == nd_Neq: return interp(x.left) != interp(x.right)\n elif x.node_type == nd_And: return interp(x.left) and interp(x.right)\n elif x.node_type == nd_Or: return interp(x.left) or interp(x.right)\n elif x.node_type == nd_Negate: return -interp(x.left)\n elif x.node_type == nd_Not: return not interp(x.left)\n\n elif x.node_type == nd_If:\n if (interp(x.left)):\n interp(x.right.left)\n else:\n interp(x.right.right)\n return None\n\n elif x.node_type == nd_While:\n while (interp(x.left)):\n interp(x.right)\n return None\n\n elif x.node_type == nd_Prtc:\n print(\"%c\" % (interp(x.left)), end='')\n return None\n\n elif x.node_type == nd_Prti:\n print(\"%d\" % (interp(x.left)), end='')\n return None\n\n elif x.node_type == nd_Prts:\n print(interp(x.left), end='')\n return None\n\n elif x.node_type == nd_Sequence:\n interp(x.left)\n interp(x.right)\n return None\n else:\n error(\"error in code generator - found %d, expecting operator\" % (x.node_type))\n\ndef str_trans(srce):\n dest = \"\"\n i = 0\n srce = srce[1:-1]\n while i < len(srce):\n if srce[i] == '\\\\' and i + 1 < len(srce):\n if srce[i + 1] == 'n':\n dest += '\\n'\n i += 2\n elif srce[i + 1] == '\\\\':\n dest += '\\\\'\n i += 2\n else:\n dest += srce[i]\n i += 1\n\n return dest\n\ndef load_ast():\n line = input_file.readline()\n line_list = shlex.split(line, False, False)\n\n text = line_list[0]\n\n value = None\n if len(line_list) > 1:\n value = line_list[1]\n if value.isdigit():\n value = int(value)\n\n if text == \";\":\n return None\n node_type = all_syms[text]\n if value != None:\n if node_type == nd_String:\n value = str_trans(value)\n\n return make_leaf(node_type, value)\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(0, 0, \"Can't open %s\" % sys.argv[1])\n\nn = load_ast()\ninterp(n)"} {"title": "Compiler/code generator", "language": "Python", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "from __future__ import print_function\nimport sys, struct, shlex, operator\n\nnd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \\\nnd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \\\nnd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)\n\nall_syms = {\n \"Identifier\" : nd_Ident, \"String\" : nd_String,\n \"Integer\" : nd_Integer, \"Sequence\" : nd_Sequence,\n \"If\" : nd_If, \"Prtc\" : nd_Prtc,\n \"Prts\" : nd_Prts, \"Prti\" : nd_Prti,\n \"While\" : nd_While, \"Assign\" : nd_Assign,\n \"Negate\" : nd_Negate, \"Not\" : nd_Not,\n \"Multiply\" : nd_Mul, \"Divide\" : nd_Div,\n \"Mod\" : nd_Mod, \"Add\" : nd_Add,\n \"Subtract\" : nd_Sub, \"Less\" : nd_Lss,\n \"LessEqual\" : nd_Leq, \"Greater\" : nd_Gtr,\n \"GreaterEqual\": nd_Geq, \"Equal\" : nd_Eql,\n \"NotEqual\" : nd_Neq, \"And\" : nd_And,\n \"Or\" : nd_Or}\n\nFETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, \\\nJMP, JZ, PRTC, PRTS, PRTI, HALT = range(24)\n\noperators = {nd_Lss: LT, nd_Gtr: GT, nd_Leq: LE, nd_Geq: GE, nd_Eql: EQ, nd_Neq: NE,\n nd_And: AND, nd_Or: OR, nd_Sub: SUB, nd_Add: ADD, nd_Div: DIV, nd_Mul: MUL, nd_Mod: MOD}\n\nunary_operators = {nd_Negate: NEG, nd_Not: NOT}\n\ninput_file = None\ncode = bytearray()\nstring_pool = {}\nglobals = {}\nstring_n = 0\nglobals_n = 0\nword_size = 4\n\n#*** show error and exit\ndef error(msg):\n print(\"%s\" % (msg))\n exit(1)\n\ndef int_to_bytes(val):\n return struct.pack(\" 1:\n value = line_list[1]\n if value.isdigit():\n value = int(value)\n return make_leaf(node_type, value)\n\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(\"Can't open %s\" % sys.argv[1])\n\nn = load_ast()\ncode_gen(n)\ncode_finish()\nlist_code()"} {"title": "Compiler/lexical analyzer", "language": "Python", "task": "The C and Python versions can be considered reference implementations.\n\n\n;Related Tasks\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n", "solution": "from __future__ import print_function\nimport sys\n\n# following two must remain in the same order\n\ntk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \\\ntk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, \\\ntk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, \\\ntk_Integer, tk_String = range(31)\n\nall_syms = [\"End_of_input\", \"Op_multiply\", \"Op_divide\", \"Op_mod\", \"Op_add\", \"Op_subtract\",\n \"Op_negate\", \"Op_not\", \"Op_less\", \"Op_lessequal\", \"Op_greater\", \"Op_greaterequal\",\n \"Op_equal\", \"Op_notequal\", \"Op_assign\", \"Op_and\", \"Op_or\", \"Keyword_if\",\n \"Keyword_else\", \"Keyword_while\", \"Keyword_print\", \"Keyword_putc\", \"LeftParen\",\n \"RightParen\", \"LeftBrace\", \"RightBrace\", \"Semicolon\", \"Comma\", \"Identifier\",\n \"Integer\", \"String\"]\n\n# single character only symbols\nsymbols = { '{': tk_Lbrace, '}': tk_Rbrace, '(': tk_Lparen, ')': tk_Rparen, '+': tk_Add, '-': tk_Sub,\n '*': tk_Mul, '%': tk_Mod, ';': tk_Semi, ',': tk_Comma }\n\nkey_words = {'if': tk_If, 'else': tk_Else, 'print': tk_Print, 'putc': tk_Putc, 'while': tk_While}\n\nthe_ch = \" \" # dummy first char - but it must be a space\nthe_col = 0\nthe_line = 1\ninput_file = None\n\n#*** show error and exit\ndef error(line, col, msg):\n print(line, col, msg)\n exit(1)\n\n#*** get the next character from the input\ndef next_ch():\n global the_ch, the_col, the_line\n\n the_ch = input_file.read(1)\n the_col += 1\n if the_ch == '\\n':\n the_line += 1\n the_col = 0\n return the_ch\n\n#*** 'x' - character constants\ndef char_lit(err_line, err_col):\n n = ord(next_ch()) # skip opening quote\n if the_ch == '\\'':\n error(err_line, err_col, \"empty character constant\")\n elif the_ch == '\\\\':\n next_ch()\n if the_ch == 'n':\n n = 10\n elif the_ch == '\\\\':\n n = ord('\\\\')\n else:\n error(err_line, err_col, \"unknown escape sequence \\\\%c\" % (the_ch))\n if next_ch() != '\\'':\n error(err_line, err_col, \"multi-character constant\")\n next_ch()\n return tk_Integer, err_line, err_col, n\n\n#*** process divide or comments\ndef div_or_cmt(err_line, err_col):\n if next_ch() != '*':\n return tk_Div, err_line, err_col\n\n # comment found\n next_ch()\n while True:\n if the_ch == '*':\n if next_ch() == '/':\n next_ch()\n return gettok()\n elif len(the_ch) == 0:\n error(err_line, err_col, \"EOF in comment\")\n else:\n next_ch()\n\n#*** \"string\"\ndef string_lit(start, err_line, err_col):\n global the_ch\n text = \"\"\n\n while next_ch() != start:\n if len(the_ch) == 0:\n error(err_line, err_col, \"EOF while scanning string literal\")\n if the_ch == '\\n':\n error(err_line, err_col, \"EOL while scanning string literal\")\n if the_ch == '\\\\':\n next_ch()\n if the_ch != 'n':\n error(err_line, err_col, \"escape sequence unknown \\\\%c\" % the_ch)\n the_ch = '\\n'\n text += the_ch\n\n next_ch()\n return tk_String, err_line, err_col, text\n\n#*** handle identifiers and integers\ndef ident_or_int(err_line, err_col):\n is_number = True\n text = \"\"\n\n while the_ch.isalnum() or the_ch == '_':\n text += the_ch\n if not the_ch.isdigit():\n is_number = False\n next_ch()\n\n if len(text) == 0:\n error(err_line, err_col, \"ident_or_int: unrecognized character: (%d) '%c'\" % (ord(the_ch), the_ch))\n\n if text[0].isdigit():\n if not is_number:\n error(err_line, err_col, \"invalid number: %s\" % (text))\n n = int(text)\n return tk_Integer, err_line, err_col, n\n\n if text in key_words:\n return key_words[text], err_line, err_col\n\n return tk_Ident, err_line, err_col, text\n\n#*** look ahead for '>=', etc.\ndef follow(expect, ifyes, ifno, err_line, err_col):\n if next_ch() == expect:\n next_ch()\n return ifyes, err_line, err_col\n\n if ifno == tk_EOI:\n error(err_line, err_col, \"follow: unrecognized character: (%d) '%c'\" % (ord(the_ch), the_ch))\n\n return ifno, err_line, err_col\n\n#*** return the next token type\ndef gettok():\n while the_ch.isspace():\n next_ch()\n\n err_line = the_line\n err_col = the_col\n\n if len(the_ch) == 0: return tk_EOI, err_line, err_col\n elif the_ch == '/': return div_or_cmt(err_line, err_col)\n elif the_ch == '\\'': return char_lit(err_line, err_col)\n elif the_ch == '<': return follow('=', tk_Leq, tk_Lss, err_line, err_col)\n elif the_ch == '>': return follow('=', tk_Geq, tk_Gtr, err_line, err_col)\n elif the_ch == '=': return follow('=', tk_Eq, tk_Assign, err_line, err_col)\n elif the_ch == '!': return follow('=', tk_Neq, tk_Not, err_line, err_col)\n elif the_ch == '&': return follow('&', tk_And, tk_EOI, err_line, err_col)\n elif the_ch == '|': return follow('|', tk_Or, tk_EOI, err_line, err_col)\n elif the_ch == '\"': return string_lit(the_ch, err_line, err_col)\n elif the_ch in symbols:\n sym = symbols[the_ch]\n next_ch()\n return sym, err_line, err_col\n else: return ident_or_int(err_line, err_col)\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(0, 0, \"Can't open %s\" % sys.argv[1])\n\nwhile True:\n t = gettok()\n tok = t[0]\n line = t[1]\n col = t[2]\n\n print(\"%5d %5d %-14s\" % (line, col, all_syms[tok]), end='')\n\n if tok == tk_Integer: print(\" %5d\" % (t[3]))\n elif tok == tk_Ident: print(\" %s\" % (t[3]))\n elif tok == tk_String: print(' \"%s\"' % (t[3]))\n else: print(\"\")\n\n if tok == tk_EOI:\n break"} {"title": "Compiler/syntax analyzer", "language": "Python", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "from __future__ import print_function\nimport sys, shlex, operator\n\ntk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \\\ntk_Geq, tk_Eql, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, \\\ntk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, \\\ntk_Integer, tk_String = range(31)\n\nnd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While, \\\nnd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq, \\\nnd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or = range(25)\n\n# must have same order as above\nTokens = [\n [\"EOI\" , False, False, False, -1, -1 ],\n [\"*\" , False, True, False, 13, nd_Mul ],\n [\"/\" , False, True, False, 13, nd_Div ],\n [\"%\" , False, True, False, 13, nd_Mod ],\n [\"+\" , False, True, False, 12, nd_Add ],\n [\"-\" , False, True, False, 12, nd_Sub ],\n [\"-\" , False, False, True, 14, nd_Negate ],\n [\"!\" , False, False, True, 14, nd_Not ],\n [\"<\" , False, True, False, 10, nd_Lss ],\n [\"<=\" , False, True, False, 10, nd_Leq ],\n [\">\" , False, True, False, 10, nd_Gtr ],\n [\">=\" , False, True, False, 10, nd_Geq ],\n [\"==\" , False, True, False, 9, nd_Eql ],\n [\"!=\" , False, True, False, 9, nd_Neq ],\n [\"=\" , False, False, False, -1, nd_Assign ],\n [\"&&\" , False, True, False, 5, nd_And ],\n [\"||\" , False, True, False, 4, nd_Or ],\n [\"if\" , False, False, False, -1, nd_If ],\n [\"else\" , False, False, False, -1, -1 ],\n [\"while\" , False, False, False, -1, nd_While ],\n [\"print\" , False, False, False, -1, -1 ],\n [\"putc\" , False, False, False, -1, -1 ],\n [\"(\" , False, False, False, -1, -1 ],\n [\")\" , False, False, False, -1, -1 ],\n [\"{\" , False, False, False, -1, -1 ],\n [\"}\" , False, False, False, -1, -1 ],\n [\";\" , False, False, False, -1, -1 ],\n [\",\" , False, False, False, -1, -1 ],\n [\"Ident\" , False, False, False, -1, nd_Ident ],\n [\"Integer literal\" , False, False, False, -1, nd_Integer],\n [\"String literal\" , False, False, False, -1, nd_String ]\n ]\n\nall_syms = {\"End_of_input\" : tk_EOI, \"Op_multiply\" : tk_Mul,\n \"Op_divide\" : tk_Div, \"Op_mod\" : tk_Mod,\n \"Op_add\" : tk_Add, \"Op_subtract\" : tk_Sub,\n \"Op_negate\" : tk_Negate, \"Op_not\" : tk_Not,\n \"Op_less\" : tk_Lss, \"Op_lessequal\" : tk_Leq,\n \"Op_greater\" : tk_Gtr, \"Op_greaterequal\": tk_Geq,\n \"Op_equal\" : tk_Eql, \"Op_notequal\" : tk_Neq,\n \"Op_assign\" : tk_Assign, \"Op_and\" : tk_And,\n \"Op_or\" : tk_Or, \"Keyword_if\" : tk_If,\n \"Keyword_else\" : tk_Else, \"Keyword_while\" : tk_While,\n \"Keyword_print\" : tk_Print, \"Keyword_putc\" : tk_Putc,\n \"LeftParen\" : tk_Lparen, \"RightParen\" : tk_Rparen,\n \"LeftBrace\" : tk_Lbrace, \"RightBrace\" : tk_Rbrace,\n \"Semicolon\" : tk_Semi, \"Comma\" : tk_Comma,\n \"Identifier\" : tk_Ident, \"Integer\" : tk_Integer,\n \"String\" : tk_String}\n\nDisplay_nodes = [\"Identifier\", \"String\", \"Integer\", \"Sequence\", \"If\", \"Prtc\", \"Prts\",\n \"Prti\", \"While\", \"Assign\", \"Negate\", \"Not\", \"Multiply\", \"Divide\", \"Mod\", \"Add\",\n \"Subtract\", \"Less\", \"LessEqual\", \"Greater\", \"GreaterEqual\", \"Equal\", \"NotEqual\",\n \"And\", \"Or\"]\n\nTK_NAME = 0\nTK_RIGHT_ASSOC = 1\nTK_IS_BINARY = 2\nTK_IS_UNARY = 3\nTK_PRECEDENCE = 4\nTK_NODE = 5\n\ninput_file = None\nerr_line = None\nerr_col = None\ntok = None\ntok_text = None\n\n#*** show error and exit\ndef error(msg):\n print(\"(%d, %d) %s\" % (int(err_line), int(err_col), msg))\n exit(1)\n\n#***\ndef gettok():\n global err_line, err_col, tok, tok_text, tok_other\n line = input_file.readline()\n if len(line) == 0:\n error(\"empty line\")\n\n line_list = shlex.split(line, False, False)\n # line col Ident var_name\n # 0 1 2 3\n\n err_line = line_list[0]\n err_col = line_list[1]\n tok_text = line_list[2]\n\n tok = all_syms.get(tok_text)\n if tok == None:\n error(\"Unknown token %s\" % (tok_text))\n\n tok_other = None\n if tok in [tk_Integer, tk_Ident, tk_String]:\n tok_other = line_list[3]\n\nclass Node:\n def __init__(self, node_type, left = None, right = None, value = None):\n self.node_type = node_type\n self.left = left\n self.right = right\n self.value = value\n\n#***\ndef make_node(oper, left, right = None):\n return Node(oper, left, right)\n\n#***\ndef make_leaf(oper, n):\n return Node(oper, value = n)\n\n#***\ndef expect(msg, s):\n if tok == s:\n gettok()\n return\n error(\"%s: Expecting '%s', found '%s'\" % (msg, Tokens[s][TK_NAME], Tokens[tok][TK_NAME]))\n\n#***\ndef expr(p):\n x = None\n\n if tok == tk_Lparen:\n x = paren_expr()\n elif tok in [tk_Sub, tk_Add]:\n op = (tk_Negate if tok == tk_Sub else tk_Add)\n gettok()\n node = expr(Tokens[tk_Negate][TK_PRECEDENCE])\n x = (make_node(nd_Negate, node) if op == tk_Negate else node)\n elif tok == tk_Not:\n gettok()\n x = make_node(nd_Not, expr(Tokens[tk_Not][TK_PRECEDENCE]))\n elif tok == tk_Ident:\n x = make_leaf(nd_Ident, tok_other)\n gettok()\n elif tok == tk_Integer:\n x = make_leaf(nd_Integer, tok_other)\n gettok()\n else:\n error(\"Expecting a primary, found: %s\" % (Tokens[tok][TK_NAME]))\n\n while Tokens[tok][TK_IS_BINARY] and Tokens[tok][TK_PRECEDENCE] >= p:\n op = tok\n gettok()\n q = Tokens[op][TK_PRECEDENCE]\n if not Tokens[op][TK_RIGHT_ASSOC]:\n q += 1\n\n node = expr(q)\n x = make_node(Tokens[op][TK_NODE], x, node)\n\n return x\n\n#***\ndef paren_expr():\n expect(\"paren_expr\", tk_Lparen)\n node = expr(0)\n expect(\"paren_expr\", tk_Rparen)\n return node\n\n#***\ndef stmt():\n t = None\n\n if tok == tk_If:\n gettok()\n e = paren_expr()\n s = stmt()\n s2 = None\n if tok == tk_Else:\n gettok()\n s2 = stmt()\n t = make_node(nd_If, e, make_node(nd_If, s, s2))\n elif tok == tk_Putc:\n gettok()\n e = paren_expr()\n t = make_node(nd_Prtc, e)\n expect(\"Putc\", tk_Semi)\n elif tok == tk_Print:\n gettok()\n expect(\"Print\", tk_Lparen)\n while True:\n if tok == tk_String:\n e = make_node(nd_Prts, make_leaf(nd_String, tok_other))\n gettok()\n else:\n e = make_node(nd_Prti, expr(0))\n\n t = make_node(nd_Sequence, t, e)\n if tok != tk_Comma:\n break\n gettok()\n expect(\"Print\", tk_Rparen)\n expect(\"Print\", tk_Semi)\n elif tok == tk_Semi:\n gettok()\n elif tok == tk_Ident:\n v = make_leaf(nd_Ident, tok_other)\n gettok()\n expect(\"assign\", tk_Assign)\n e = expr(0)\n t = make_node(nd_Assign, v, e)\n expect(\"assign\", tk_Semi)\n elif tok == tk_While:\n gettok()\n e = paren_expr()\n s = stmt()\n t = make_node(nd_While, e, s)\n elif tok == tk_Lbrace:\n gettok()\n while tok != tk_Rbrace and tok != tk_EOI:\n t = make_node(nd_Sequence, t, stmt())\n expect(\"Lbrace\", tk_Rbrace)\n elif tok == tk_EOI:\n pass\n else:\n error(\"Expecting start of statement, found: %s\" % (Tokens[tok][TK_NAME]))\n\n return t\n\n#***\ndef parse():\n t = None\n gettok()\n while True:\n t = make_node(nd_Sequence, t, stmt())\n if tok == tk_EOI or t == None:\n break\n return t\n\ndef prt_ast(t):\n if t == None:\n print(\";\")\n else:\n print(\"%-14s\" % (Display_nodes[t.node_type]), end='')\n if t.node_type in [nd_Ident, nd_Integer]:\n print(\"%s\" % (t.value))\n elif t.node_type == nd_String:\n print(\"%s\" %(t.value))\n else:\n print(\"\")\n prt_ast(t.left)\n prt_ast(t.right)\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(0, 0, \"Can't open %s\" % sys.argv[1])\nt = parse()\nprt_ast(t)"} {"title": "Compiler/virtual machine interpreter", "language": "Python", "task": "The C and Python versions can be considered reference implementations.\n\n;Related Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Code Generator task\n* AST Interpreter task\n\n\n__TOC__\n\n", "solution": "from __future__ import print_function\nimport sys, struct\n\nFETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, \\\nJMP, JZ, PRTC, PRTS, PRTI, HALT = range(24)\n\ncode_map = {\n \"fetch\": FETCH,\n \"store\": STORE,\n \"push\": PUSH,\n \"add\": ADD,\n \"sub\": SUB,\n \"mul\": MUL,\n \"div\": DIV,\n \"mod\": MOD,\n \"lt\": LT,\n \"gt\": GT,\n \"le\": LE,\n \"ge\": GE,\n \"eq\": EQ,\n \"ne\": NE,\n \"and\": AND,\n \"or\": OR,\n \"not\": NOT,\n \"neg\": NEG,\n \"jmp\": JMP,\n \"jz\": JZ,\n \"prtc\": PRTC,\n \"prts\": PRTS,\n \"prti\": PRTI,\n \"halt\": HALT\n}\n\ninput_file = None\ncode = bytearray()\nstring_pool = []\nword_size = 4\n\n#*** show error and exit\ndef error(msg):\n print(\"%s\" % (msg))\n exit(1)\n\ndef int_to_bytes(val):\n return struct.pack(\" stack[-1]; stack.pop()\n elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()\n elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()\n elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()\n elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()\n elif op == NEG: stack[-1] = -stack[-1]\n elif op == NOT: stack[-1] = not stack[-1]\n elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == JZ:\n if stack.pop():\n pc += word_size\n else:\n pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == PRTC: print(\"%c\" % (stack[-1]), end=''); stack.pop()\n elif op == PRTS: print(\"%s\" % (string_pool[stack[-1]]), end=''); stack.pop()\n elif op == PRTI: print(\"%d\" % (stack[-1]), end=''); stack.pop()\n elif op == HALT: break\n\ndef str_trans(srce):\n dest = \"\"\n i = 0\n while i < len(srce):\n if srce[i] == '\\\\' and i + 1 < len(srce):\n if srce[i + 1] == 'n':\n dest += '\\n'\n i += 2\n elif srce[i + 1] == '\\\\':\n dest += '\\\\'\n i += 2\n else:\n dest += srce[i]\n i += 1\n\n return dest\n\n#***\ndef load_code():\n global string_pool\n\n line = input_file.readline()\n if len(line) == 0:\n error(\"empty line\")\n\n line_list = line.split()\n data_size = int(line_list[1])\n n_strings = int(line_list[3])\n\n for i in range(n_strings):\n string_pool.append(str_trans(input_file.readline().strip('\"\\n')))\n\n while True:\n line = input_file.readline()\n if len(line) == 0:\n break\n line_list = line.split()\n offset = int(line_list[0])\n instr = line_list[1]\n opcode = code_map.get(instr)\n if opcode == None:\n error(\"Unknown instruction %s at %d\" % (instr, offset))\n emit_byte(opcode)\n if opcode in [JMP, JZ]:\n p = int(line_list[3])\n emit_word(p - (offset + 1))\n elif opcode == PUSH:\n value = int(line_list[2])\n emit_word(value)\n elif opcode in [FETCH, STORE]:\n value = int(line_list[2].strip('[]'))\n emit_word(value)\n\n return data_size\n\n#*** main driver\ninput_file = sys.stdin\nif len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], \"r\", 4096)\n except IOError as e:\n error(0, 0, \"Can't open %s\" % sys.argv[1])\n\ndata_size = load_code()\nrun_vm(data_size)"} {"title": "Composite numbers k with no single digit factors whose factors are all substrings of k", "language": "Python", "task": "Find the composite numbers '''k''' in base 10, that have no single digit prime factors and whose prime factors are all a substring of '''k'''.\n\n\n;Task\n\n* Find and show here, on this page, the first ten elements of the sequence.\n\n\n\n;Stretch\n\n* Find and show the next ten elements.\n\n\n\n\n", "solution": "from sympy import isprime, factorint\n\ndef contains_its_prime_factors_all_over_7(n):\n if n < 10 or isprime(n):\n return False\n strn = str(n)\n pfacs = factorint(n).keys()\n return all(f > 9 and str(f) in strn for f in pfacs)\n\nfound = 0\nfor n in range(1_000_000_000):\n if contains_its_prime_factors_all_over_7(n):\n found += 1\n print(f'{n: 12,}', end = '\\n' if found % 10 == 0 else '')\n if found == 20:\n break\n"} {"title": "Conjugate transpose", "language": "Python", "task": "Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.\n\n::: (M^H)_{ji} = \\overline{M_{ij}}\n\n\nThis means that row j, column i of the conjugate transpose equals the \ncomplex conjugate of row i, column j of the original matrix.\n\n\nIn the next list, M must also be a square matrix.\n\n* A Hermitian matrix equals its own conjugate transpose: M^H = M.\n* A multiplication with its conjugate transpose: M^HM = MM^H.\n* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.\n\n\n\n;Task:\nGiven some matrix of complex numbers, find its conjugate transpose. \n\nAlso determine if the matrix is a:\n::* Hermitian matrix,\n::* normal matrix, or \n::* unitary matrix.\n\n\n;See also:\n* MathWorld entry: conjugate transpose\n* MathWorld entry: Hermitian matrix\n* MathWorld entry: normal matrix\n* MathWorld entry: unitary matrix\n\n", "solution": "def conjugate_transpose(m):\n return tuple(tuple(n.conjugate() for n in row) for row in zip(*m))\n\ndef mmul( ma, mb):\n return tuple(tuple(sum( ea*eb for ea,eb in zip(a,b)) for b in zip(*mb)) for a in ma)\n\ndef mi(size):\n 'Complex Identity matrix'\n sz = range(size)\n m = [[0 + 0j for i in sz] for j in sz]\n for i in range(size):\n m[i][i] = 1 + 0j\n return tuple(tuple(row) for row in m)\n\ndef __allsame(vector):\n first, rest = vector[0], vector[1:]\n return all(i == first for i in rest)\n\ndef __allnearsame(vector, eps=1e-14):\n first, rest = vector[0], vector[1:]\n return all(abs(first.real - i.real) < eps and abs(first.imag - i.imag) < eps\n for i in rest)\n\ndef isequal(matrices, eps=1e-14):\n 'Check any number of matrices for equality within eps'\n x = [len(m) for m in matrices]\n if not __allsame(x): return False\n y = [len(m[0]) for m in matrices]\n if not __allsame(y): return False\n for s in range(x[0]):\n for t in range(y[0]):\n if not __allnearsame([m[s][t] for m in matrices], eps): return False\n return True\n \n\ndef ishermitian(m, ct):\n return isequal([m, ct])\n\ndef isnormal(m, ct):\n return isequal([mmul(m, ct), mmul(ct, m)])\n\ndef isunitary(m, ct):\n mct, ctm = mmul(m, ct), mmul(ct, m)\n mctx, mcty, cmx, ctmy = len(mct), len(mct[0]), len(ctm), len(ctm[0])\n ident = mi(mctx)\n return isequal([mct, ctm, ident])\n\ndef printm(comment, m):\n print(comment)\n fields = [['%g%+gj' % (f.real, f.imag) for f in row] for row in m]\n width = max(max(len(f) for f in row) for row in fields)\n lines = (', '.join('%*s' % (width, f) for f in row) for row in fields)\n print('\\n'.join(lines))\n\nif __name__ == '__main__':\n for matrix in [\n ((( 3.000+0.000j), (+2.000+1.000j)), \n (( 2.000-1.000j), (+1.000+0.000j))),\n\n ((( 1.000+0.000j), (+1.000+0.000j), (+0.000+0.000j)), \n (( 0.000+0.000j), (+1.000+0.000j), (+1.000+0.000j)), \n (( 1.000+0.000j), (+0.000+0.000j), (+1.000+0.000j))),\n\n ((( 2**0.5/2+0.000j), (+2**0.5/2+0.000j), (+0.000+0.000j)), \n (( 0.000+2**0.5/2j), (+0.000-2**0.5/2j), (+0.000+0.000j)), \n (( 0.000+0.000j), (+0.000+0.000j), (+0.000+1.000j)))]:\n printm('\\nMatrix:', matrix)\n ct = conjugate_transpose(matrix)\n printm('Its conjugate transpose:', ct)\n print('Hermitian? %s.' % ishermitian(matrix, ct))\n print('Normal? %s.' % isnormal(matrix, ct))\n print('Unitary? %s.' % isunitary(matrix, ct))"} {"title": "Continued fraction", "language": "Python 2.6+ and 3.x", "task": "A number may be represented as a continued fraction (see Mathworld for more information) as follows:\n:a_0 + \\cfrac{b_1}{a_1 + \\cfrac{b_2}{a_2 + \\cfrac{b_3}{a_3 + \\ddots}}}\n\nThe task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:\n\nFor the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.\n\n:\\sqrt{2} = 1 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\ddots}}}\n\nFor Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.\n\n:e = 2 + \\cfrac{1}{1 + \\cfrac{1}{2 + \\cfrac{2}{3 + \\cfrac{3}{4 + \\ddots}}}}\n\nFor Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.\n\n:\\pi = 3 + \\cfrac{1}{6 + \\cfrac{9}{6 + \\cfrac{25}{6 + \\ddots}}}\n\n\n;See also:\n:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n\n", "solution": "from fractions import Fraction\nimport itertools\ntry: zip = itertools.izip\nexcept: pass\n \n# The Continued Fraction\ndef CF(a, b, t):\n terms = list(itertools.islice(zip(a, b), t))\n z = Fraction(1,1)\n for a, b in reversed(terms):\n z = a + b / z\n return z\n \n# Approximates a fraction to a string\ndef pRes(x, d):\n q, x = divmod(x, 1)\n res = str(q)\n res += \".\"\n for i in range(d):\n x *= 10\n q, x = divmod(x, 1)\n res += str(q)\n return res\n \n# Test the Continued Fraction for sqrt2\ndef sqrt2_a():\n yield 1\n for x in itertools.repeat(2):\n yield x\n \ndef sqrt2_b():\n for x in itertools.repeat(1):\n yield x\n \ncf = CF(sqrt2_a(), sqrt2_b(), 950)\nprint(pRes(cf, 200))\n#1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147\n \n \n# Test the Continued Fraction for Napier's Constant\ndef Napier_a():\n yield 2\n for x in itertools.count(1):\n yield x\n \ndef Napier_b():\n yield 1\n for x in itertools.count(1):\n yield x\n \ncf = CF(Napier_a(), Napier_b(), 950)\nprint(pRes(cf, 200))\n#2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794349076323382988075319525101901\n \n# Test the Continued Fraction for Pi\ndef Pi_a():\n yield 3\n for x in itertools.repeat(6):\n yield x\n \ndef Pi_b():\n for x in itertools.count(1,2):\n yield x*x\n \ncf = CF(Pi_a(), Pi_b(), 950)\nprint(pRes(cf, 10))\n#3.1415926532"} {"title": "Continued fraction", "language": "Python from D", "task": "A number may be represented as a continued fraction (see Mathworld for more information) as follows:\n:a_0 + \\cfrac{b_1}{a_1 + \\cfrac{b_2}{a_2 + \\cfrac{b_3}{a_3 + \\ddots}}}\n\nThe task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:\n\nFor the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.\n\n:\\sqrt{2} = 1 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\ddots}}}\n\nFor Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.\n\n:e = 2 + \\cfrac{1}{1 + \\cfrac{1}{2 + \\cfrac{2}{3 + \\cfrac{3}{4 + \\ddots}}}}\n\nFor Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.\n\n:\\pi = 3 + \\cfrac{1}{6 + \\cfrac{9}{6 + \\cfrac{25}{6 + \\ddots}}}\n\n\n;See also:\n:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n\n", "solution": "from decimal import Decimal, getcontext\n\ndef calc(fun, n):\n temp = Decimal(\"0.0\")\n\n for ni in xrange(n+1, 0, -1):\n (a, b) = fun(ni)\n temp = Decimal(b) / (a + temp)\n\n return fun(0)[0] + temp\n\ndef fsqrt2(n):\n return (2 if n > 0 else 1, 1)\n\ndef fnapier(n):\n return (n if n > 0 else 2, (n - 1) if n > 1 else 1)\n\ndef fpi(n):\n return (6 if n > 0 else 3, (2 * n - 1) ** 2)\n\ngetcontext().prec = 50\nprint calc(fsqrt2, 200)\nprint calc(fnapier, 200)\nprint calc(fpi, 200)"} {"title": "Continued fraction/Arithmetic/Construct from rational number", "language": "Python from Ruby", "task": "To understand this task in context please see [[Continued fraction arithmetic]]\nThe purpose of this task is to write a function \\mathit{r2cf}(\\mathrm{int} N_1, \\mathrm{int} N_2), or \\mathit{r2cf}(\\mathrm{Fraction} N), which will output a continued fraction assuming:\n:N_1 is the numerator\n:N_2 is the denominator\n \nThe function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.\n\nTo achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \\mathrm{abs}(N_2) is zero.\n\nDemonstrate the function by outputing the continued fraction for:\n: 1/2\n: 3\n: 23/8\n: 13/11\n: 22/7\n: -151/77\n\\sqrt 2 should approach [1; 2, 2, 2, 2, \\ldots] try ever closer rational approximations until boredom gets the better of you:\n: 14142,10000\n: 141421,100000\n: 1414214,1000000\n: 14142136,10000000\n\nTry :\n: 31,10\n: 314,100\n: 3142,1000\n: 31428,10000\n: 314285,100000\n: 3142857,1000000\n: 31428571,10000000\n: 314285714,100000000\n\nObserve how this rational number behaves differently to \\sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\\infty] when an extra term is required.\n\n", "solution": "def r2cf(n1,n2):\n while n2:\n n1, (t1, n2) = n2, divmod(n1, n2)\n yield t1\n\nprint(list(r2cf(1,2))) # => [0, 2]\nprint(list(r2cf(3,1))) # => [3]\nprint(list(r2cf(23,8))) # => [2, 1, 7]\nprint(list(r2cf(13,11))) # => [1, 5, 2]\nprint(list(r2cf(22,7))) # => [3, 7]\nprint(list(r2cf(14142,10000))) # => [1, 2, 2, 2, 2, 2, 1, 1, 29]\nprint(list(r2cf(141421,100000))) # => [1, 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2]\nprint(list(r2cf(1414214,1000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 3, 6, 1, 2, 1, 12]\nprint(list(r2cf(14142136,10000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2]"} {"title": "Continued fraction/Arithmetic/G(matrix ng, continued fraction n)", "language": "Python from Ruby", "task": "This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:\n: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix}\nI may perform perform the following operations:\n:Input the next term of N1\n:Output a term of the continued fraction resulting from the operation.\n\nI output a term if the integer parts of \\frac{a}{b} and \\frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \\infty.\n\nWhen I input a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a + a_1 * t & a_1 \\\\\n b + b_1 * t & b_1 \n\\end{bmatrix}\n\nWhen I output a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} b_1 & b \\\\\n a_1 - b_1 * t & a - b * t \n\\end{bmatrix}\n\nWhen I need a term t but there are no more my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a_1 & a_1 \\\\\n b_1 & b_1 \n\\end{bmatrix}\n\nI am done when b1 and b are zero.\n\nDemonstrate your solution by calculating:\n:[1;5,2] + 1/2\n:[3;7] + 1/2 \n:[3;7] divided by 4\nUsing a generator for \\sqrt{2} (e.g., from [[Continued fraction]]) calculate \\frac{1}{\\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons.\n\nThe first step in implementing [[Arithmetic-geometric mean]] is to calculate \\frac{1 + \\frac{1}{\\sqrt{2}}}{2} do this now to cross the starting line and begin the race.\n\n", "solution": "class NG:\n def __init__(self, a1, a, b1, b):\n self.a1, self.a, self.b1, self.b = a1, a, b1, b\n\n def ingress(self, n):\n self.a, self.a1 = self.a1, self.a + self.a1 * n\n self.b, self.b1 = self.b1, self.b + self.b1 * n\n\n @property\n def needterm(self):\n return (self.b == 0 or self.b1 == 0) or not self.a//self.b == self.a1//self.b1\n\n @property\n def egress(self):\n n = self.a // self.b\n self.a, self.b = self.b, self.a - self.b * n\n self.a1, self.b1 = self.b1, self.a1 - self.b1 * n\n return n\n\n @property\n def egress_done(self):\n if self.needterm: self.a, self.b = self.a1, self.b1\n return self.egress\n\n @property\n def done(self):\n return self.b == 0 and self.b1 == 0"} {"title": "Convert decimal number to rational", "language": "Python 2.6+", "task": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 - 4527027 / 5000000\n* 0.518518 - 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 - 3 / 4 \n\n", "solution": ">>> from fractions import Fraction\n>>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))\n\n0.9054054 67/74\n0.518518 14/27\n0.75 3/4\n>>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))\n\n0.9054054 4527027/5000000\n0.518518 259259/500000\n0.75 3/4\n>>> "} {"title": "Convert decimal number to rational", "language": "Python 3.7", "task": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 - 4527027 / 5000000\n* 0.518518 - 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 - 3 / 4 \n\n", "solution": "'''Approximate rationals from decimals'''\n\nfrom math import (floor, gcd)\nimport sys\n\n\n# approxRatio :: Float -> Float -> Ratio\ndef approxRatio(epsilon):\n '''The simplest rational approximation to\n n within the margin given by epsilon.\n '''\n def gcde(e, x, y):\n def _gcd(a, b):\n return a if b < e else _gcd(b, a % b)\n return _gcd(abs(x), abs(y))\n return lambda n: (lambda c=(\n gcde(epsilon if 0 < epsilon else (0.0001), 1, n)\n ): ratio(floor(n / c))(floor(1 / c)))()\n\n\n# main :: IO ()\ndef main():\n '''Conversions at different levels of precision.'''\n\n xs = [0.9054054, 0.518518, 0.75]\n print(\n fTable(__doc__ + ' (epsilon of 1/10000):\\n')(str)(\n lambda r: showRatio(r) + ' -> ' + repr(fromRatio(r))\n )(\n approxRatio(1 / 10000)\n )(xs)\n )\n print('\\n')\n\n e = minBound(float)\n print(\n fTable(__doc__ + ' (epsilon of ' + repr(e) + '):\\n')(str)(\n lambda r: showRatio(r) + ' -> ' + repr(fromRatio(r))\n )(\n approxRatio(e)\n )(xs)\n )\n\n\n# GENERIC -------------------------------------------------\n\n# fromRatio :: Ratio Int -> Float\ndef fromRatio(r):\n '''A floating point value derived from a\n a rational value.\n '''\n return r.get('numerator') / r.get('denominator')\n\n\n# minBound :: Bounded Type -> a\ndef minBound(t):\n '''Minimum value for a bounded type.'''\n maxsize = sys.maxsize\n float_infomin = sys.float_info.min\n return {\n int: (-maxsize - 1),\n float: float_infomin,\n bool: False,\n str: chr(0)\n }[t]\n\n\n# ratio :: Int -> Int -> Ratio Int\ndef ratio(n):\n '''Rational value constructed\n from a numerator and a denominator.\n '''\n def go(n, d):\n g = gcd(n, d)\n return {\n 'type': 'Ratio',\n 'numerator': n // g, 'denominator': d // g\n }\n return lambda d: go(n * signum(d), abs(d))\n\n\n# showRatio :: Ratio -> String\ndef showRatio(r):\n '''String representation of the ratio r.'''\n d = r.get('denominator')\n return str(r.get('numerator')) + (\n ' / ' + str(d) if 1 != d else ''\n )\n\n\n# signum :: Num -> Num\ndef signum(n):\n '''The sign of n.'''\n return -1 if 0 > n else (1 if 0 < n else 0)\n\n\n# DISPLAY -------------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Convert seconds to compound duration", "language": "Python", "task": "Write a function or program which:\n* takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* returns a string which shows the same duration decomposed into:\n:::* weeks,\n:::* days, \n:::* hours, \n:::* minutes, and \n:::* seconds.\n\nThis is detailed below (e.g., \"2 hr, 59 sec\").\n\n\nDemonstrate that it passes the following three test-cases:\n\n'''''Test Cases'''''\n\n:::::{| class=\"wikitable\"\n|-\n! input number\n! output string\n|-\n| 7259\n| 2 hr, 59 sec\n|-\n| 86400\n| 1 d\n|-\n| 6000000\n| 9 wk, 6 d, 10 hr, 40 min\n|}\n\n'''''Details'''''\n\nThe following five units should be used:\n:::::{| class=\"wikitable\"\n|-\n! unit\n! suffix used in output\n! conversion\n|-\n| week\n| wk\n| 1 week = 7 days\n|-\n| day\n| d\n| 1 day = 24 hours\n|-\n| hour\n| hr\n| 1 hour = 60 minutes\n|-\n| minute\n| min\n| 1 minute = 60 seconds\n|-\n| second\n| sec\n| \n|}\n\nHowever, '''only''' include quantities with non-zero values in the output (e.g., return \"1 d\" and not \"0 wk, 1 d, 0 hr, 0 min, 0 sec\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n\n\n", "solution": "'''Compound duration'''\n\nfrom functools import reduce\nfrom itertools import chain\n\n\n# compoundDurationFromUnits :: [Num] -> [String] -> Num -> [(Num, String)]\ndef compoundDurationFromUnits(qs):\n '''A list of compound string representions of a number n of time units,\n in terms of the multiples given in qs, and the labels given in ks.\n '''\n return lambda ks: lambda n: list(\n chain.from_iterable(map(\n lambda v, k: [(v, k)] if 0 < v else [],\n mapAccumR(\n lambda a, x: divmod(a, x) if 0 < x else (1, a)\n )(n)(qs)[1],\n ks\n ))\n )\n\n\n# --------------------------TEST---------------------------\n# main :: IO ()\ndef main():\n '''Tests of various durations, with a\n particular set of units and labels.\n '''\n\n print(\n fTable('Compound durations from numbers of seconds:\\n')(str)(\n quoted(\"'\")\n )(\n lambda n: ', '.join([\n str(v) + ' ' + k for v, k in\n compoundDurationFromUnits([0, 7, 24, 60, 60])(\n ['wk', 'd', 'hr', 'min', 'sec']\n )(n)\n ])\n )([7259, 86400, 6000000])\n )\n\n\n# -------------------------GENERIC-------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\ndef mapAccumR(f):\n '''A tuple of an accumulation and a list derived by a combined\n map and fold, with accumulation from right to left.\n '''\n def go(a, x):\n acc, y = f(a[0], x)\n return (acc, [y] + a[1])\n return lambda acc: lambda xs: (\n reduce(go, reversed(xs), (acc, []))\n )\n\n\n# quoted :: Char -> String -> String\ndef quoted(c):\n '''A string flanked on both sides\n by a specified quote character.\n '''\n return lambda s: c + s + c\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Copy stdin to stdout", "language": "Python", "task": "Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.\n\n", "solution": "python -c 'import sys; sys.stdout.write(sys.stdin.read())'\n\n"} {"title": "Count the coins", "language": "Python from Go", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "def changes(amount, coins):\n ways = [0] * (amount + 1)\n ways[0] = 1\n for coin in coins:\n for j in xrange(coin, amount + 1):\n ways[j] += ways[j - coin]\n return ways[amount]\n\nprint changes(100, [1, 5, 10, 25])\nprint changes(100000, [1, 5, 10, 25, 50, 100])"} {"title": "Count the coins", "language": "Python from C", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "try:\n import psyco\n psyco.full()\nexcept ImportError:\n pass\n\ndef count_changes(amount_cents, coins):\n n = len(coins)\n # max([]) instead of max() for Psyco\n cycle = max([c+1 for c in coins if c <= amount_cents]) * n\n table = [0] * cycle\n for i in xrange(n):\n table[i] = 1\n\n pos = n\n for s in xrange(1, amount_cents + 1):\n for i in xrange(n):\n if i == 0 and pos >= cycle:\n pos = 0\n if coins[i] <= s:\n q = pos - coins[i] * n\n table[pos]= table[q] if (q >= 0) else table[q + cycle]\n if i:\n table[pos] += table[pos - 1]\n pos += 1\n return table[pos - 1]\n\ndef main():\n us_coins = [100, 50, 25, 10, 5, 1]\n eu_coins = [200, 100, 50, 20, 10, 5, 2, 1]\n\n for coins in (us_coins, eu_coins):\n print count_changes( 100, coins[2:])\n print count_changes( 100000, coins)\n print count_changes( 1000000, coins)\n print count_changes(10000000, coins), \"\\n\"\n\nmain()"} {"title": "Create an HTML table", "language": "Python", "task": "Create an HTML table. \n* The table body should have at least three rows of three columns.\n* Each of these three columns should be labelled \"X\", \"Y\", and \"Z\". \n* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. \n* The rows of the \"X\", \"Y\", and \"Z\" columns should be filled with random or sequential integers having 4 digits or less. \n* The numbers should be aligned in the same fashion for all columns.\n\n", "solution": "import random\n\ndef rand9999():\n return random.randint(1000, 9999)\n\ndef tag(attr='', **kwargs):\n for tag, txt in kwargs.items():\n return '<{tag}{attr}>{txt}'.format(**locals())\n\nif __name__ == '__main__':\n header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\\n'\n rows = '\\n'.join(tag(tr=tag(' style=\"font-weight: bold;\"', td=i)\n + ''.join(tag(td=rand9999())\n for j in range(3)))\n for i in range(1, 6))\n table = tag(table='\\n' + header + rows + '\\n')\n print(table)"} {"title": "Create an HTML table", "language": "Python 3.6", "task": "Create an HTML table. \n* The table body should have at least three rows of three columns.\n* Each of these three columns should be labelled \"X\", \"Y\", and \"Z\". \n* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. \n* The rows of the \"X\", \"Y\", and \"Z\" columns should be filled with random or sequential integers having 4 digits or less. \n* The numbers should be aligned in the same fashion for all columns.\n\n", "solution": "from functools import (reduce)\nimport itertools\nimport random\n\n\n# HTML RENDERING ----------------------------------------\n\n# treeHTML :: tree\n# {tag :: String, text :: String, kvs :: Dict}\n# -> HTML String\ndef treeHTML(tree):\n return foldTree(\n lambda x: lambda xs: (\n f\"<{x['tag'] + attribString(x)}>\" + (\n str(x['text']) if 'text' in x else '\\n'\n ) + ''.join(xs) + f\"\\n\"\n )\n )(tree)\n\n\n# attribString :: Dict -> String\ndef attribString(dct):\n kvs = dct['kvs'] if 'kvs' in dct else None\n return ' ' + reduce(\n lambda a, k: a + k + '=\"' + kvs[k] + '\" ',\n kvs.keys(), ''\n ).strip() if kvs else ''\n\n\n# HTML TABLE FROM GENERATED DATA ------------------------\n\n\ndef main():\n # Number of columns and rows to generate.\n n = 3\n\n # Table details -------------------------------------\n strCaption = 'Table generated with Python'\n colNames = take(n)(enumFrom('A'))\n dataRows = map(\n lambda x: (x, map(\n lambda _: random.randint(100, 9999),\n colNames\n )), take(n)(enumFrom(1)))\n tableStyle = {\n 'style': \"width:25%; border:2px solid silver;\"\n }\n trStyle = {\n 'style': \"border:1px solid silver;text-align:right;\"\n }\n\n # TREE STRUCTURE OF TABLE ---------------------------\n tableTree = Node({'tag': 'table', 'kvs': tableStyle})([\n Node({\n 'tag': 'caption',\n 'text': strCaption\n })([]),\n\n # HEADER ROW --------------------------------\n (Node({'tag': 'tr'})(\n Node({\n 'tag': 'th',\n 'kvs': {'style': 'text-align:right;'},\n 'text': k\n })([]) for k in ([''] + colNames)\n ))\n ] +\n # DATA ROWS ---------------------------------\n list(Node({'tag': 'tr', 'kvs': trStyle})(\n [Node({'tag': 'th', 'text': tpl[0]})([])] +\n list(Node(\n {'tag': 'td', 'text': str(v)})([]) for v in tpl[1]\n )\n ) for tpl in dataRows)\n )\n\n print(\n treeHTML(tableTree)\n # dataRows\n )\n\n\n# GENERIC -----------------------------------------------\n\n# Node :: a -> [Tree a] -> Tree a\ndef Node(v):\n return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}\n\n\n# enumFrom :: Enum a => a -> [a]\ndef enumFrom(x):\n return itertools.count(x) if type(x) is int else (\n map(chr, itertools.count(ord(x)))\n )\n\n\n# foldTree :: (a -> [b] -> b) -> Tree a -> b\ndef foldTree(f):\n def go(node):\n return f(node['root'])(\n list(map(go, node['nest']))\n )\n return lambda tree: go(tree)\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n return lambda xs: (\n xs[0:n]\n if isinstance(xs, list)\n else list(itertools.islice(xs, n))\n )\n\n\nif __name__ == '__main__':\n main()"} {"title": "Cullen and Woodall numbers", "language": "Python", "task": "A Cullen number is a number of the form '''n x 2n + 1''' where '''n''' is a natural number.\n\nA Woodall number is very similar. It is a number of the form '''n x 2n - 1''' where '''n''' is a natural number.\n\nSo for each '''n''' the associated Cullen number and Woodall number differ by 2.\n\n''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.''\n\n\n'''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime.\n\nIt is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated.\n\n\n;Task\n\n* Write procedures to find Cullen numbers and Woodall numbers. \n\n* Use those procedures to find and show here, on this page the first 20 of each.\n\n\n;Stretch\n\n* Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''.\n\n* Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''.\n\n\n;See also\n\n* OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1\n\n* OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1\n\n* OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime\n\n* OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime\n\n\n", "solution": "print(\"working...\")\nprint(\"First 20 Cullen numbers:\")\n\nfor n in range(1,21):\n num = n*pow(2,n)+1\n print(str(num),end= \" \")\n\nprint()\nprint(\"First 20 Woodall numbers:\")\n\nfor n in range(1,21):\n num = n*pow(2,n)-1\n print(str(num),end=\" \")\n\nprint()\nprint(\"done...\")\n"} {"title": "Cullen and Woodall numbers", "language": "Python from Quackery", "task": "A Cullen number is a number of the form '''n x 2n + 1''' where '''n''' is a natural number.\n\nA Woodall number is very similar. It is a number of the form '''n x 2n - 1''' where '''n''' is a natural number.\n\nSo for each '''n''' the associated Cullen number and Woodall number differ by 2.\n\n''Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.''\n\n\n'''Cullen primes''' are Cullen numbers that are prime. Similarly, '''Woodall primes''' are Woodall numbers that are prime.\n\nIt is common to list the Cullen and Woodall primes by the value of '''n''' rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, '''n''' == 4713, has 1423 digits when evaluated.\n\n\n;Task\n\n* Write procedures to find Cullen numbers and Woodall numbers. \n\n* Use those procedures to find and show here, on this page the first 20 of each.\n\n\n;Stretch\n\n* Find and show the first '''5''' '''Cullen primes''' in terms of '''n'''.\n\n* Find and show the first '''12''' '''Woodall primes''' in terms of '''n'''.\n\n\n;See also\n\n* OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1\n\n* OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1\n\n* OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime\n\n* OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime\n\n\n", "solution": "def cullen(n): return((n< c) -> a -> b -> c\ndef curry(f):\n return lambda a: lambda b: f(a, b)\n\n\n# uncurry :: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n return lambda x, y: f(x)(y)\n\n\n# EXAMPLES --------------------------------------\n\n# A plain uncurried function with 2 arguments,\n\n# justifyLeft :: Int -> String -> String\ndef justifyLeft(n, s):\n return (s + (n * ' '))[:n]\n\n\n# and a similar, but manually curried, function.\n\n# justifyRight :: Int -> String -> String\ndef justifyRight(n):\n return lambda s: (\n ((n * ' ') + s)[-n:]\n )\n\n\n# CURRYING and UNCURRYING at run-time:\n\ndef main():\n for s in [\n 'Manually curried using a lambda:',\n '\\n'.join(map(\n justifyRight(5),\n ['1', '9', '10', '99', '100', '1000']\n )),\n\n '\\nAutomatically uncurried:',\n uncurry(justifyRight)(5, '10000'),\n\n '\\nAutomatically curried',\n '\\n'.join(map(\n curry(justifyLeft)(10),\n ['1', '9', '10', '99', '100', '1000']\n ))\n ]:\n print (s)\n\n\nmain()"} {"title": "Curzon numbers", "language": "Python", "task": "A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by '''2 x n + 1'''.\n\n'''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''kn + 1''' is evenly divisible by '''k x n + 1'''.\n\n''Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.'' \n\nGeneralized Curzon numbers only exist for even base integers. \n\n\n;Task \n\n* Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''.\n\n\n;Stretch\n\n* Find and show the '''one thousandth'''.\n\n\n;See also\n\n;* Numbers Aplenty - Curzon numbers\n;* OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)\n\n''and even though it is not specifically mentioned that they are Curzon numbers:''\n\n;* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)\n\n", "solution": "def is_Curzon(n, k):\n r = k * n\n return pow(k, n, r + 1) == r\n\nfor k in [2, 4, 6, 8, 10]:\n n, curzons = 1, []\n while len(curzons) < 1000:\n if is_Curzon(n, k):\n curzons.append(n)\n n += 1\n print(f'Curzon numbers with k = {k}:')\n for i, c in enumerate(curzons[:50]):\n print(f'{c: 5,}', end='\\n' if (i + 1) % 25 == 0 else '')\n print(f' Thousandth Curzon with k = {k}: {curzons[999]}.\\n')"} {"title": "Cut a rectangle", "language": "Python from D", "task": "A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.\n\n[[file:rect-cut.svg]]\n\nWrite a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts.\n\nPossibly related task: [[Maze generation]] for depth-first search.\n\n", "solution": "try:\n import psyco\nexcept ImportError:\n pass\nelse:\n psyco.full()\n\nw, h = 0, 0\ncount = 0\nvis = []\n\ndef cwalk(y, x, d):\n global vis, count, w, h\n if not y or y == h or not x or x == w:\n count += 1\n return\n\n vis[y][x] = vis[h - y][w - x] = 1\n\n if x and not vis[y][x - 1]:\n cwalk(y, x - 1, d | 1)\n if (d & 1) and x < w and not vis[y][x+1]:\n cwalk(y, x + 1, d|1)\n if y and not vis[y - 1][x]:\n cwalk(y - 1, x, d | 2)\n if (d & 2) and y < h and not vis[y + 1][x]:\n cwalk(y + 1, x, d | 2)\n\n vis[y][x] = vis[h - y][w - x] = 0\n\ndef count_only(x, y):\n global vis, count, w, h\n count = 0\n w = x\n h = y\n\n if (h * w) & 1:\n return count\n if h & 1:\n w, h = h, w\n\n vis = [[0] * (w + 1) for _ in xrange(h + 1)]\n vis[h // 2][w // 2] = 1\n\n if w & 1:\n vis[h // 2][w // 2 + 1] = 1\n\n res = 0\n if w > 1:\n cwalk(h // 2, w // 2 - 1, 1)\n res = 2 * count - 1\n count = 0\n if w != h:\n cwalk(h // 2 + 1, w // 2, 3 if (w & 1) else 2)\n\n res += 2 * count - (not (w & 1))\n else:\n res = 1\n\n if w == h:\n res = 2 * res + 2\n return res\n\ndef main():\n for y in xrange(1, 10):\n for x in xrange(1, y + 1):\n if not (x & 1) or not (y & 1):\n print \"%d x %d: %d\" % (y, x, count_only(x, y))\n\nmain()"} {"title": "Cyclotomic polynomial", "language": "Python", "task": "The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n - 1, and is not a divisor of x^k - 1 for any k < n.\n\n\n;Task:\n* Find and print the first 30 cyclotomic polynomials.\n* Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.\n\n\n;See also\n* Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.\n* The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.\n\n", "solution": "from itertools import count, chain\nfrom collections import deque\n\ndef primes(_cache=[2, 3]):\n yield from _cache\n for n in count(_cache[-1]+2, 2):\n if isprime(n):\n _cache.append(n)\n yield n\n\ndef isprime(n):\n for p in primes():\n if n%p == 0:\n return False\n if p*p > n:\n return True\n\ndef factors(n):\n for p in primes():\n # prime factoring is such a non-issue for small numbers that, for\n # this example, we might even just say\n # for p in count(2):\n if p*p > n:\n if n > 1:\n yield(n, 1, 1)\n break\n\n if n%p == 0:\n cnt = 0\n while True:\n n, cnt = n//p, cnt+1\n if n%p != 0: break\n yield p, cnt, n\n# ^^ not the most sophisticated prime number routines, because no need\n\n# Returns (list1, list2) representing the division between\n# two polinomials. A list p of integers means the product\n# (x^p[0] - 1) * (x^p[1] - 1) * ...\ndef cyclotomic(n):\n def poly_div(num, den):\n return (num[0] + den[1], num[1] + den[0])\n\n def elevate(poly, n): # replace poly p(x) with p(x**n)\n powerup = lambda p, n: [a*n for a in p]\n return poly if n == 1 else (powerup(poly[0], n), powerup(poly[1], n))\n\n\n if n == 0:\n return ([], [])\n if n == 1:\n return ([1], [])\n\n p, m, r = next(factors(n))\n poly = cyclotomic(r)\n return elevate(poly_div(elevate(poly, p), poly), p**(m-1))\n\ndef to_text(poly):\n def getx(c, e):\n if e == 0:\n return '1'\n elif e == 1:\n return 'x'\n return 'x' + (''.join('\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079'[i] for i in map(int, str(e))))\n\n parts = []\n for (c,e) in (poly):\n if c < 0:\n coef = ' - ' if c == -1 else f' - {-c} '\n else:\n coef = (parts and ' + ' or '') if c == 1 else f' + {c}'\n parts.append(coef + getx(c,e))\n return ''.join(parts)\n\ndef terms(poly):\n # convert above representation of division to (coef, power) pairs\n\n def merge(a, b):\n # a, b should be deques. They may change during the course.\n while a or b:\n l = a[0] if a else (0, -1) # sentinel value\n r = b[0] if b else (0, -1)\n if l[1] > r[1]:\n a.popleft()\n elif l[1] < r[1]:\n b.popleft()\n l = r\n else:\n a.popleft()\n b.popleft()\n l = (l[0] + r[0], l[1])\n yield l\n\n def mul(poly, p): # p means polynomial x^p - 1\n poly = list(poly)\n return merge(deque((c, e+p) for c,e in poly),\n deque((-c, e) for c,e in poly))\n\n def div(poly, p): # p means polynomial x^p - 1\n q = deque()\n for c,e in merge(deque(poly), q):\n if c:\n q.append((c, e - p))\n yield (c, e - p)\n if e == p: break\n\n p = [(1, 0)] # 1*x^0, i.e. 1\n\n for x in poly[0]: # numerator\n p = mul(p, x)\n for x in sorted(poly[1], reverse=True): # denominator\n p = div(p, x)\n return p\n\nfor n in chain(range(11), [2]):\n print(f'{n}: {to_text(terms(cyclotomic(n)))}')\n\nwant = 1\nfor n in count():\n c = [c for c,_ in terms(cyclotomic(n))]\n while want in c or -want in c:\n print(f'C[{want}]: {n}')\n want += 1"} {"title": "Damm algorithm", "language": "Python", "task": "The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. \n\n\nThe algorithm is named after H. Michael Damm.\n\n\n;Task:\nVerify the checksum, stored as last digit of an input.\n\n\n\n", "solution": "def damm(num: int) -> bool:\n row = 0\n for digit in str(num):\n row = _matrix[row][int(digit)] \n return row == 0\n\n_matrix = (\n (0, 3, 1, 7, 5, 9, 8, 6, 4, 2),\n (7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n (4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n (1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n (6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n (3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n (5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n (8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n (9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n (2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n)\n\nif __name__ == '__main__':\n for test in [5724, 5727, 112946]:\n print(f'{test}\\t Validates as: {damm(test)}')"} {"title": "De Bruijn sequences", "language": "Python", "task": "{{DISPLAYTITLE:de Bruijn sequences}}\nThe sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.\n\n\nA note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized\nunless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be\ncapitalized.\n\n\nIn combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on\na size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every\npossible length-''n'' string (computer science, formal theory) on ''A'' occurs\nexactly once as a contiguous substring.\n\n\nSuch a sequence is denoted by ''B''(''k'', ''n'') and has\nlength ''k''''n'', which is also the number of distinct substrings of\nlength ''n'' on ''A''; \nde Bruijn sequences are therefore optimally short.\n\n\nThere are:\n (k!)k(n-1) / kn\ndistinct de Bruijn sequences ''B''(''k'', ''n''). \n\n\n;Task:\nFor this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on\na PIN-like code lock that does not have an \"enter\"\nkey and accepts the last ''n'' digits entered.\n\n\nNote: automated teller machines (ATMs) used to work like\nthis, but their software has been updated to not allow a brute-force attack.\n\n\n;Example:\nA digital door lock with a 4-digit code would\nhave ''B'' (10, 4) solutions, with a length of '''10,000''' (digits).\n\nTherefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to\nopen the lock.\n\nTrying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses.\n\n\n;Task requirements:\n:* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.\n:::* Show the length of the generated de Bruijn sequence.\n:::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page).\n:::* Show the first and last '''130''' digits of the de Bruijn sequence.\n:* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence.\n:::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).\n:* Reverse the de Bruijn sequence.\n:* Again, perform the (above) verification test.\n:* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.\n:::* Perform the verification test (again). There should be four PIN codes missing.\n\n\n(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list\nany and all missing PIN codes.)\n\nShow all output here, on this page.\n\n\n\n;References:\n:* Wikipedia entry: de Bruijn sequence.\n:* MathWorld entry: de Bruijn sequence.\n:* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.\n\n", "solution": "# from https://en.wikipedia.org/wiki/De_Bruijn_sequence\n\ndef de_bruijn(k, n):\n \"\"\"\n de Bruijn sequence for alphabet k\n and subsequences of length n.\n \"\"\"\n try:\n # let's see if k can be cast to an integer;\n # if so, make our alphabet a list\n _ = int(k)\n alphabet = list(map(str, range(k)))\n\n except (ValueError, TypeError):\n alphabet = k\n k = len(k)\n\n a = [0] * k * n\n sequence = []\n\n def db(t, p):\n if t > n:\n if n % p == 0:\n sequence.extend(a[1:p + 1])\n else:\n a[t] = a[t - p]\n db(t + 1, p)\n for j in range(a[t - p] + 1, k):\n a[t] = j\n db(t + 1, t)\n db(1, 1)\n return \"\".join(alphabet[i] for i in sequence)\n \ndef validate(db):\n \"\"\"\n \n Check that all 10,000 combinations of 0-9 are present in \n De Bruijn string db.\n \n Validating the reversed deBruijn sequence:\n No errors found\n \n Validating the overlaid deBruijn sequence:\n 4 errors found:\n PIN number 1459 missing\n PIN number 4591 missing\n PIN number 5814 missing\n PIN number 8145 missing\n \n \"\"\"\n \n dbwithwrap = db+db[0:3]\n \n digits = '0123456789'\n \n errorstrings = []\n \n for d1 in digits:\n for d2 in digits:\n for d3 in digits:\n for d4 in digits:\n teststring = d1+d2+d3+d4\n if teststring not in dbwithwrap:\n errorstrings.append(teststring)\n \n if len(errorstrings) > 0:\n print(\" \"+str(len(errorstrings))+\" errors found:\")\n for e in errorstrings:\n print(\" PIN number \"+e+\" missing\")\n else:\n print(\" No errors found\")\n\ndb = de_bruijn(10, 4)\n\nprint(\" \")\nprint(\"The length of the de Bruijn sequence is \", str(len(db)))\nprint(\" \")\nprint(\"The first 130 digits of the de Bruijn sequence are: \"+db[0:130])\nprint(\" \")\nprint(\"The last 130 digits of the de Bruijn sequence are: \"+db[-130:])\nprint(\" \")\nprint(\"Validating the deBruijn sequence:\")\nvalidate(db)\ndbreversed = db[::-1]\nprint(\" \")\nprint(\"Validating the reversed deBruijn sequence:\")\nvalidate(dbreversed)\ndboverlaid = db[0:4443]+'.'+db[4444:]\nprint(\" \")\nprint(\"Validating the overlaid deBruijn sequence:\")\nvalidate(dboverlaid)\n"} {"title": "Deceptive numbers", "language": "Python", "task": "Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation '''Rn''' symbolizes the repunit made up of '''n''' ones.\n\nEvery prime '''p''' larger than 5, evenly divides the repunit '''Rp-1'''.\n\n\n;E.G.\n\nThe repunit '''R6''' is evenly divisible by '''7'''.\n\n111111 / 7 = 15873\n\nThe repunit '''R42''' is evenly divisible by '''43'''.\n\n111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677\n\nAnd so on.\n\n\nThere are composite numbers that also have this same property. They are often referred to as ''deceptive non-primes'' or ''deceptive numbers''.\n\n\nThe repunit '''R90''' is evenly divisible by the composite number '''91''' (=7*13).\n\n111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221\n\n\n;Task \n\n* Find and show at least the first '''10 deceptive numbers'''; composite numbers '''n''' that evenly divide the repunit '''Rn-1'''\n\n\n;See also\n\n;* Numbers Aplenty - Deceptive numbers\n;* OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R_{k-1}\n\n", "solution": "from itertools import count, islice\nfrom math import isqrt\n\ndef is_deceptive(n):\n if n & 1 and n % 3 and n % 5 and pow(10, n - 1, n) == 1:\n for d in range(7, isqrt(n) + 1, 6):\n if not (n % d and n % (d + 4)): return True\n return False\n\nprint(*islice(filter(is_deceptive, count()), 100))"} {"title": "Deming's funnel", "language": "Python from Racket", "task": "W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of \"rules\" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.\n\n* '''Rule 1''': The funnel remains directly above the target.\n* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.\n* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.\n* '''Rule 4''': The funnel is moved directly over the last place a marble landed.\n\nApply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule. \n\nNote that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.\n\n'''Stretch goal 1''': Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.\n\n'''Stretch goal 2''': Show scatter plots of all four results.\n\n\n;Further information:\n* Further explanation and interpretation\n* Video demonstration of the funnel experiment at the Mayo Clinic.\n\n", "solution": "import math \n\ndxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,\n -0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,\n 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, \n 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,\n -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, 0.201, \n 0.034, 0.097, -0.17, 0.054, -0.553, -0.024, -0.181, -0.7, -0.361, -0.789,\n 0.279, -0.174, -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853,\n 0.157, 0.648, 1.774, -1.043, 0.051, 0.021, 0.247, -0.31, 0.171, 0.0, 0.106,\n 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, 0.281, -0.749,\n -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, \n 0.087]\n\ndys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,\n -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, \n -0.742, -0.01, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199,\n 0.701, 0.096, -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, \n 0.009, 0.508, -0.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, \n -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, \n -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -0.044, \n 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, \n -0.729, 0.65, -1.103, 0.154, -1.72, 0.051, -0.385, 0.477, 1.537, -0.901, \n 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032]\n\ndef funnel(dxs, rule):\n x, rxs = 0, []\n for dx in dxs:\n rxs.append(x + dx)\n x = rule(x, dx)\n return rxs\n\ndef mean(xs): return sum(xs) / len(xs)\n\ndef stddev(xs):\n m = mean(xs)\n return math.sqrt(sum((x-m)**2 for x in xs) / len(xs))\n\ndef experiment(label, rule):\n rxs, rys = funnel(dxs, rule), funnel(dys, rule)\n print label\n print 'Mean x, y : %.4f, %.4f' % (mean(rxs), mean(rys))\n print 'Std dev x, y : %.4f, %.4f' % (stddev(rxs), stddev(rys))\n print\n\n\nexperiment('Rule 1:', lambda z, dz: 0)\nexperiment('Rule 2:', lambda z, dz: -dz)\nexperiment('Rule 3:', lambda z, dz: -(z+dz))\nexperiment('Rule 4:', lambda z, dz: z+dz)"} {"title": "Department numbers", "language": "Python", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "from itertools import permutations\n \ndef solve():\n c, p, f, s = \"\\\\,Police,Fire,Sanitation\".split(',')\n print(f\"{c:>3} {p:^6} {f:^4} {s:^10}\")\n c = 1\n for p, f, s in permutations(range(1, 8), r=3):\n if p + s + f == 12 and p % 2 == 0:\n print(f\"{c:>3}: {p:^6} {f:^4} {s:^10}\")\n c += 1\n \nif __name__ == '__main__':\n solve()"} {"title": "Department numbers", "language": "Python 3", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "'''Department numbers'''\n\nfrom itertools import (chain)\nfrom operator import (ne)\n\n\n# options :: Int -> Int -> Int -> [(Int, Int, Int)]\ndef options(lo, hi, total):\n '''Eligible integer triples.'''\n ds = enumFromTo(lo)(hi)\n return bind(filter(even, ds))(\n lambda x: bind(filter(curry(ne)(x), ds))(\n lambda y: bind([total - (x + y)])(\n lambda z: [(x, y, z)] if (\n z != y and lo <= z <= hi\n ) else []\n )\n )\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test'''\n\n xs = options(1, 7, 12)\n print(('Police', 'Sanitation', 'Fire'))\n for tpl in xs:\n print(tpl)\n print('\\nNo. of options: ' + str(len(xs)))\n\n\n# GENERIC ABSTRACTIONS ------------------------------------\n\n# bind (>>=) :: [a] -> (a -> [b]) -> [b]\ndef bind(xs):\n '''List monad injection operator.\n Two computations sequentially composed,\n with any value produced by the first\n passed as an argument to the second.'''\n return lambda f: list(\n chain.from_iterable(\n map(f, xs)\n )\n )\n\n\n# curry :: ((a, b) -> c) -> a -> b -> c\ndef curry(f):\n '''A curried function derived\n from an uncurried function.'''\n return lambda a: lambda b: f(a, b)\n\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# even :: Int -> Bool\ndef even(x):\n '''True if x is an integer\n multiple of two.'''\n return 0 == x % 2\n\n\nif __name__ == '__main__':\n main()"} {"title": "Department numbers", "language": "Python 3.7", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "'''Department numbers'''\n\nfrom operator import ne\n\n\n# options :: Int -> Int -> Int -> [(Int, Int, Int)]\ndef options(lo, hi, total):\n '''Eligible triples.'''\n ds = enumFromTo(lo)(hi)\n return [\n (x, y, z)\n for x in filter(even, ds)\n for y in filter(curry(ne)(x), ds)\n for z in [total - (x + y)]\n if y != z and lo <= z <= hi\n ]\n\n\n# Or with less tightly-constrained generation,\n# and more winnowing work downstream:\n\n# options2 :: Int -> Int -> Int -> [(Int, Int, Int)]\ndef options2(lo, hi, total):\n '''Eligible triples.'''\n ds = enumFromTo(lo)(hi)\n return [\n (x, y, z)\n for x in ds\n for y in ds\n for z in [total - (x + y)]\n if even(x) and y not in [x, z] and lo <= z <= hi\n ]\n\n\n# GENERIC -------------------------------------------------\n\n\n# curry :: ((a, b) -> c) -> a -> b -> c\ndef curry(f):\n '''A curried function derived\n from an uncurried function.'''\n return lambda a: lambda b: f(a, b)\n\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: list(range(m, 1 + n))\n\n\n# even :: Int -> Bool\ndef even(x):\n '''True if x is an integer\n multiple of two.'''\n return 0 == x % 2\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string derived by the intercalation\n of a list of strings with the newline character.'''\n return '\\n'.join(xs)\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test'''\n\n xs = options(1, 7, 12)\n print(('Police', 'Sanitation', 'Fire'))\n print(unlines(map(str, xs)))\n print('\\nNo. of options: ' + str(len(xs)))\n\n\nif __name__ == '__main__':\n main()"} {"title": "Descending primes", "language": "Python", "task": "Generate and show all primes with strictly descending decimal digits.\n\n;See also\n;* OEIS:A052014 - Primes with distinct digits in descending order\n\n;Related:\n*[[Ascending primes]]\n\n\n", "solution": "from sympy import isprime\n\ndef descending(xs=range(10)):\n for x in xs:\n yield x\n yield from descending(x*10 + d for d in range(x%10))\n\nfor i, p in enumerate(sorted(filter(isprime, descending()))):\n print(f'{p:9d}', end=' ' if (1 + i)%8 else '\\n')\n\nprint()"} {"title": "Detect division by zero", "language": "Python", "task": "Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.\n\n", "solution": "def div_check(x, y):\n try:\n x / y\n except ZeroDivisionError:\n return True\n else:\n return False"} {"title": "Determinant and permanent", "language": "Python", "task": "permanent of the matrix.\n\nThe determinant is given by\n:: \\det(A) = \\sum_\\sigma\\sgn(\\sigma)\\prod_{i=1}^n M_{i,\\sigma_i}\nwhile the permanent is given by\n:: \\operatorname{perm}(A)=\\sum_\\sigma\\prod_{i=1}^n M_{i,\\sigma_i}\nIn both cases the sum is over the permutations \\sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)\n\nMore efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.\n\n\n;Related task:\n* [[Permutations by swapping]]\n\n", "solution": "from itertools import permutations\nfrom operator import mul\nfrom math import fsum\nfrom spermutations import spermutations\n\ndef prod(lst):\n return reduce(mul, lst, 1)\n\ndef perm(a):\n n = len(a)\n r = range(n)\n s = permutations(r)\n return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)\n\ndef det(a):\n n = len(a)\n r = range(n)\n s = spermutations(n)\n return fsum(sign * prod(a[i][sigma[i]] for i in r)\n for sigma, sign in s)\n\nif __name__ == '__main__':\n from pprint import pprint as pp\n\n for a in ( \n [\n [1, 2], \n [3, 4]], \n\n [\n [1, 2, 3, 4],\n [4, 5, 6, 7],\n [7, 8, 9, 10],\n [10, 11, 12, 13]], \n\n [\n [ 0, 1, 2, 3, 4],\n [ 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19],\n [20, 21, 22, 23, 24]],\n ):\n print('')\n pp(a)\n print('Perm: %s Det: %s' % (perm(a), det(a)))"} {"title": "Determine if a string has all the same characters", "language": "Python", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "===Functional===\n\nWhat we are testing here is the cardinality of the set of characters from which a string is drawn, so the first thought might well be to use '''set'''. \n\nOn the other hand, '''itertools.groupby''' has the advantage of yielding richer information (the list of groups is ordered), for less work.\n\n"} {"title": "Determine if a string has all the same characters", "language": "Python 3.7", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "'''Determine if a string has all the same characters'''\n\nfrom itertools import groupby\n\n\n# firstDifferingCharLR :: String -> Either String Dict\ndef firstDifferingCharLR(s):\n '''Either a message reporting that no character changes were\n seen, or a dictionary with details of the first character\n (if any) that differs from that at the head of the string.\n '''\n def details(xs):\n c = xs[1][0]\n return {\n 'char': repr(c),\n 'hex': hex(ord(c)),\n 'index': s.index(c),\n 'total': len(s)\n }\n xs = list(groupby(s))\n return Right(details(xs)) if 1 < len(xs) else (\n Left('Total length ' + str(len(s)) + ' - No character changes.')\n )\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test of 7 strings'''\n\n print(fTable('First, if any, points of difference:\\n')(repr)(\n either(identity)(\n lambda dct: dct['char'] + ' (' + dct['hex'] +\n ') at character ' + str(1 + dct['index']) +\n ' of ' + str(dct['total']) + '.'\n )\n )(firstDifferingCharLR)([\n '',\n ' ',\n '2',\n '333',\n '.55',\n 'tttTTT',\n '4444 444'\n ]))\n\n\n# GENERIC -------------------------------------------------\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.\n '''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.\n '''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Determine if a string has all unique characters", "language": "Python", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are unique\n::::* indicate if or which character is duplicated and where\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as unique\n::* process the strings from left-to-right\n::* if unique, display a message saying such\n::* if not unique, then:\n::::* display a message saying such\n::::* display what character is duplicated\n::::* only the 1st non-unique character need be displayed\n::::* display where \"both\" duplicated characters are in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 1 which is a single period ('''.''')\n:::* a string of length 6 which contains: '''abcABC'''\n:::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX'''\n:::* a string of length 36 which ''doesn't'' contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "'''Determine if a string has all unique characters'''\n\nfrom itertools import groupby\n\n\n# duplicatedCharIndices :: String -> Maybe (Char, [Int])\ndef duplicatedCharIndices(s):\n '''Just the first duplicated character, and\n the indices of its occurrence, or\n Nothing if there are no duplications.\n '''\n def go(xs):\n if 1 < len(xs):\n duplicates = list(filter(lambda kv: 1 < len(kv[1]), [\n (k, list(v)) for k, v in groupby(\n sorted(xs, key=swap),\n key=snd\n )\n ]))\n return Just(second(fmap(fst))(\n sorted(\n duplicates,\n key=lambda kv: kv[1][0]\n )[0]\n )) if duplicates else Nothing()\n else:\n return Nothing()\n return go(list(enumerate(s)))\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Test over various strings.'''\n\n def showSample(s):\n return repr(s) + ' (' + str(len(s)) + ')'\n\n def showDuplicate(cix):\n c, ix = cix\n return repr(c) + (\n ' (' + hex(ord(c)) + ') at ' + repr(ix)\n )\n\n print(\n fTable('First duplicated character, if any:')(\n showSample\n )(maybe('None')(showDuplicate))(duplicatedCharIndices)([\n '', '.', 'abcABC', 'XYZ ZYX',\n '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'\n ])\n )\n\n\n# FORMATTING ----------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# fmap :: (a -> b) -> [a] -> [b]\ndef fmap(f):\n '''fmap over a list.\n f lifted to a function over a list.\n '''\n return lambda xs: [f(x) for x in xs]\n\n\n# fst :: (a, b) -> a\ndef fst(tpl):\n '''First member of a pair.'''\n return tpl[0]\n\n\n# head :: [a] -> a\ndef head(xs):\n '''The first element of a non-empty list.'''\n return xs[0] if isinstance(xs, list) else next(xs)\n\n\n# maybe :: b -> (a -> b) -> Maybe a -> b\ndef maybe(v):\n '''Either the default value v, if m is Nothing,\n or the application of f to x,\n where m is Just(x).\n '''\n return lambda f: lambda m: v if (\n None is m or m.get('Nothing')\n ) else f(m.get('Just'))\n\n\n# second :: (a -> b) -> ((c, a) -> (c, b))\ndef second(f):\n '''A simple function lifted to a function over a tuple,\n with f applied only to the second of two values.\n '''\n return lambda xy: (xy[0], f(xy[1]))\n\n\n# snd :: (a, b) -> b\ndef snd(tpl):\n '''Second member of a pair.'''\n return tpl[1]\n\n\n# swap :: (a, b) -> (b, a)\ndef swap(tpl):\n '''The swapped components of a pair.'''\n return (tpl[1], tpl[0])\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Determine if a string is collapsible", "language": "Python", "task": "Determine if a character string is ''collapsible''.\n\nAnd if so, collapse the string (by removing ''immediately repeated'' characters).\n\n\n\nIf a character string has ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nAn ''immediately repeated'' character is any character that is immediately followed by an\nidentical character (or characters). Another word choice could've been ''duplicated character'', but that\nmight have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.}\n\n\n;Examples:\nIn the following character string:\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated\nby underscores (above), even though they (those characters) appear elsewhere in the character string.\n\n\n\nSo, after ''collapsing'' the string, the result would be:\n\n The beter the 4-whel drive, the further you'l be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string:\n\n headmistressship \n\n\nThe \"collapsed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to\nlocate ''repeated'' characters and ''collapse'' (delete) them from the character\nstring. The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n string\n number\n ++\n 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln |\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888|\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. |\n 5 | --- Harry S Truman | <###### has many repeated blanks\n +------------------------------------------------------------------------+\n\n\n", "solution": "from itertools import groupby\n\ndef collapser(txt):\n return ''.join(item for item, grp in groupby(txt))\n\nif __name__ == '__main__':\n strings = [\n \"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"\ud83d\ude0d\ud83d\ude00\ud83d\ude4c\ud83d\udc83\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude4c\",\n ]\n for txt in strings:\n this = \"Original\"\n print(f\"\\n{this:14} Size: {len(txt)} \u00ab\u00ab\u00ab{txt}\u00bb\u00bb\u00bb\" )\n this = \"Collapsed\"\n sqz = collapser(txt)\n print(f\"{this:>14} Size: {len(sqz)} \u00ab\u00ab\u00ab{sqz}\u00bb\u00bb\u00bb\" )"} {"title": "Determine if a string is squeezable", "language": "Python", "task": "Determine if a character string is ''squeezable''.\n\nAnd if so, squeeze the string (by removing any number of\na ''specified'' ''immediately repeated'' character).\n\n\nThis task is very similar to the task '''Determine if a character string is collapsible''' except\nthat only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nA specified ''immediately repeated'' character is any specified character that is immediately \nfollowed by an identical character (or characters). Another word choice could've been ''duplicated\ncharacter'', but that might have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around\nNovember 2019) '''PL/I''' BIF: '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified ''immediately repeated'' character of '''e''':\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''e''' is an specified repeated character, indicated by an underscore\n(above), even though they (the characters) appear elsewhere in the character string.\n\n\n\nSo, after ''squeezing'' the string, the result would be:\n\n The better the 4-whel drive, the further you'll be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string, using a specified immediately repeated character '''s''':\n\n headmistressship \n\n\nThe \"squeezed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character\nand ''squeeze'' (delete) them from the character string. The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the specified repeated character (to be searched for and possibly ''squeezed''):\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( | a blank, a minus, a seven, a period)\n ++\n 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln | '-'\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'\n 5 | --- Harry S Truman | (below) <###### has many repeated blanks\n +------------------------------------------------------------------------+ |\n |\n |\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n * a blank\n * a minus\n * a lowercase '''r'''\n\n\nNote: there should be seven results shown, one each for the 1st four strings, and three results for\nthe 5th string.\n\n\n", "solution": "from itertools import groupby\n\ndef squeezer(s, txt):\n return ''.join(item if item == s else ''.join(grp)\n for item, grp in groupby(txt))\n\nif __name__ == '__main__':\n strings = [\n \"\",\n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ',\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\",\n \"\ud83d\ude0d\ud83d\ude00\ud83d\ude4c\ud83d\udc83\ud83d\ude0d\ud83d\ude0d\ud83d\ude0d\ud83d\ude4c\",\n ]\n squeezers = ' ,-,7,., -r,e,s,a,\ud83d\ude0d'.split(',')\n for txt, chars in zip(strings, squeezers):\n this = \"Original\"\n print(f\"\\n{this:14} Size: {len(txt)} \u00ab\u00ab\u00ab{txt}\u00bb\u00bb\u00bb\" )\n for ch in chars:\n this = f\"Squeezer '{ch}'\"\n sqz = squeezer(ch, txt)\n print(f\"{this:>14} Size: {len(sqz)} \u00ab\u00ab\u00ab{sqz}\u00bb\u00bb\u00bb\" )"} {"title": "Dice game probabilities", "language": "Python", "task": "Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.\n\nThey roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?\n\nLater the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?\n\nThis task was adapted from the Project Euler Problem n.205:\nhttps://projecteuler.net/problem=205\n\n", "solution": "from itertools import product\n\ndef gen_dict(n_faces, n_dice):\n counts = [0] * ((n_faces + 1) * n_dice)\n for t in product(range(1, n_faces + 1), repeat=n_dice):\n counts[sum(t)] += 1\n return counts, n_faces ** n_dice\n\ndef beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):\n c1, p1 = gen_dict(n_sides1, n_dice1)\n c2, p2 = gen_dict(n_sides2, n_dice2)\n p12 = float(p1 * p2)\n\n return sum(p[1] * q[1] / p12\n for p, q in product(enumerate(c1), enumerate(c2))\n if p[0] > q[0])\n\nprint beating_probability(4, 9, 6, 6)\nprint beating_probability(10, 5, 7, 6)"} {"title": "Digital root", "language": "Python", "task": "The digital root, X, of a number, n, is calculated:\n: find X as the sum of the digits of n\n: find a new X by summing the digits of X, repeating until X has only one digit.\n\nThe additive persistence is the number of summations required to obtain the single digit. \n\nThe task is to calculate the additive persistence and the digital root of a number, e.g.:\n:627615 has additive persistence 2 and digital root of 9;\n:39390 has additive persistence 2 and digital root of 6;\n:588225 has additive persistence 2 and digital root of 3;\n:393900588225 has additive persistence 2 and digital root of 9;\n\nThe digital root may be calculated in bases other than 10.\n\n\n;See:\n* [[Casting out nines]] for this wiki's use of this procedure.\n* [[Digital root/Multiplicative digital root]]\n* [[Sum digits of an integer]]\n* Digital root sequence on OEIS\n* Additive persistence sequence on OEIS\n* [[Iterated digits squaring]]\n\n", "solution": "def digital_root (n):\n ap = 0\n n = abs(int(n))\n while n >= 10:\n n = sum(int(digit) for digit in str(n))\n ap += 1\n return ap, n\n\nif __name__ == '__main__':\n for n in [627615, 39390, 588225, 393900588225, 55]:\n persistance, root = digital_root(n)\n print(\"%12i has additive persistance %2i and digital root %i.\" \n % (n, persistance, root))"} {"title": "Disarium numbers", "language": "Python", "task": "A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.\n\n\n;E.G.\n\n'''135''' is a '''Disarium number''':\n\n 11 + 32 + 53 == 1 + 9 + 125 == 135\n\nThere are a finite number of '''Disarium numbers'''.\n\n\n;Task\n\n* Find and display the first 18 '''Disarium numbers'''.\n\n\n;Stretch\n\n* Find and display all 20 '''Disarium numbers'''.\n\n\n;See also\n\n;* Geeks for Geeks - Disarium numbers\n;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)\n;* Related task: Narcissistic decimal number\n;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''\n\n", "solution": "#!/usr/bin/python\n\ndef isDisarium(n):\n digitos = len(str(n))\n suma = 0\n x = n\n while x != 0:\n suma += (x % 10) ** digitos\n digitos -= 1\n x //= 10\n if suma == n:\n return True\n else:\n return False\n\nif __name__ == '__main__':\n limite = 19\n cont = 0\n n = 0\n print(\"The first\",limite,\"Disarium numbers are:\")\n while cont < limite:\n if isDisarium(n):\n print(n, end = \" \")\n cont += 1\n n += 1"} {"title": "Display a linear combination", "language": "Python", "task": "Display a finite linear combination in an infinite vector basis (e_1, e_2,\\ldots).\n\nWrite a function that, when given a finite list of scalars (\\alpha^1,\\alpha^2,\\ldots), creates a string representing the linear combination \\sum_i\\alpha^i e_i in an explicit format often used in mathematics, that is:\n\n:\\alpha^{i_1}e_{i_1}\\pm|\\alpha^{i_2}|e_{i_2}\\pm|\\alpha^{i_3}|e_{i_3}\\pm\\ldots\n\nwhere \\alpha^{i_k}\\neq 0\n\nThe output must comply to the following rules:\n* don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.\n* don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.\n* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. \n::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.\n\n\nShow here output for the following lists of scalars:\n\n 1) 1, 2, 3\n 2) 0, 1, 2, 3\n 3) 1, 0, 3, 4\n 4) 1, 2, 0\n 5) 0, 0, 0\n 6) 0\n 7) 1, 1, 1\n 8) -1, -1, -1\n 9) -1, -2, 0, -3\n10) -1\n\n\n", "solution": "def linear(x):\n return ' + '.join(['{}e({})'.format('-' if v == -1 else '' if v == 1 else str(v) + '*', i + 1)\n for i, v in enumerate(x) if v] or ['0']).replace(' + -', ' - ')\n\nlist(map(lambda x: print(linear(x)), [[1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0],\n [0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], [-1, -2, 0, 3], [-1]]))\n"} {"title": "Display an outline as a nested table", "language": "Python", "task": "{| class=\"wikitable\" style=\"text-align: center;\"\n|-\n| style=\"background: #ffffe6; \" colspan=7 | Display an outline as a nested table.\n|-\n| style=\"background: #ffebd2; \" colspan=3 | Parse the outline to a tree,\n| style=\"background: #f0fff0; \" colspan=2 | count the leaves descending from each node,\n| style=\"background: #e6ffff; \" colspan=2 | and write out a table with 'colspan' values\n|-\n| style=\"background: #ffebd2; \" | measuring the indent of each line,\n| style=\"background: #ffebd2; \" | translating the indentation to a nested structure,\n| style=\"background: #ffebd2; \" | and padding the tree to even depth.\n| style=\"background: #f0fff0; \" | defining the width of a leaf as 1,\n| style=\"background: #f0fff0; \" | and the width of a parent node as a sum.\n| style=\"background: #e6ffff; \" | either as a wiki table,\n| style=\"background: #e6ffff; \" | or as HTML.\n|-\n| | \n| | \n| | \n| | \n| style=\"background: #f0fff0; \" | (The sum of the widths of its children)\n| | \n| | \n|}\n\nThe graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches.\n\n;Task:\nGiven a outline with at least 3 levels of indentation, for example:\n\nDisplay an outline as a nested table.\n Parse the outline to a tree,\n measuring the indent of each line,\n translating the indentation to a nested structure,\n and padding the tree to even depth.\n count the leaves descending from each node,\n defining the width of a leaf as 1,\n and the width of a parent node as a sum.\n (The sum of the widths of its children)\n and write out a table with 'colspan' values\n either as a wiki table,\n or as HTML.\n\nwrite a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table.\n\nThe WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string:\n\n{| class=\"wikitable\" style=\"text-align: center;\"\n|-\n| style=\"background: #ffffe6; \" colspan=7 | Display an outline as a nested table.\n|-\n| style=\"background: #ffebd2; \" colspan=3 | Parse the outline to a tree,\n| style=\"background: #f0fff0; \" colspan=2 | count the leaves descending from each node,\n| style=\"background: #e6ffff; \" colspan=2 | and write out a table with 'colspan' values\n|-\n| style=\"background: #ffebd2; \" | measuring the indent of each line,\n| style=\"background: #ffebd2; \" | translating the indentation to a nested structure,\n| style=\"background: #ffebd2; \" | and padding the tree to even depth.\n| style=\"background: #f0fff0; \" | defining the width of a leaf as 1,\n| style=\"background: #f0fff0; \" | and the width of a parent node as a sum.\n| style=\"background: #e6ffff; \" | either as a wiki table,\n| style=\"background: #e6ffff; \" | or as HTML.\n|-\n| | \n| | \n| | \n| | \n| style=\"background: #f0fff0; \" | (The sum of the widths of its children)\n| | \n| | \n|}\n\n;Extra credit:\nUse background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed.\n\n\n;Output:\nDisplay your nested table on this page.\n\n", "solution": "\"\"\"Display an outline as a nested table. Requires Python >=3.6.\"\"\"\n\nimport itertools\nimport re\nimport sys\n\nfrom collections import deque\nfrom typing import NamedTuple\n\n\nRE_OUTLINE = re.compile(r\"^((?: |\\t)*)(.+)$\", re.M)\n\nCOLORS = itertools.cycle(\n [\n \"#ffffe6\",\n \"#ffebd2\",\n \"#f0fff0\",\n \"#e6ffff\",\n \"#ffeeff\",\n ]\n)\n\n\nclass Node:\n def __init__(self, indent, value, parent, children=None):\n self.indent = indent\n self.value = value\n self.parent = parent\n self.children = children or []\n\n self.color = None\n\n def depth(self):\n if self.parent:\n return self.parent.depth() + 1\n return -1\n\n def height(self):\n \"\"\"Height of the subtree rooted at this node.\"\"\"\n if not self.children:\n return 0\n return max(child.height() for child in self.children) + 1\n\n def colspan(self):\n if self.leaf:\n return 1\n return sum(child.colspan() for child in self.children)\n\n @property\n def leaf(self):\n return not bool(self.children)\n\n def __iter__(self):\n # Level order tree traversal.\n q = deque()\n q.append(self)\n while q:\n node = q.popleft()\n yield node\n q.extend(node.children)\n\n\nclass Token(NamedTuple):\n indent: int\n value: str\n\n\ndef tokenize(outline):\n \"\"\"Generate ``Token``s from the given outline.\"\"\"\n for match in RE_OUTLINE.finditer(outline):\n indent, value = match.groups()\n yield Token(len(indent), value)\n\n\ndef parse(outline):\n \"\"\"Return the given outline as a tree of ``Node``s.\"\"\"\n # Split the outline into lines and count the level of indentation.\n tokens = list(tokenize(outline))\n\n # Parse the tokens into a tree of nodes.\n temp_root = Node(-1, \"\", None)\n _parse(tokens, 0, temp_root)\n\n # Pad the tree so that all branches have the same depth.\n root = temp_root.children[0]\n pad_tree(root, root.height())\n\n return root\n\n\ndef _parse(tokens, index, node):\n \"\"\"Recursively build a tree of nodes.\n\n Args:\n tokens (list): A collection of ``Token``s.\n index (int): Index of the current token.\n node (Node): Potential parent or sibling node.\n \"\"\"\n # Base case. No more lines.\n if index >= len(tokens):\n return\n\n token = tokens[index]\n\n if token.indent == node.indent:\n # A sibling of node\n current = Node(token.indent, token.value, node.parent)\n node.parent.children.append(current)\n _parse(tokens, index + 1, current)\n\n elif token.indent > node.indent:\n # A child of node\n current = Node(token.indent, token.value, node)\n node.children.append(current)\n _parse(tokens, index + 1, current)\n\n elif token.indent < node.indent:\n # Try the node's parent until we find a sibling.\n _parse(tokens, index, node.parent)\n\n\ndef pad_tree(node, height):\n \"\"\"Pad the tree with blank nodes so all branches have the same depth.\"\"\"\n if node.leaf and node.depth() < height:\n pad_node = Node(node.indent + 1, \"\", node)\n node.children.append(pad_node)\n\n for child in node.children:\n pad_tree(child, height)\n\n\ndef color_tree(node):\n \"\"\"Walk the tree and color each node as we go.\"\"\"\n if not node.value:\n node.color = \"#F9F9F9\"\n elif node.depth() <= 1:\n node.color = next(COLORS)\n else:\n node.color = node.parent.color\n\n for child in node.children:\n color_tree(child)\n\n\ndef table_data(node):\n \"\"\"Return an HTML table data element for the given node.\"\"\"\n indent = \" \"\n\n if node.colspan() > 1:\n colspan = f'colspan=\"{node.colspan()}\"'\n else:\n colspan = \"\"\n\n if node.color:\n style = f'style=\"background-color: {node.color};\"'\n else:\n style = \"\"\n\n attrs = \" \".join([colspan, style])\n return f\"{indent}{node.value}\"\n\n\ndef html_table(tree):\n \"\"\"Return the tree as an HTML table.\"\"\"\n # Number of columns in the table.\n table_cols = tree.colspan()\n\n # Running count of columns in the current row.\n row_cols = 0\n\n # HTML buffer\n buf = [\"\"]\n\n # Breadth first iteration.\n for node in tree:\n if row_cols == 0:\n buf.append(\" \")\n\n buf.append(table_data(node))\n row_cols += node.colspan()\n\n if row_cols == table_cols:\n buf.append(\" \")\n row_cols = 0\n\n buf.append(\"
\")\n return \"\\n\".join(buf)\n\n\ndef wiki_table_data(node):\n \"\"\"Return an wiki table data string for the given node.\"\"\"\n if not node.value:\n return \"| |\"\n\n if node.colspan() > 1:\n colspan = f\"colspan={node.colspan()}\"\n else:\n colspan = \"\"\n\n if node.color:\n style = f'style=\"background: {node.color};\"'\n else:\n style = \"\"\n\n attrs = \" \".join([colspan, style])\n return f\"| {attrs} | {node.value}\"\n\n\ndef wiki_table(tree):\n \"\"\"Return the tree as a wiki table.\"\"\"\n # Number of columns in the table.\n table_cols = tree.colspan()\n\n # Running count of columns in the current row.\n row_cols = 0\n\n # HTML buffer\n buf = ['{| class=\"wikitable\" style=\"text-align: center;\"']\n\n for node in tree:\n if row_cols == 0:\n buf.append(\"|-\")\n\n buf.append(wiki_table_data(node))\n row_cols += node.colspan()\n\n if row_cols == table_cols:\n row_cols = 0\n\n buf.append(\"|}\")\n return \"\\n\".join(buf)\n\n\ndef example(table_format=\"wiki\"):\n \"\"\"Write an example table to stdout in either HTML or Wiki format.\"\"\"\n\n outline = (\n \"Display an outline as a nested table.\\n\"\n \" Parse the outline to a tree,\\n\"\n \" measuring the indent of each line,\\n\"\n \" translating the indentation to a nested structure,\\n\"\n \" and padding the tree to even depth.\\n\"\n \" count the leaves descending from each node,\\n\"\n \" defining the width of a leaf as 1,\\n\"\n \" and the width of a parent node as a sum.\\n\"\n \" (The sum of the widths of its children)\\n\"\n \" and write out a table with 'colspan' values\\n\"\n \" either as a wiki table,\\n\"\n \" or as HTML.\"\n )\n\n tree = parse(outline)\n color_tree(tree)\n\n if table_format == \"wiki\":\n print(wiki_table(tree))\n else:\n print(html_table(tree))\n\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n\n if len(args) == 1:\n table_format = args[0]\n else:\n table_format = \"wiki\"\n\n example(table_format)"} {"title": "Distance and Bearing", "language": "Python", "task": "It is very important in aviation to have knowledge of the nearby airports at any time in flight. \n;Task:\nDetermine the distance and bearing from an Airplane to the 20 nearest Airports whenever requested.\nUse the non-commercial data from openflights.org airports.dat as reference.\n\n\nA request comes from an airplane at position ( latitude, longitude ): ( '''51.514669, 2.198581''' ).\n\n\nYour report should contain the following information from table airports.dat (column shown in brackets):\n\nName(2), Country(4), ICAO(6), Distance and Bearing calculated from Latitude(7) and Longitude(8). \n\n\nDistance is measured in nautical miles (NM). Resolution is 0.1 NM.\n\nBearing is measured in degrees (deg). 0deg = 360deg = north then clockwise 90deg = east, 180deg = south, 270deg = west. Resolution is 1deg.\n \n\n;See:\n:* openflights.org/data: Airport, airline and route data\n:* Movable Type Scripts: Calculate distance, bearing and more between Latitude/Longitude points\n\n", "solution": "''' Rosetta Code task Distance_and_Bearing '''\n\nfrom math import radians, degrees, sin, cos, asin, atan2, sqrt\nfrom pandas import read_csv\n\n\nEARTH_RADIUS_KM = 6372.8\nTASK_CONVERT_NM = 0.0094174\nAIRPORT_DATA_FILE = 'airports.dat.txt'\n\nQUERY_LATITUDE, QUERY_LONGITUDE = 51.514669, 2.198581\n\n\ndef haversine(lat1, lon1, lat2, lon2):\n '''\n Given two latitude, longitude pairs in degrees for two points on the Earth,\n get distance (nautical miles) and initial direction of travel (degrees)\n for travel from lat1, lon1 to lat2, lon2\n '''\n rlat1, rlon1, rlat2, rlon2 = [radians(x) for x in [lat1, lon1, lat2, lon2]]\n dlat = rlat2 - rlat1\n dlon = rlon2 - rlon1\n arc = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlon / 2) ** 2\n clen = 2.0 * degrees(asin(sqrt(arc)))\n theta = atan2(sin(dlon) * cos(rlat2),\n cos(rlat1) * sin(rlat2) - sin(rlat1) * cos(rlat2) * cos(dlon))\n theta = (degrees(theta) + 360) % 360\n return EARTH_RADIUS_KM * clen * TASK_CONVERT_NM, theta\n\n\ndef find_nearest_airports(latitude, longitude, wanted=20, csv=AIRPORT_DATA_FILE):\n ''' Given latitude and longitude, find `wanted` closest airports in database file csv. '''\n airports = read_csv(csv, header=None, usecols=[1, 3, 5, 6, 7], names=[\n 'Name', 'Country', 'ICAO', 'Latitude', 'Longitude'])\n airports['Distance'] = 0.0\n airports['Bearing'] = 0\n for (idx, row) in enumerate(airports.itertuples()):\n distance, bearing = haversine(\n latitude, longitude, row.Latitude, row.Longitude)\n airports.at[idx, 'Distance'] = round(distance, ndigits=1)\n airports.at[idx, 'Bearing'] = int(round(bearing))\n\n airports.sort_values(by=['Distance'], ignore_index=True, inplace=True)\n return airports.loc[0:wanted-1, ['Name', 'Country', 'ICAO', 'Distance', 'Bearing']]\n\n\nprint(find_nearest_airports(QUERY_LATITUDE, QUERY_LONGITUDE))\n"} {"title": "Diversity prediction theorem", "language": "Python 3.7", "task": "The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. \n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\n\nScott E. Page introduced the diversity prediction theorem: \n: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. \n\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\n\n;Definitions:\n::* Average Individual Error: Average of the individual squared errors\n::* Collective Error: Squared error of the collective prediction\n::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then\n:::::: Collective Error = Average Individual Error - Prediction Diversity\n\n;Task:\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n:::* the true value and the crowd estimates\n:::* the average error\n:::* the crowd error\n:::* the prediction diversity\n\n\nUse (at least) these two examples:\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''\n\n\n\n;Also see:\n:* Wikipedia entry: Wisdom of the crowd\n:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').\n\n", "solution": "'''Diversity prediction theorem'''\n\nfrom itertools import chain\nfrom functools import reduce\n\n\n# diversityValues :: Num a => a -> [a] ->\n# { mean-Error :: a, crowd-error :: a, diversity :: a }\ndef diversityValues(x):\n '''The mean error, crowd error and\n diversity, for a given observation x\n and a non-empty list of predictions ps.\n '''\n def go(ps):\n mp = mean(ps)\n return {\n 'mean-error': meanErrorSquared(x)(ps),\n 'crowd-error': pow(x - mp, 2),\n 'diversity': meanErrorSquared(mp)(ps)\n }\n return go\n\n\n# meanErrorSquared :: Num -> [Num] -> Num\ndef meanErrorSquared(x):\n '''The mean of the squared differences\n between the observed value x and\n a non-empty list of predictions ps.\n '''\n def go(ps):\n return mean([\n pow(p - x, 2) for p in ps\n ])\n return go\n\n\n# ------------------------- TEST -------------------------\n# main :: IO ()\ndef main():\n '''Observed value: 49,\n prediction lists: various.\n '''\n\n print(unlines(map(\n showDiversityValues(49),\n [\n [48, 47, 51],\n [48, 47, 51, 42],\n [50, '?', 50, {}, 50], # Non-numeric values.\n [] # Missing predictions.\n ]\n )))\n print(unlines(map(\n showDiversityValues('49'), # String in place of number.\n [\n [50, 50, 50],\n [40, 35, 40],\n ]\n )))\n\n\n# ---------------------- FORMATTING ----------------------\n\n# showDiversityValues :: Num -> [Num] -> Either String String\ndef showDiversityValues(x):\n '''Formatted string representation\n of diversity values for a given\n observation x and a non-empty\n list of predictions p.\n '''\n def go(ps):\n def showDict(dct):\n w = 4 + max(map(len, dct.keys()))\n\n def showKV(a, kv):\n k, v = kv\n return a + k.rjust(w, ' ') + (\n ' : ' + showPrecision(3)(v) + '\\n'\n )\n return 'Predictions: ' + showList(ps) + ' ->\\n' + (\n reduce(showKV, dct.items(), '')\n )\n\n def showProblem(e):\n return (\n unlines(map(indented(1), e)) if (\n isinstance(e, list)\n ) else indented(1)(repr(e))\n ) + '\\n'\n\n return 'Observation: ' + repr(x) + '\\n' + (\n either(showProblem)(showDict)(\n bindLR(numLR(x))(\n lambda n: bindLR(numsLR(ps))(\n compose(Right, diversityValues(n))\n )\n )\n )\n )\n return go\n\n\n# ------------------ GENERIC FUNCTIONS -------------------\n\n# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.\n '''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# bindLR (>>=) :: Either a -> (a -> Either b) -> Either b\ndef bindLR(m):\n '''Either monad injection operator.\n Two computations sequentially composed,\n with any value produced by the first\n passed as an argument to the second.\n '''\n def go(mf):\n return (\n mf(m.get('Right')) if None is m.get('Left') else m\n )\n return go\n\n\n# compose :: ((a -> a), ...) -> (a -> a)\ndef compose(*fs):\n '''Composition, from right to left,\n of a series of functions.\n '''\n def go(f, g):\n def fg(x):\n return f(g(x))\n return fg\n return reduce(go, fs, identity)\n\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been mapped.\n The list monad can be derived by using a function f which\n wraps its output in a list,\n (using an empty list to represent computational failure).\n '''\n def go(xs):\n return chain.from_iterable(map(f, xs))\n return go\n\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.\n '''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# identity :: a -> a\ndef identity(x):\n '''The identity function.'''\n return x\n\n\n# indented :: Int -> String -> String\ndef indented(n):\n '''String indented by n multiples\n of four spaces.\n '''\n return lambda s: (4 * ' ' * n) + s\n\n# mean :: [Num] -> Float\ndef mean(xs):\n '''Arithmetic mean of a list\n of numeric values.\n '''\n return sum(xs) / float(len(xs))\n\n\n# numLR :: a -> Either String Num\ndef numLR(x):\n '''Either Right x if x is a float or int,\n or a Left explanatory message.'''\n return Right(x) if (\n isinstance(x, (float, int))\n ) else Left(\n 'Expected number, saw: ' + (\n str(type(x)) + ' ' + repr(x)\n )\n )\n\n\n# numsLR :: [a] -> Either String [Num]\ndef numsLR(xs):\n '''Either Right xs if all xs are float or int,\n or a Left explanatory message.'''\n def go(ns):\n ls, rs = partitionEithers(map(numLR, ns))\n return Left(ls) if ls else Right(rs)\n return bindLR(\n Right(xs) if (\n bool(xs) and isinstance(xs, list)\n ) else Left(\n 'Expected a non-empty list, saw: ' + (\n str(type(xs)) + ' ' + repr(xs)\n )\n )\n )(go)\n\n\n# partitionEithers :: [Either a b] -> ([a],[b])\ndef partitionEithers(lrs):\n '''A list of Either values partitioned into a tuple\n of two lists, with all Left elements extracted\n into the first list, and Right elements\n extracted into the second list.\n '''\n def go(a, x):\n ls, rs = a\n r = x.get('Right')\n return (ls + [x.get('Left')], rs) if None is r else (\n ls, rs + [r]\n )\n return reduce(go, lrs, ([], []))\n\n\n# showList :: [a] -> String\ndef showList(xs):\n '''Compact string representation of a list'''\n return '[' + ','.join(str(x) for x in xs) + ']'\n\n\n# showPrecision :: Int -> Float -> String\ndef showPrecision(n):\n '''A string showing a floating point number\n at a given degree of precision.'''\n def go(x):\n return str(round(x, n))\n return go\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string derived by the intercalation\n of a list of strings with the newline character.'''\n return '\\n'.join(xs)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Doomsday rule", "language": "Python", "task": " About the task\nJohn Conway (1937-2020), was a mathematician who also invented several mathematically\noriented computer pastimes, such as the famous Game of Life cellular automaton program.\nDr. Conway invented a simple algorithm for finding the day of the week, given any date.\nThe algorithm was based on calculating the distance of a given date from certain\n\"anchor days\" which follow a pattern for the day of the week upon which they fall.\n\n; Algorithm\nThe formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and\n\n doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7\n\nwhich, for 2021, is 0 (Sunday).\n\nTo calculate the day of the week, we then count days from a close doomsday,\nwith these as charted here by month, then add the doomsday for the year,\nthen get the remainder after dividing by 7. This should give us the number\ncorresponding to the day of the week for that date.\n\n Month\t Doomsday Dates for Month\n --------------------------------------------\n January (common years) 3, 10, 17, 24, 31\n January (leap years) 4, 11, 18, 25\n February (common years) 7, 14, 21, 28\n February (leap years) 1, 8, 15, 22, 29\n March 7, 14, 21, 28\n April 4, 11, 18, 25\n May 2, 9, 16, 23, 30\n June 6, 13, 20, 27\n July 4, 11, 18, 25\n August 1, 8, 15, 22, 29\n September 5, 12, 19, 26\n October 3, 10, 17, 24, 31\n November 7, 14, 21, 28\n December 5, 12, 19, 26\n\n; Task\n\nGiven the following dates:\n\n* 1800-01-06 (January 6, 1800)\n* 1875-03-29 (March 29, 1875)\n* 1915-12-07 (December 7, 1915)\n* 1970-12-23 (December 23, 1970)\n* 2043-05-14 (May 14, 2043)\n* 2077-02-12 (February 12, 2077)\n* 2101-04-02 (April 2, 2101)\n\n\nUse Conway's Doomsday rule to calculate the day of the week for each date.\n\n\n; see also\n* Doomsday rule\n* Tomorrow is the Day After Doomsday (p.28)\n\n\n\n\n", "solution": "from datetime import date\nfrom calendar import isleap\n\ndef weekday(d):\n days = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\n \"Friday\", \"Saturday\"]\n dooms = [\n [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],\n [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]\n ]\n \n c = d.year // 100\n r = d.year % 100\n s = r // 12\n t = r % 12\n c_anchor = (5 * (c % 4) + 2) % 7\n doomsday = (s + t + (t // 4) + c_anchor) % 7\n anchorday = dooms[isleap(d.year)][d.month - 1]\n weekday = (doomsday + d.day - anchorday + 7) % 7\n return days[weekday]\n\ndates = [date(*x) for x in\n [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),\n (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]\n]\n\nfor d in dates:\n tense = \"was\" if d < date.today() else \"is\" if d == date.today() else \"will be\"\n print(\"{} {} a {}\".format(d.strftime(\"%B %d, %Y\"), tense, weekday(d)))"} {"title": "Dot product", "language": "Python", "task": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "def dotp(a,b):\n assert len(a) == len(b), 'Vector sizes must match'\n return sum(aterm * bterm for aterm,bterm in zip(a, b))\n\nif __name__ == '__main__':\n a, b = [1, 3, -5], [4, -2, -1]\n assert dotp(a,b) == 3"} {"title": "Dot product", "language": "Python 3.7", "task": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "'''Dot product'''\n\nfrom operator import (mul)\n\n\n# dotProduct :: Num a => [a] -> [a] -> Either String a\ndef dotProduct(xs):\n '''Either the dot product of xs and ys,\n or a string reporting unmatched vector sizes.\n '''\n return lambda ys: Left('vector sizes differ') if (\n len(xs) != len(ys)\n ) else Right(sum(map(mul, xs, ys)))\n\n\n# TEST ----------------------------------------------------\n# main :: IO ()\ndef main():\n '''Dot product of other vectors with [1, 3, -5]'''\n\n print(\n fTable(main.__doc__ + ':\\n')(str)(str)(\n compose(\n either(append('Undefined :: '))(str)\n )(dotProduct([1, 3, -5]))\n )([[4, -2, -1, 8], [4, -2], [4, 2, -1], [4, -2, -1]])\n )\n\n\n# GENERIC -------------------------------------------------\n\n# Left :: a -> Either a b\ndef Left(x):\n '''Constructor for an empty Either (option type) value\n with an associated string.\n '''\n return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right :: b -> Either a b\ndef Right(x):\n '''Constructor for a populated Either (option type) value'''\n return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# append (++) :: [a] -> [a] -> [a]\n# append (++) :: String -> String -> String\ndef append(xs):\n '''Two lists or strings combined into one.'''\n return lambda ys: xs + ys\n\n\n# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n '''Right to left function composition.'''\n return lambda f: lambda x: g(f(x))\n\n\n# either :: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n '''The application of fl to e if e is a Left value,\n or the application of fr to e if e is a Right value.\n '''\n return lambda fr: lambda e: fl(e['Left']) if (\n None is e['Right']\n ) else fr(e['Right'])\n\n\n# FORMATTING ----------------------------------------------\n\n# fTable :: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n '''Heading -> x display function -> fx display function ->\n f -> xs -> tabular string.\n '''\n def go(xShow, fxShow, f, xs):\n ys = [xShow(x) for x in xs]\n w = max(map(len, ys))\n return s + '\\n' + '\\n'.join(map(\n lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n xs, ys\n ))\n return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n xShow, fxShow, f, xs\n )\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Draw a clock", "language": "Python", "task": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "[http://www.thinkgeek.com/gadgets/watches/6a17/ Think Geek Binary Clock]\n"} {"title": "Draw a clock", "language": "Python 2.6+, 3.0+", "task": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "import time\n\ndef chunks(l, n=5):\n return [l[i:i+n] for i in range(0, len(l), n)]\n\ndef binary(n, digits=8):\n n=int(n)\n return '{0:0{1}b}'.format(n, digits)\n\ndef secs(n):\n n=int(n)\n h='x' * n\n return \"|\".join(chunks(h))\n\ndef bin_bit(h):\n h=h.replace(\"1\",\"x\")\n h=h.replace(\"0\",\" \")\n return \"|\".join(list(h))\n\n\nx=str(time.ctime()).split()\ny=x[3].split(\":\")\n\ns=y[-1]\ny=map(binary,y[:-1])\n\nprint bin_bit(y[0])\nprint\nprint bin_bit(y[1])\nprint\nprint secs(s)"} {"title": "Draw a rotating cube", "language": "Python 2.7.9", "task": "Task\nDraw a rotating cube. \n\nIt should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.\n\n\n;Related tasks\n* Draw a cuboid\n* write language name in 3D ASCII\n\n", "solution": "from visual import *\nscene.title = \"VPython: Draw a rotating cube\"\n\nscene.range = 2\nscene.autocenter = True\n\nprint \"Drag with right mousebutton to rotate view.\"\nprint \"Drag up+down with middle mousebutton to zoom.\"\n\ndeg45 = math.radians(45.0) # 0.785398163397\n\ncube = box() # using defaults, see http://www.vpython.org/contents/docs/defaults.html \ncube.rotate( angle=deg45, axis=(1,0,0) )\ncube.rotate( angle=deg45, axis=(0,0,1) )\n\nwhile True: # Animation-loop\n rate(50)\n cube.rotate( angle=0.005, axis=(0,1,0) )\n"} {"title": "Draw a sphere", "language": "Python from C", "task": "{{requires|Graphics}}\n\n\n;Task:\nDraw a sphere. \n\nThe sphere can be represented graphically, or in ASCII art, depending on the language capabilities. \n\nEither static or rotational projection is acceptable for this task.\n\n\n;Related tasks:\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar\n\n", "solution": "import math\n\nshades = ('.',':','!','*','o','e','&','#','%','@')\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]/len, v[1]/len, v[2]/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)"} {"title": "Draw a sphere", "language": "Python 2.7.5", "task": "{{requires|Graphics}}\n\n\n;Task:\nDraw a sphere. \n\nThe sphere can be represented graphically, or in ASCII art, depending on the language capabilities. \n\nEither static or rotational projection is acceptable for this task.\n\n\n;Related tasks:\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar\n\n", "solution": "from __future__ import print_function, division\nfrom visual import *\n\ntitle = \"VPython: Draw a sphere\"\nscene.title = title\nprint( \"%s\\n\" % title )\n\nprint( 'Drag with right mousebutton to rotate view' )\nprint( 'Drag up+down with middle mousebutton to zoom')\n\nscene.autocenter = True\n\n# uncomment any (or all) of those variants:\nS1 = sphere(pos=(0.0, 0.0, 0.0), radius=1.0, color=color.blue)\n#S2 = sphere(pos=(2.0, 0.0, 0.0), radius=1.0, material=materials.earth)\n#S3 = sphere(pos=(0.0, 2.0, 0.0), radius=1.0, material=materials.BlueMarble)\n#S4 = sphere(pos=(0.0, 0.0, 2.0), radius=1.0,\n# color=color.orange, material=materials.marble)\n\nwhile True: # Animation-loop\n rate(100)\n pass # no animation in this demo\n"} {"title": "Dutch national flag problem", "language": "Python", "task": "The Dutch national flag is composed of three coloured bands in the order:\n::* red (top)\n::* then white, and\n::* lastly blue (at the bottom). \n\n\nThe problem posed by Edsger Dijkstra is:\n:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.\nWhen the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...\n\n\n;Task\n# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.\n# Sort the balls in a way idiomatic to your language.\n# Check the sorted balls ''are'' in the order of the Dutch national flag.\n\n\n;C.f.:\n* Dutch national flag problem\n* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)\n\n", "solution": "import random\n\ncolours_in_order = 'Red White Blue'.split()\n\ndef dutch_flag_sort(items, order=colours_in_order):\n 'return sort of items using the given order'\n reverse_index = dict((x,i) for i,x in enumerate(order))\n return sorted(items, key=lambda x: reverse_index[x])\n\ndef dutch_flag_check(items, order=colours_in_order):\n 'Return True if each item of items is in the given order'\n reverse_index = dict((x,i) for i,x in enumerate(order))\n order_of_items = [reverse_index[item] for item in items]\n return all(x <= y for x, y in zip(order_of_items, order_of_items[1:]))\n\ndef random_balls(mx=5):\n 'Select from 1 to mx balls of each colour, randomly'\n balls = sum([[colour] * random.randint(1, mx)\n for colour in colours_in_order], [])\n random.shuffle(balls)\n return balls\n\ndef main():\n # Ensure we start unsorted\n while True:\n balls = random_balls()\n if not dutch_flag_check(balls):\n break\n print(\"Original Ball order:\", balls)\n sorted_balls = dutch_flag_sort(balls)\n print(\"Sorted Ball Order:\", sorted_balls)\n assert dutch_flag_check(sorted_balls), 'Whoops. Not sorted!'\n\nif __name__ == '__main__':\n main()"} {"title": "EKG sequence convergence", "language": "Python", "task": "The sequence is from the natural numbers and is defined by:\n* a(1) = 1; \n* a(2) = Start = 2;\n* for n > 2, a(n) shares at least one prime factor with a(n-1) and is the ''smallest'' such natural number ''not already used''.\n\nThe sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).\n\nVariants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: \n* The sequence described above , starting 1, 2, ... the EKG(2) sequence;\n* the sequence starting 1, 3, ... the EKG(3) sequence; \n* ... the sequence starting 1, N, ... the EKG(N) sequence.\n\n\n;Convergence\nIf an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential '''state'''. Two EKG generators with differing starts can converge to produce the same sequence after initial differences.\nEKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)).\n\n\n;Task:\n# Calculate and show here the first 10 members of EKG(2).\n# Calculate and show here the first 10 members of EKG(5).\n# Calculate and show here the first 10 members of EKG(7).\n# Calculate and show here the first 10 members of EKG(9).\n# Calculate and show here the first 10 members of EKG(10).\n# Calculate and show here at which term EKG(5) and EKG(7) converge ('''stretch goal''').\n\n;Related Tasks:\n# [[Greatest common divisor]]\n# [[Sieve of Eratosthenes]]\n\n;Reference:\n* The EKG Sequence and the Tree of Numbers. (Video).\n\n", "solution": "from itertools import count, islice, takewhile\nfrom math import gcd\n\ndef EKG_gen(start=2):\n \"\"\"\\\n Generate the next term of the EKG together with the minimum cache of \n numbers left in its production; (the \"state\" of the generator).\n Using math.gcd\n \"\"\"\n c = count(start + 1)\n last, so_far = start, list(range(2, start))\n yield 1, []\n yield last, []\n while True:\n for index, sf in enumerate(so_far):\n if gcd(last, sf) > 1:\n last = so_far.pop(index)\n yield last, so_far[::]\n break\n else:\n so_far.append(next(c))\n\ndef find_convergence(ekgs=(5,7)):\n \"Returns the convergence point or zero if not found within the limit\"\n ekg = [EKG_gen(n) for n in ekgs]\n for e in ekg:\n next(e) # skip initial 1 in each sequence\n return 2 + len(list(takewhile(lambda state: not all(state[0] == s for s in state[1:]),\n zip(*ekg))))\n\nif __name__ == '__main__':\n for start in 2, 5, 7, 9, 10:\n print(f\"EKG({start}):\", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1])\n print(f\"\\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!\")"} {"title": "Earliest difference between prime gaps", "language": "Python from Julia, Wren", "task": "When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer.\n\n\n\n{|class=\"wikitable\"\n!gap!!minimalstartingprime!!endingprime\n|-\n|2||3||5\n|-\n|4||7||11\n|-\n|6||23||29\n|-\n|8||89||97\n|-\n|10||139||149\n|-\n|12||199||211\n|-\n|14||113||127\n|-\n|16||1831||1847\n|-\n|18||523||541\n|-\n|20||887||907\n|-\n|22||1129||1151\n|-\n|24||1669||1693\n|-\n|26||2477||2503\n|-\n|28||2971||2999\n|-\n|30||4297||4327\n|}\n\nThis task involves locating the minimal primes corresponding to those gaps.\n\nThough every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30:\n\n\nFor the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent.\n\n\n\n;Task\n\nFor each order of magnitude '''m''' from '''101''' through '''106''':\n\n* Find the first two sets of minimum adjacent prime gaps where the absolute value of the difference between the prime gap start values is greater than '''m'''.\n\n\n;E.G.\n\nFor an '''m''' of '''101'''; \n\nThe start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < '''101''' so keep going.\n\nThe start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > '''101''' so this the earliest adjacent gap difference > '''101'''.\n\n\n;Stretch goal\n\n* Do the same for '''107''' and '''108''' (and higher?) orders of magnitude\n\nNote: the earliest value found for each order of magnitude may not be unique, in fact, ''is'' not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.\n\n", "solution": "\"\"\" https://rosettacode.org/wiki/Earliest_difference_between_prime_gaps \"\"\"\n\nfrom primesieve import primes\n\nLIMIT = 10**9\npri = primes(LIMIT * 5)\ngapstarts = {}\nfor i in range(1, len(pri)):\n if pri[i] - pri[i - 1] not in gapstarts:\n gapstarts[pri[i] - pri[i - 1]] = pri[i - 1]\n\nPM, GAP1, = 10, 2\nwhile True:\n while GAP1 not in gapstarts:\n GAP1 += 2\n start1 = gapstarts[GAP1]\n GAP2 = GAP1 + 2\n if GAP2 not in gapstarts:\n GAP1 = GAP2 + 2\n continue\n start2 = gapstarts[GAP2]\n diff = abs(start2 - start1)\n if diff > PM:\n print(f\"Earliest difference >{PM: ,} between adjacent prime gap starting primes:\")\n print(f\"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\\n\")\n if PM == LIMIT:\n break\n PM *= 10\n else:\n GAP1 = GAP2\n"} {"title": "Eban numbers", "language": "Python", "task": "Definition:\nAn '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English.\n\nOr more literally, spelled numbers that contain the letter '''e''' are banned.\n\n\nThe American version of spelling numbers will be used here (as opposed to the British).\n\n'''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\nOnly numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task.\n\nThis will allow optimizations to be used.\n\n\n\n;Task:\n:::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count\n:::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count\n:::* show a count of all eban numbers up and including '''10,000'''\n:::* show a count of all eban numbers up and including '''100,000'''\n:::* show a count of all eban numbers up and including '''1,000,000'''\n:::* show a count of all eban numbers up and including '''10,000,000'''\n:::* show all output here.\n\n\n;See also:\n:* The MathWorld entry: eban numbers.\n:* The OEIS entry: A6933, eban numbers.\n:* [[Number names]].\n\n", "solution": "# Use inflect\n\n\"\"\"\n\n show all eban numbers <= 1,000 (in a horizontal format), and a count\n show all eban numbers between 1,000 and 4,000 (inclusive), and a count\n show a count of all eban numbers up and including 10,000\n show a count of all eban numbers up and including 100,000\n show a count of all eban numbers up and including 1,000,000\n show a count of all eban numbers up and including 10,000,000\n \n\"\"\"\n\nimport inflect\nimport time\n\nbefore = time.perf_counter()\n\np = inflect.engine()\n\n# eban numbers <= 1000\n\nprint(' ')\nprint('eban numbers up to and including 1000:')\nprint(' ')\n\ncount = 0\n\nfor i in range(1,1001):\n if not 'e' in p.number_to_words(i):\n print(str(i)+' ',end='')\n count += 1\n \nprint(' ')\nprint(' ')\nprint('count = '+str(count))\nprint(' ')\n\n# eban numbers 1000 to 4000\n\nprint(' ')\nprint('eban numbers between 1000 and 4000 (inclusive):')\nprint(' ')\n\ncount = 0\n\nfor i in range(1000,4001):\n if not 'e' in p.number_to_words(i):\n print(str(i)+' ',end='')\n count += 1\n \nprint(' ')\nprint(' ')\nprint('count = '+str(count))\nprint(' ')\n\n# eban numbers up to 10000\n\nprint(' ')\nprint('eban numbers up to and including 10000:')\nprint(' ')\n\ncount = 0\n\nfor i in range(1,10001):\n if not 'e' in p.number_to_words(i):\n count += 1\n \nprint(' ')\nprint('count = '+str(count))\nprint(' ')\n\n# eban numbers up to 100000\n\nprint(' ')\nprint('eban numbers up to and including 100000:')\nprint(' ')\n\ncount = 0\n\nfor i in range(1,100001):\n if not 'e' in p.number_to_words(i):\n count += 1\n \nprint(' ')\nprint('count = '+str(count))\nprint(' ')\n\n# eban numbers up to 1000000\n\nprint(' ')\nprint('eban numbers up to and including 1000000:')\nprint(' ')\n\ncount = 0\n\nfor i in range(1,1000001):\n if not 'e' in p.number_to_words(i):\n count += 1\n \nprint(' ')\nprint('count = '+str(count))\nprint(' ')\n\n# eban numbers up to 10000000\n\nprint(' ')\nprint('eban numbers up to and including 10000000:')\nprint(' ')\n\ncount = 0\n\nfor i in range(1,10000001):\n if not 'e' in p.number_to_words(i):\n count += 1\n \nprint(' ')\nprint('count = '+str(count))\nprint(' ')\n\nafter = time.perf_counter()\n\nprint(\" \")\nprint(\"Run time in seconds: \"+str(after - before))\n"} {"title": "Eertree", "language": "Python", "task": "An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. \n\nThe data structure has commonalities to both ''tries'' and ''suffix trees''.\n See links below. \n\n\n;Task:\nConstruct an eertree for the string \"eertree\", then output all sub-palindromes by traversing the tree.\n\n\n;See also:\n* Wikipedia entry: trie.\n* Wikipedia entry: suffix tree \n* Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.\n\n", "solution": "#!/bin/python\nfrom __future__ import print_function\n\nclass Node(object):\n\tdef __init__(self):\n\t\tself.edges = {} # edges (or forward links)\n\t\tself.link = None # suffix link (backward links)\n\t\tself.len = 0 # the length of the node\n\nclass Eertree(object):\n\tdef __init__(self):\n\t\tself.nodes = []\n\t\t# two initial root nodes\n\t\tself.rto = Node() #odd length root node, or node -1\n\t\tself.rte = Node() #even length root node, or node 0\n\n\t\t# Initialize empty tree\n\t\tself.rto.link = self.rte.link = self.rto;\n\t\tself.rto.len = -1\n\t\tself.rte.len = 0\n\t\tself.S = [0] # accumulated input string, T=S[1..i]\n\t\tself.maxSufT = self.rte # maximum suffix of tree T\n\n\tdef get_max_suffix_pal(self, startNode, a):\n\t\t# We traverse the suffix-palindromes of T in the order of decreasing length.\n\t\t# For each palindrome we read its length k and compare T[i-k] against a\n\t\t# until we get an equality or arrive at the -1 node.\n\t\tu = startNode\n\t\ti = len(self.S)\n\t\tk = u.len\n\t\twhile id(u) != id(self.rto) and self.S[i - k - 1] != a:\n\t\t\tassert id(u) != id(u.link) #Prevent infinte loop\n\t\t\tu = u.link\n\t\t\tk = u.len\n\n\t\treturn u\n\t\n\tdef add(self, a):\n\n\t\t# We need to find the maximum suffix-palindrome P of Ta\n\t\t# Start by finding maximum suffix-palindrome Q of T.\n\t\t# To do this, we traverse the suffix-palindromes of T\n\t\t# in the order of decreasing length, starting with maxSuf(T)\n\t\tQ = self.get_max_suffix_pal(self.maxSufT, a)\n\n\t\t# We check Q to see whether it has an outgoing edge labeled by a.\n\t\tcreateANewNode = not a in Q.edges\n\n\t\tif createANewNode:\n\t\t\t# We create the node P of length Q+2\n\t\t\tP = Node()\n\t\t\tself.nodes.append(P)\n\t\t\tP.len = Q.len + 2\n\t\t\tif P.len == 1:\n\t\t\t\t# if P = a, create the suffix link (P,0)\n\t\t\t\tP.link = self.rte\n\t\t\telse:\n\t\t\t\t# It remains to create the suffix link from P if |P|>1. Just\n\t\t\t\t# continue traversing suffix-palindromes of T starting with the suffix \n\t\t\t\t# link of Q.\n\t\t\t\tP.link = self.get_max_suffix_pal(Q.link, a).edges[a]\n\n\t\t\t# create the edge (Q,P)\n\t\t\tQ.edges[a] = P\n\n\t\t#P becomes the new maxSufT\n\t\tself.maxSufT = Q.edges[a]\n\n\t\t#Store accumulated input string\n\t\tself.S.append(a)\n\n\t\treturn createANewNode\n\t\n\tdef get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):\n\t\t#Each node represents a palindrome, which can be reconstructed\n\t\t#by the path from the root node to each non-root node.\n\n\t\t#Traverse all edges, since they represent other palindromes\n\t\tfor lnkName in nd.edges:\n\t\t\tnd2 = nd.edges[lnkName] #The lnkName is the character used for this edge\n\t\t\tself.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)\n\n\t\t#Reconstruct based on charsToHere characters.\n\t\tif id(nd) != id(self.rto) and id(nd) != id(self.rte): #Don't print for root nodes\n\t\t\ttmp = \"\".join(charsToHere)\n\t\t\tif id(nodesToHere[0]) == id(self.rte): #Even string\n\t\t\t\tassembled = tmp[::-1] + tmp\n\t\t\telse: #Odd string\n\t\t\t\tassembled = tmp[::-1] + tmp[1:]\n\t\t\tresult.append(assembled)\n\nif __name__==\"__main__\":\n\tst = \"eertree\"\n\tprint (\"Processing string\", st)\n\teertree = Eertree()\n\tfor ch in st:\n\t\teertree.add(ch)\n\n\tprint (\"Number of sub-palindromes:\", len(eertree.nodes))\n\n\t#Traverse tree to find sub-palindromes\n\tresult = []\n\teertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) #Odd length words\n\teertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) #Even length words\n\tprint (\"Sub-palindromes:\", result)"} {"title": "Egyptian division", "language": "Python", "task": "Egyptian division is a method of dividing integers using addition and \ndoubling that is similar to the algorithm of [[Ethiopian multiplication]]\n\n'''Algorithm:'''\n\nGiven two numbers where the '''dividend''' is to be divided by the '''divisor''':\n\n# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.\n# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.\n# Continue with successive i'th rows of 2^i and 2^i * divisor.\n# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.\n# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''\n# Consider each row of the table, in the ''reverse'' order of its construction.\n# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.\n# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).\n\n\n'''Example: 580 / 34'''\n\n''' Table creation: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n|-\n| 1\n| 34\n|-\n| 2\n| 68\n|-\n| 4\n| 136\n|-\n| 8\n| 272\n|-\n| 16\n| 544\n|}\n\n''' Initialization of sums: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| 16\n| 544\n|\n\n|\n\n|-\n|\n|\n| 0\n| 0\n|}\n\n''' Considering table rows, bottom-up: '''\n\nWhen a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n| 16\n| 544\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n| 16\n| 544\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n| 16\n| 544\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n| 16\n| 544\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| '''1'''\n| '''34'''\n| 17\n| 578\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n;Answer:\nSo 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.\n\n\n;Task:\nThe task is to create a function that does Egyptian division. The function should\nclosely follow the description above in using a list/array of powers of two, and\nanother of doublings.\n\n* Functions should be clear interpretations of the algorithm.\n* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.\n\n\n;Related tasks:\n:* Egyptian fractions\n\n\n;References:\n:* Egyptian Number System\n\n", "solution": "from itertools import product\n\ndef egyptian_divmod(dividend, divisor):\n assert divisor != 0\n pwrs, dbls = [1], [divisor]\n while dbls[-1] <= dividend:\n pwrs.append(pwrs[-1] * 2)\n dbls.append(pwrs[-1] * divisor)\n ans, accum = 0, 0\n for pwr, dbl in zip(pwrs[-2::-1], dbls[-2::-1]):\n if accum + dbl <= dividend:\n accum += dbl\n ans += pwr\n return ans, abs(accum - dividend)\n\nif __name__ == \"__main__\":\n # Test it gives the same results as the divmod built-in\n for i, j in product(range(13), range(1, 13)):\n assert egyptian_divmod(i, j) == divmod(i, j)\n # Mandated result\n i, j = 580, 34\n print(f'{i} divided by {j} using the Egyption method is %i remainder %i'\n % egyptian_divmod(i, j))"} {"title": "Egyptian division", "language": "Python from Haskell", "task": "Egyptian division is a method of dividing integers using addition and \ndoubling that is similar to the algorithm of [[Ethiopian multiplication]]\n\n'''Algorithm:'''\n\nGiven two numbers where the '''dividend''' is to be divided by the '''divisor''':\n\n# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.\n# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.\n# Continue with successive i'th rows of 2^i and 2^i * divisor.\n# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.\n# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''\n# Consider each row of the table, in the ''reverse'' order of its construction.\n# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.\n# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).\n\n\n'''Example: 580 / 34'''\n\n''' Table creation: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n|-\n| 1\n| 34\n|-\n| 2\n| 68\n|-\n| 4\n| 136\n|-\n| 8\n| 272\n|-\n| 16\n| 544\n|}\n\n''' Initialization of sums: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| 16\n| 544\n|\n\n|\n\n|-\n|\n|\n| 0\n| 0\n|}\n\n''' Considering table rows, bottom-up: '''\n\nWhen a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n| 16\n| 544\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n| 16\n| 544\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n| 16\n| 544\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n| 16\n| 544\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| '''1'''\n| '''34'''\n| 17\n| 578\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n;Answer:\nSo 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.\n\n\n;Task:\nThe task is to create a function that does Egyptian division. The function should\nclosely follow the description above in using a list/array of powers of two, and\nanother of doublings.\n\n* Functions should be clear interpretations of the algorithm.\n* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.\n\n\n;Related tasks:\n:* Egyptian fractions\n\n\n;References:\n:* Egyptian Number System\n\n", "solution": "'''Quotient and remainder of division by the Rhind papyrus method.'''\n\nfrom functools import reduce\n\n\n# eqyptianQuotRem :: Int -> Int -> (Int, Int)\ndef eqyptianQuotRem(m):\n '''Quotient and remainder derived by the Eqyptian method.'''\n\n def expansion(xi):\n '''Doubled value, and next power of two - both by self addition.'''\n x, i = xi\n return Nothing() if x > m else Just(\n ((x + x, i + i), xi)\n )\n\n def collapse(qr, ix):\n '''Addition of a power of two to the quotient,\n and subtraction of a paired value from the remainder.'''\n i, x = ix\n q, r = qr\n return (q + i, r - x) if x < r else qr\n\n return lambda n: reduce(\n collapse,\n unfoldl(expansion)(\n (1, n)\n ),\n (0, m)\n )\n\n\n# ------------------------- TEST --------------------------\n# main :: IO ()\ndef main():\n '''Test'''\n print(\n eqyptianQuotRem(580)(34)\n )\n\n\n# ------------------- GENERIC FUNCTIONS -------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.'''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.'''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# unfoldl(lambda x: Just(((x - 1), x)) if 0 != x else Nothing())(10)\n# -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n# unfoldl :: (b -> Maybe (b, a)) -> b -> [a]\ndef unfoldl(f):\n '''Dual to reduce or foldl.\n Where these reduce a list to a summary value, unfoldl\n builds a list from a seed value.\n Where f returns Just(a, b), a is appended to the list,\n and the residual b is used as the argument for the next\n application of f.\n When f returns Nothing, the completed list is returned.\n '''\n def go(v):\n x, r = v, v\n xs = []\n while True:\n mb = f(x)\n if mb.get('Nothing'):\n return xs\n else:\n x, r = mb.get('Just')\n xs.insert(0, r)\n return xs\n return go\n\n\n# MAIN ----------------------------------------------------\nif __name__ == '__main__':\n main()"} {"title": "Elementary cellular automaton", "language": "Python", "task": "An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.\n\nThe rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.\n\n\n;Task:\nCreate a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.\n\nThe space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.\n\nThis task is basically a generalization of [[one-dimensional cellular automata]].\n\n\n;See also\n* Cellular automata (natureofcode.com)\n\n", "solution": "def eca(cells, rule):\n lencells = len(cells)\n c = \"0\" + cells + \"0\" # Zero pad the ends\n rulebits = '{0:08b}'.format(rule)\n neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}\n yield c[1:-1]\n while True:\n c = ''.join(['0',\n ''.join(neighbours2next[c[i-1:i+2]]\n for i in range(1,lencells+1)),\n '0'])\n yield c[1:-1]\n\nif __name__ == '__main__':\n lines, start, rules = 50, '0000000001000000000', (90, 30, 122)\n zipped = [range(lines)] + [eca(start, rule) for rule in rules]\n print('\\n Rules: %r' % (rules,))\n for data in zip(*zipped):\n i = data[0]\n cells = data[1:]\n print('%2i: %s' % (i, ' '.join(cells).replace('0', '.').replace('1', '#')))"} {"title": "Elementary cellular automaton/Infinite length", "language": "Python", "task": "The purpose of this task is to create a version of an [[Elementary cellular automaton]] whose number of cells is only limited by the memory size of the computer.\n\nTo be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells.\n\nExamples:\n\n\n1 -> ..., 0, 0, 1, 0, 0, ...\n0, 1 -> ..., 1, 1, 0, 1, 0, 0, ...\n1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ...\n\n\nMore complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.\n\n", "solution": "def _notcell(c):\n return '0' if c == '1' else '1'\n\ndef eca_infinite(cells, rule):\n lencells = len(cells)\n rulebits = '{0:08b}'.format(rule)\n neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}\n c = cells\n while True:\n yield c\n c = _notcell(c[0])*2 + c + _notcell(c[-1])*2 # Extend and pad the ends\n\n c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1))\n #yield c[1:-1]\n\nif __name__ == '__main__':\n lines = 25\n for rule in (90, 30):\n print('\\nRule: %i' % rule)\n for i, c in zip(range(lines), eca_infinite('1', rule)):\n print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '#')))"} {"title": "Elementary cellular automaton/Random number generator", "language": "Python", "task": "Mathematica software for its default random number generator.\n\nSteven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.\n\nThe purpose of this task is to demonstrate this. With the code written in the most significant.\n\nYou can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.\n\nFor extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.\n\n;Reference:\n* Cellular automata: Is Rule 30 random? (PDF).\n\n\n", "solution": "from elementary_cellular_automaton import eca, eca_wrap\n\ndef rule30bytes(lencells=100):\n cells = '1' + '0' * (lencells - 1)\n gen = eca(cells, 30)\n while True:\n yield int(''.join(next(gen)[0] for i in range(8)), 2)\n\nif __name__ == '__main__':\n print([b for i,b in zip(range(10), rule30bytes())])"} {"title": "Elliptic curve arithmetic", "language": "Python from C", "task": "digital signatures. \n\nThe purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol. \n\nIn a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve:\n\n:::: y^2 = x^3 + a x + b\n\n'''a''' and '''b''' are arbitrary parameters that define the specific curve which is used. \n\nFor this particular task, we'll use the following parameters:\n\n:::: a=0, b=7 \n\nThe most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it. \n\nTo do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:\n\n:::: P + Q + R = 0 \n\nHere '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry. \n\nWe'll also assume here that this infinity point is unique and defines the neutral element of the addition.\n\nThis was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:\n\nGiven any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned.\n\nConsidering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).\n\n'''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis.\n\nThe task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. \n\nYou will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven.\n\n''Hint'': You might need to define a \"doubling\" function, that returns '''P+P''' for any given point '''P'''.\n\n''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a \"multiply\" function that returns, \nfor any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).\n\n", "solution": "#!/usr/bin/env python3\n\nclass Point:\n b = 7\n def __init__(self, x=float('inf'), y=float('inf')):\n self.x = x\n self.y = y\n\n def copy(self):\n return Point(self.x, self.y)\n\n def is_zero(self):\n return self.x > 1e20 or self.x < -1e20\n\n def neg(self):\n return Point(self.x, -self.y)\n\n def dbl(self):\n if self.is_zero():\n return self.copy()\n try:\n L = (3 * self.x * self.x) / (2 * self.y)\n except ZeroDivisionError:\n return Point()\n x = L * L - 2 * self.x\n return Point(x, L * (self.x - x) - self.y)\n\n def add(self, q):\n if self.x == q.x and self.y == q.y:\n return self.dbl()\n if self.is_zero():\n return q.copy()\n if q.is_zero():\n return self.copy()\n try:\n L = (q.y - self.y) / (q.x - self.x)\n except ZeroDivisionError:\n return Point()\n x = L * L - self.x - q.x\n return Point(x, L * (self.x - x) - self.y)\n\n def mul(self, n):\n p = self.copy()\n r = Point()\n i = 1\n while i <= n:\n if i&n:\n r = r.add(p)\n p = p.dbl()\n i <<= 1\n return r\n\n def __str__(self):\n return \"({:.3f}, {:.3f})\".format(self.x, self.y)\n\ndef show(s, p):\n print(s, \"Zero\" if p.is_zero() else p)\n\ndef from_y(y):\n n = y * y - Point.b\n x = n**(1./3) if n>=0 else -((-n)**(1./3))\n return Point(x, y)\n\n# demonstrate\na = from_y(1)\nb = from_y(2)\nshow(\"a =\", a)\nshow(\"b =\", b)\nc = a.add(b)\nshow(\"c = a + b =\", c)\nd = c.neg()\nshow(\"d = -c =\", d)\nshow(\"c + d =\", c.add(d))\nshow(\"a + b + d =\", a.add(b.add(d)))\nshow(\"a * 12345 =\", a.mul(12345))"} {"title": "Empty directory", "language": "Python 2.x", "task": "Starting with a path to some directory, determine whether the directory is empty.\n\nAn empty directory contains no files nor subdirectories. \nWith [[Unix]] or [[Windows]] systems, every directory contains an entry for \".\" and almost every directory contains \"..\" (except for a root directory); an empty directory contains no other entries.\n\n", "solution": "import os;\nif os.listdir(raw_input(\"directory\")):\n print \"not empty\"\nelse:\n print \"empty\"\n"} {"title": "Empty string", "language": "Python", "task": "Languages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* Demonstrate how to assign an empty string to a variable.\n::* Demonstrate how to check that a string is empty.\n::* Demonstrate how to check that a string is not empty.\n\n\n\n", "solution": "s = ''\n# or:\ns = str()\n\nif not s or s == '':\n print(\"String is empty\")\n\nif len(s) == 0:\n print(\"String is empty\")\nelse:\n print(\"String not empty\")\n\n\n# boolean test function for python2 and python3\n# test for regular (non-unicode) strings\n# unicode strings\n# None \ndef emptystring(s):\n if isinstance(s, (''.__class__ , u''.__class__) ):\n if len(s) == 0: \n return True\n else \n return False\n\n elif s is None:\n return True\n"} {"title": "Entropy/Narcissist", "language": "Python 3.4", "task": "Write a computer program that computes and shows its own [[entropy]].\n\n\n;Related Tasks: \n:* [[Fibonacci_word]]\n:* [[Entropy]]\n\n", "solution": "import math\nfrom collections import Counter\n\ndef entropy(s):\n p, lns = Counter(s), float(len(s))\n return -sum( count/lns * math.log(count/lns, 2) for count in p.values())\n\nwith open(__file__) as f:\n b=f.read()\n \nprint(entropy(b))"} {"title": "Equilibrium index", "language": "Python", "task": "An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. \n\n\nFor example, in a sequence A:\n\n::::: A_0 = -7\n::::: A_1 = 1\n::::: A_2 = 5\n::::: A_3 = 2\n::::: A_4 = -4\n::::: A_5 = 3\n::::: A_6 = 0\n\n3 is an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6\n\n6 is also an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0\n\n(sum of zero elements is zero) \n\n7 is not an equilibrium index, because it is not a valid index of sequence A.\n\n\n;Task;\nWrite a function that, given a sequence, returns its equilibrium indices (if any).\n\nAssume that the sequence may be very long.\n\n", "solution": "f = (eqindex2Pass, eqindexMultiPass, eqindex1Pass)\nd = ([-7, 1, 5, 2, -4, 3, 0],\n [2, 4, 6],\n [2, 9, 2],\n [1, -1, 1, -1, 1, -1, 1])\n\nfor data in d:\n print(\"d = %r\" % data)\n for func in f:\n print(\" %16s(d) -> %r\" % (func.__name__, list(func(data))))"} {"title": "Esthetic numbers", "language": "Python 3.9.5", "task": "An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.\n\n\n;E.G.\n\n:* '''12''' is an esthetic number. One and two differ by 1.\n\n:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.\n\n:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.\n\n\nThese examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.\n\nEsthetic numbers are also sometimes referred to as stepping numbers.\n\n\n;Task\n\n:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.\n\n:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)\n\n:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.\n\n:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.\n\n\n;Related task:\n* numbers with equal rises and falls\n\n\n;See also:\n:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1\n:;*Numbers Aplenty - Esthetic numbers\n:;*Geeks for Geeks - Stepping numbers\n\n", "solution": "from collections import deque\nfrom itertools import dropwhile, islice, takewhile\nfrom textwrap import wrap\nfrom typing import Iterable, Iterator\n\n\nDigits = str # Alias for the return type of to_digits()\n\n\ndef esthetic_nums(base: int) -> Iterator[int]:\n \"\"\"Generate the esthetic number sequence for a given base\n\n >>> list(islice(esthetic_nums(base=10), 20))\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65]\n \"\"\"\n queue: deque[tuple[int, int]] = deque()\n queue.extendleft((d, d) for d in range(1, base))\n while True:\n num, lsd = queue.pop()\n yield num\n new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)\n num *= base # Shift num left one digit\n queue.extendleft((num + d, d) for d in new_lsds)\n\n\ndef to_digits(num: int, base: int) -> Digits:\n \"\"\"Return a representation of an integer as digits in a given base\n\n >>> to_digits(0x3def84f0ce, base=16)\n '3def84f0ce'\n \"\"\"\n digits: list[str] = []\n while num:\n num, d = divmod(num, base)\n digits.append(\"0123456789abcdef\"[d])\n return \"\".join(reversed(digits)) if digits else \"0\"\n\n\ndef pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:\n \"\"\"Pretty print an iterable which returns strings\n\n >>> pprint_it(map(str, range(20)), indent=0, width=40)\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,\n 12, 13, 14, 15, 16, 17, 18, 19\n \n \"\"\"\n joined = \", \".join(it)\n lines = wrap(joined, width=width - indent)\n for line in lines:\n print(f\"{indent*' '}{line}\")\n print()\n\n\ndef task_2() -> None:\n nums: Iterator[int]\n for base in range(2, 16 + 1):\n start, stop = 4 * base, 6 * base\n nums = esthetic_nums(base)\n nums = islice(nums, start - 1, stop) # start and stop are 1-based indices\n print(\n f\"Base-{base} esthetic numbers from \"\n f\"index {start} through index {stop} inclusive:\\n\"\n )\n pprint_it(to_digits(num, base) for num in nums)\n\n\ndef task_3(lower: int, upper: int, base: int = 10) -> None:\n nums: Iterator[int] = esthetic_nums(base)\n nums = dropwhile(lambda num: num < lower, nums)\n nums = takewhile(lambda num: num <= upper, nums)\n print(\n f\"Base-{base} esthetic numbers with \"\n f\"magnitude between {lower:,} and {upper:,}:\\n\"\n )\n pprint_it(to_digits(num, base) for num in nums)\n\n\nif __name__ == \"__main__\":\n print(\"======\\nTask 2\\n======\\n\")\n task_2()\n\n print(\"======\\nTask 3\\n======\\n\")\n task_3(1_000, 9_999)\n\n print(\"======\\nTask 4\\n======\\n\")\n task_3(100_000_000, 130_000_000)\n\n"} {"title": "Esthetic numbers", "language": "Python from Haskell", "task": "An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.\n\n\n;E.G.\n\n:* '''12''' is an esthetic number. One and two differ by 1.\n\n:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.\n\n:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.\n\n\nThese examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.\n\nEsthetic numbers are also sometimes referred to as stepping numbers.\n\n\n;Task\n\n:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.\n\n:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)\n\n:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.\n\n:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.\n\n\n;Related task:\n* numbers with equal rises and falls\n\n\n;See also:\n:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1\n:;*Numbers Aplenty - Esthetic numbers\n:;*Geeks for Geeks - Stepping numbers\n\n", "solution": "'''Esthetic numbers'''\n\nfrom functools import reduce\nfrom itertools import (\n accumulate, chain, count, dropwhile,\n islice, product, takewhile\n)\nfrom operator import add\nfrom string import digits, ascii_lowercase\nfrom textwrap import wrap\n\n\n# estheticNumbersInBase :: Int -> [Int]\ndef estheticNumbersInBase(b):\n '''Infinite stream of numbers which are\n esthetic in a given base.\n '''\n return concatMap(\n compose(\n lambda deltas: concatMap(\n lambda headDigit: concatMap(\n compose(\n fromBaseDigits(b),\n scanl(add)(headDigit)\n )\n )(deltas)\n )(range(1, b)),\n replicateList([-1, 1])\n )\n )(count(0))\n\n\n# ------------------------ TESTS -------------------------\ndef main():\n '''Specified tests'''\n def samples(b):\n i, j = b * 4, b * 6\n return '\\n'.join([\n f'Esthetics [{i}..{j}] for base {b}:',\n unlines(wrap(\n unwords([\n showInBase(b)(n) for n in compose(\n drop(i - 1), take(j)\n )(\n estheticNumbersInBase(b)\n )\n ]), 60\n ))\n ])\n\n def takeInRange(a, b):\n return compose(\n dropWhile(lambda x: x < a),\n takeWhile(lambda x: x <= b)\n )\n\n print(\n '\\n\\n'.join([\n samples(b) for b in range(2, 1 + 16)\n ])\n )\n for (lo, hi) in [(1000, 9999), (100_000_000, 130_000_000)]:\n print(f'\\nBase 10 Esthetics in range [{lo}..{hi}]:')\n print(\n unlines(wrap(\n unwords(\n str(x) for x in takeInRange(lo, hi)(\n estheticNumbersInBase(10)\n )\n ), 60\n ))\n )\n\n\n# ------------------- BASES AND DIGITS -------------------\n\n# fromBaseDigits :: Int -> [Int] -> [Int]\ndef fromBaseDigits(b):\n '''An empty list if any digits are out of range for\n the base. Otherwise a list containing an integer.\n '''\n def go(digitList):\n maybeNum = reduce(\n lambda r, d: None if r is None or (\n 0 > d or d >= b\n ) else r * b + d,\n digitList, 0\n )\n return [] if None is maybeNum else [maybeNum]\n return go\n\n\n# toBaseDigits :: Int -> Int -> [Int]\ndef toBaseDigits(b):\n '''A list of the digits of n in base b.\n '''\n def f(x):\n return None if 0 == x else (\n divmod(x, b)[::-1]\n )\n return lambda n: list(reversed(unfoldr(f)(n)))\n\n\n# showInBase :: Int -> Int -> String\ndef showInBase(b):\n '''String representation of n in base b.\n '''\n charSet = digits + ascii_lowercase\n return lambda n: ''.join([\n charSet[i] for i in toBaseDigits(b)(n)\n ])\n\n\n# ----------------------- GENERIC ------------------------\n\n# compose :: ((a -> a), ...) -> (a -> a)\ndef compose(*fs):\n '''Composition, from right to left,\n of a series of functions.\n '''\n def go(f, g):\n def fg(x):\n return f(g(x))\n return fg\n return reduce(go, fs, lambda x: x)\n\n\n# concatMap :: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n '''A concatenated list over which a function has been\n mapped.\n The list monad can be derived by using a function f\n which wraps its output in a list, (using an empty\n list to represent computational failure).\n '''\n def go(xs):\n return chain.from_iterable(map(f, xs))\n return go\n\n\n# drop :: Int -> [a] -> [a]\n# drop :: Int -> String -> String\ndef drop(n):\n '''The sublist of xs beginning at\n (zero-based) index n.\n '''\n def go(xs):\n if isinstance(xs, (list, tuple, str)):\n return xs[n:]\n else:\n take(n)(xs)\n return xs\n return go\n\n\n# dropWhile :: (a -> Bool) -> [a] -> [a]\n# dropWhile :: (Char -> Bool) -> String -> String\ndef dropWhile(p):\n '''The suffix remainining after takeWhile p xs.\n '''\n return lambda xs: list(\n dropwhile(p, xs)\n )\n\n\n# replicateList :: [a] -> Int -> [[a]]\ndef replicateList(xs):\n '''All distinct lists of length n that\n consist of elements drawn from xs.\n '''\n def rep(n):\n def go(x):\n return [[]] if 1 > x else [\n ([a] + b) for (a, b) in product(\n xs, go(x - 1)\n )\n ]\n return go(n)\n return rep\n\n\n# scanl :: (b -> a -> b) -> b -> [a] -> [b]\ndef scanl(f):\n '''scanl is like reduce, but defines a succession of\n intermediate values, building from the left.\n '''\n def go(a):\n def g(xs):\n return accumulate(chain([a], xs), f)\n return g\n return go\n\n\n# take :: Int -> [a] -> [a]\n# take :: Int -> String -> String\ndef take(n):\n '''The prefix of xs of length n,\n or xs itself if n > length xs.\n '''\n def go(xs):\n return list(islice(xs, n))\n return go\n\n\n# takeWhile :: (a -> Bool) -> [a] -> [a]\n# takeWhile :: (Char -> Bool) -> String -> String\ndef takeWhile(p):\n '''The longest (possibly empty) prefix of xs\n in which all elements satisfy p.\n '''\n return lambda xs: list(\n takewhile(p, xs)\n )\n\n\n# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]\ndef unfoldr(f):\n '''Dual to reduce or foldr.\n Where catamorphism reduces a list to a summary value,\n the anamorphic unfoldr builds a list from a seed value.\n As long as f returns (a, b) a is prepended to the list,\n and the residual b is used as the argument for the next\n application of f.\n When f returns None, the completed list is returned.\n '''\n def go(v):\n xr = v, v\n xs = []\n while True:\n xr = f(xr[1])\n if None is not xr:\n xs.append(xr[0])\n else:\n return xs\n return go\n\n\n# unlines :: [String] -> String\ndef unlines(xs):\n '''A single string formed by the intercalation\n of a list of strings with the newline character.\n '''\n return '\\n'.join(xs)\n\n\n# unwords :: [String] -> String\ndef unwords(xs):\n '''A space-separated string derived\n from a list of words.\n '''\n return ' '.join(xs)\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Euclid-Mullin sequence", "language": "Python", "task": "Definition\nThe Euclid-Mullin sequence is an infinite sequence of distinct prime numbers, in which each element is the least prime factor of one plus the product of all earlier elements. \n\nThe first element is usually assumed to be 2. So the second element is : (2) + 1 = 3 and the third element is : (2 x 3) + 1 = 7 as this is prime.\n\nAlthough intermingled with smaller elements, the sequence can produce very large elements quite quickly and only the first 51 have been computed at the time of writing.\n\n;Task\nCompute and show here the first '''16''' elements of the sequence or, if your language does not support arbitrary precision arithmetic, as many as you can.\n\n;Stretch goal\nCompute the next '''11''' elements of the sequence.\n\n;Reference\nOEIS sequence A000945\n\n", "solution": "\"\"\" Rosetta code task: Euclid-Mullin_sequence \"\"\"\n\nfrom primePy import primes\n\ndef euclid_mullin():\n \"\"\" generate Euclid-Mullin sequence \"\"\"\n total = 1\n while True:\n next_iter = primes.factor(total + 1)\n total *= next_iter\n yield next_iter\n\nGEN = euclid_mullin()\nprint('First 16 Euclid-Mullin numbers:', ', '.join(str(next(GEN)) for _ in range(16)))\n"} {"title": "Euler's identity", "language": "Python", "task": "{{Wikipedia|Euler's_identity}}\n\n\nIn mathematics, ''Euler's identity'' is the equality:\n\n ei\\pi + 1 = 0\n\nwhere\n\n e is Euler's number, the base of natural logarithms,\n ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and\n \\pi is pi, the ratio of the circumference of a circle to its diameter.\n\nEuler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:\n\n The number 0.\n The number 1.\n The number \\pi (\\pi = 3.14159+),\n The number e (e = 2.71828+), which occurs widely in mathematical analysis.\n The number ''i'', the imaginary unit of the complex numbers.\n\n;Task\nShow in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. \n\nMost languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. \n\nIf that is the case, or there is some other limitation, show \nthat ei\\pi + 1 is ''approximately'' equal to zero and \nshow the amount of error in the calculation.\n\nIf your language is capable of symbolic calculations, show \nthat ei\\pi + 1 is ''exactly'' equal to zero for bonus kudos points.\n\n", "solution": ">>> import math\n>>> math.e ** (math.pi * 1j) + 1\n1.2246467991473532e-16j"} {"title": "Euler's sum of powers conjecture", "language": "Python", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "def eulers_sum_of_powers():\n max_n = 250\n pow_5 = [n**5 for n in range(max_n)]\n pow5_to_n = {n**5: n for n in range(max_n)}\n for x0 in range(1, max_n):\n for x1 in range(1, x0):\n for x2 in range(1, x1):\n for x3 in range(1, x2):\n pow_5_sum = sum(pow_5[i] for i in (x0, x1, x2, x3))\n if pow_5_sum in pow5_to_n:\n y = pow5_to_n[pow_5_sum]\n return (x0, x1, x2, x3, y)\n\nprint(\"%i**5 + %i**5 + %i**5 + %i**5 == %i**5\" % eulers_sum_of_powers())"} {"title": "Euler's sum of powers conjecture", "language": "Python 2.6+", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "from itertools import combinations\n\ndef eulers_sum_of_powers():\n max_n = 250\n pow_5 = [n**5 for n in range(max_n)]\n pow5_to_n = {n**5: n for n in range(max_n)}\n for x0, x1, x2, x3 in combinations(range(1, max_n), 4):\n pow_5_sum = sum(pow_5[i] for i in (x0, x1, x2, x3))\n if pow_5_sum in pow5_to_n:\n y = pow5_to_n[pow_5_sum]\n return (x0, x1, x2, x3, y)\n\nprint(\"%i**5 + %i**5 + %i**5 + %i**5 == %i**5\" % eulers_sum_of_powers())"} {"title": "Euler's sum of powers conjecture", "language": "Python 3.7", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "'''Euler's sum of powers conjecture'''\n\nfrom itertools import (chain, takewhile)\n\n\n# main :: IO ()\ndef main():\n '''Search for counter-example'''\n\n xs = enumFromTo(1)(249)\n\n powerMap = {x**5: x for x in xs}\n sumMap = {\n x**5 + y**5: (x, y)\n for x in xs[1:]\n for y in xs if x > y\n }\n\n # isExample :: (Int, Int) -> Bool\n def isExample(ps):\n p, s = ps\n return p - s in sumMap\n\n # display :: (Int, Int) -> String\n def display(ps):\n p, s = ps\n a, b = sumMap[p - s]\n c, d = sumMap[s]\n return '^5 + '.join([str(n) for n in [a, b, c, d]]) + (\n '^5 = ' + str(powerMap[p]) + '^5'\n )\n\n print(__doc__ + ' \u2013 counter-example:\\n')\n print(\n maybe('No counter-example found.')(display)(\n find(isExample)(\n bind(powerMap.keys())(\n lambda p: bind(\n takewhile(\n lambda x: p > x,\n sumMap.keys()\n )\n )(lambda s: [(p, s)])\n )\n )\n )\n )\n\n\n# ----------------------- GENERIC ------------------------\n\n# Just :: a -> Maybe a\ndef Just(x):\n '''Constructor for an inhabited Maybe (option type) value.\n Wrapper containing the result of a computation.\n '''\n return {'type': 'Maybe', 'Nothing': False, 'Just': x}\n\n\n# Nothing :: () -> Maybe a\ndef Nothing():\n '''Constructor for an empty Maybe (option type) value.\n Empty wrapper returned where a computation is not possible.\n '''\n return {'type': 'Maybe', 'Nothing': True}\n\n\n# bind (>>=) :: [a] -> (a -> [b]) -> [b]\ndef bind(xs):\n '''List monad injection operator.\n Two computations sequentially composed,\n with any value produced by the first\n passed as an argument to the second.\n '''\n def go(f):\n return chain.from_iterable(map(f, xs))\n return go\n\n\n# enumFromTo :: (Int, Int) -> [Int]\ndef enumFromTo(m):\n '''Integer enumeration from m to n.'''\n return lambda n: range(m, 1 + n)\n\n\n# find :: (a -> Bool) -> [a] -> Maybe a\ndef find(p):\n '''Just the first element in the list that matches p,\n or Nothing if no elements match.\n '''\n def go(xs):\n try:\n return Just(next(x for x in xs if p(x)))\n except StopIteration:\n return Nothing()\n return go\n\n\n# maybe :: b -> (a -> b) -> Maybe a -> b\ndef maybe(v):\n '''Either the default value v, if m is Nothing,\n or the application of f to x,\n where m is Just(x).\n '''\n return lambda f: lambda m: v if (\n None is m or m.get('Nothing')\n ) else f(m.get('Just'))\n\n\n# MAIN ---\nif __name__ == '__main__':\n main()"} {"title": "Even or odd", "language": "Python", "task": "Test whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.\n* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.\n* Use modular congruences:\n** ''i'' 0 (mod 2) iff ''i'' is even.\n** ''i'' 1 (mod 2) iff ''i'' is odd.\n\n", "solution": ">>> def is_odd(i): return bool(i & 1)\n\n>>> def is_even(i): return not is_odd(i)\n\n>>> [(j, is_odd(j)) for j in range(10)]\n[(0, False), (1, True), (2, False), (3, True), (4, False), (5, True), (6, False), (7, True), (8, False), (9, True)]\n>>> [(j, is_even(j)) for j in range(10)]\n[(0, True), (1, False), (2, True), (3, False), (4, True), (5, False), (6, True), (7, False), (8, True), (9, False)]\n>>> "} {"title": "Evolutionary algorithm", "language": "Python", "task": "Starting with:\n* The target string: \"METHINKS IT IS LIKE A WEASEL\".\n* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).\n* A fitness function that computes the 'closeness' of its argument to the target string.\n* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.\n:* repeat until the parent converges, (hopefully), to the target.\n\n\n;See also:\n* Wikipedia entry: Weasel algorithm.\n* Wikipedia entry: Evolutionary algorithm.\n\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n\nNote that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n (:* repeat until the parent converges, (hopefully), to the target.\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n Create a new string based on the TOS, '''changing randomly any characters which\n don't already match the target''':\n\n''NOTE:'' this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.\n\n", "solution": "from string import letters\nfrom random import choice, random\n \ntarget = list(\"METHINKS IT IS LIKE A WEASEL\")\ncharset = letters + ' '\nparent = [choice(charset) for _ in range(len(target))]\nminmutaterate = .09\nC = range(100)\n \nperfectfitness = float(len(target))\n \ndef fitness(trial):\n 'Sum of matching chars by position'\n return sum(t==h for t,h in zip(trial, target))\n \ndef mutaterate():\n 'Less mutation the closer the fit of the parent'\n return 1-((perfectfitness - fitness(parent)) / perfectfitness * (1 - minmutaterate))\n \ndef mutate(parent, rate):\n return [(ch if random() <= rate else choice(charset)) for ch in parent]\n \ndef que():\n '(from the favourite saying of Manuel in Fawlty Towers)'\n print (\"#%-4i, fitness: %4.1f%%, '%s'\" %\n (iterations, fitness(parent)*100./perfectfitness, ''.join(parent)))\n\ndef mate(a, b):\n place = 0\n if choice(xrange(10)) < 7:\n place = choice(xrange(len(target)))\n else:\n return a, b\n \n return a, b, a[:place] + b[place:], b[:place] + a[place:]\n\niterations = 0\ncenter = len(C)/2\nwhile parent != target:\n rate = mutaterate()\n iterations += 1\n if iterations % 100 == 0: que()\n copies = [ mutate(parent, rate) for _ in C ] + [parent]\n parent1 = max(copies[:center], key=fitness)\n parent2 = max(copies[center:], key=fitness)\n parent = max(mate(parent1, parent2), key=fitness)\nque()"} {"title": "Executable library", "language": "Python", "task": "The general idea behind an executable library is to create a library \nthat when used as a library does one thing; \nbut has the ability to be run directly via command line. \nThus the API comes with a CLI in the very same source code file.\n\n'''Task detail'''\n\n* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number.\n\n* The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task:\n:: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n:: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.\n\n* Create a second executable to calculate the following:\n** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000.\n\n* Explain any extra setup/run steps needed to complete the task.\n\n'''Notes:''' \n* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment.\n* Interpreters are present in the runtime environment.\n\n", "solution": "from collections import Counter\n\ndef function_length_frequency(func, hrange):\n return Counter(len(func(n)) for n in hrange).most_common()\n\nif __name__ == '__main__':\n from executable_hailstone_library import hailstone\n\n upto = 100000\n hlen, freq = function_length_frequency(hailstone, range(1, upto))[0]\n print(\"The length of hailstone sequence that is most common for\\n\"\n \"hailstone(n) where 1<=n<%i, is %i. It occurs %i times.\"\n % (upto, hlen, freq))"} {"title": "Execute Computer/Zero", "language": "Python", "task": "Computer/zero Assembly}}\n\n;Task:\nCreate a [[Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs \"2+2\" and \"7*8\" found there.\n\n:* The virtual machine \"bytecode\" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.\n:* For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it.\n\n;Bonus Points: Run all 5 sample programs at the aforementioned website and output their results.\n\n\n\n", "solution": "\"\"\"Computer/zero Assembly emulator. Requires Python >= 3.7\"\"\"\n\nimport re\n\nfrom typing import Dict\nfrom typing import Iterable\nfrom typing import List\nfrom typing import NamedTuple\nfrom typing import Optional\nfrom typing import Tuple\n\n\nNOP = 0b000\nLDA = 0b001\nSTA = 0b010\nADD = 0b011\nSUB = 0b100\nBRZ = 0b101\nJMP = 0b110\nSTP = 0b111\n\nOPCODES = {\n \"NOP\": NOP,\n \"LDA\": LDA,\n \"STA\": STA,\n \"ADD\": ADD,\n \"SUB\": SUB,\n \"BRZ\": BRZ,\n \"JMP\": JMP,\n \"STP\": STP,\n}\n\nRE_INSTRUCTION = re.compile(\n r\"\\s*\"\n r\"(?:(?P