problem_id
stringlengths 32
32
| name
stringclasses 1
value | problem
stringlengths 200
14k
| solutions
stringlengths 12
1.12M
| test_cases
stringlengths 37
74M
| difficulty
stringclasses 3
values | language
stringclasses 1
value | source
stringclasses 7
values | num_solutions
int64 12
1.12M
| starter_code
stringlengths 0
956
|
---|---|---|---|---|---|---|---|---|---|
a1ea00fc8921a32af6c67e1c8312b6e0 | UNKNOWN | We have the following sequence:
```python
f(0) = 0
f(1) = 1
f(2) = 1
f(3) = 2
f(4) = 4;
f(n) = f(n-1) + f(n-2) + f(n-3) + f(n-4) + f(n-5);
```
Your task is to give the number of total values for the odd terms of the sequence up to the n-th term (included). (The number n (of n-th term) will be given as a positive integer)
The values 1 (one) is the only that is duplicated in the sequence and should be counted only once.
E.g.
```
count_odd_pentaFib(5) -----> 1 # because the terms up to 5 are: 0, 1, 1, 2, 4, 8 (only 1 is odd and counted once)
```
Other examples:
```
count_odd_pentaFib(10) ------> 3 #because the odds terms are: [1, 1, 31, 61] (three different values)
count_odd_pentaFib(15) ------> 5 # beacause the odd terms are: [1, 1, 31, 61, 1793, 3525] (five different values)
```
Good luck !!
(Your code should be fast. Many moderate high values will be waiting to test it.) | ["def count_odd_pentaFib(n):\n return 2 * (n // 6) + [0, 1, 2, 2, 2, 2][n % 6] - (n >= 2)", "buf = [0,1,1,2,4]\ndef count_odd_pentaFib(n):\n while len(buf)<=n:\n buf.append(sum(buf[-5:]))\n return len([i for i in set(buf[:n+1]) if i&1])\n", "def count_odd_pentaFib(n):\n if n == 0 :\n return 0\n if n < 5:\n return 1\n i = 4\n cnt = 1\n a, b, c, d, e = 0, 1, 1, 2, 4\n while i < n:\n a, b, c, d, e = b, c, d, e, a + b + c + d + e\n if e % 2 == 1:\n cnt += 1\n i += 1\n return cnt\n", "def count_odd_pentaFib(n):\n st = [0, 1]\n count = 0\n if 0< n < 2: return 1\n if n <= 0 : return 0\n while n >= 2:\n if sum(st[-5:]) % 2 != 0: count += 1\n st.append(sum(st[-5:]))\n n -= 1\n return count", "penta_fib_table = {\n 0: 0,\n 1: 1,\n 2: 1,\n 3: 2,\n 4: 4\n}\ndef penta_fib(n):\n if n in penta_fib_table:\n return penta_fib_table[n]\n return penta_fib(n - 1) + penta_fib(n - 2) + penta_fib(n - 3) + penta_fib(n - 4) + penta_fib(n - 5)\n\ndef count_odd_pentaFib(n):\n odd_terms = []\n for i in range(1, n + 1):\n penta_fib_i = penta_fib(i)\n penta_fib_table[i] = penta_fib_i\n if penta_fib_i % 2 == 1:\n odd_terms.append(penta_fib_i)\n return len(set(odd_terms))", "from functools import lru_cache\n\n\n@lru_cache()\ndef pentabonacci(n):\n return n if n in(0, 4) else 1 if n in (1, 2) else 2 if n == 3 else sum(pentabonacci(n - k) for k in range(1, 6))\n\n\ndef count_odd_pentaFib(n):\n return sum(1 for i in range(n + 1) if pentabonacci(i) % 2) - (1 if n > 1 else 0)", "from collections import deque\ndef count_odd_pentaFib(n):\n if n == 0: return 0\n elif n < 6: return 1\n \n def pentabonacci(max_term):\n terms = deque((1,1,2,4,8), 5)\n m = max_term - 5\n for i in range(m):\n next_term = sum(terms)\n yield next_term\n terms.append(next_term)\n \n return len(set((term for term in pentabonacci(n) if term % 2 == 1))) + 1\n", "from collections import deque\nfrom itertools import islice, groupby\n\ndef odd_penta_fib():\n q = deque([0, 1, 1, 2, 4, 8], maxlen=6)\n while True:\n yield q[0]\n q.append(q[-1] * 2 - q[0])\n \ndef count_odd_pentaFib(n):\n return sum(1 for key, grp in groupby(islice(odd_penta_fib(), n+1)) if key % 2 == 1)", "vector = [0, 1, 1, 2, 4]\nanswers = [0, 1, 1, 1, 1]\nfor i in range(43996):\n vector = vector[1:] + [sum(vector)]\n answers.append(answers[-1] + vector[-1] % 2)\n \ndef count_odd_pentaFib(n):\n return answers[n]"] | {"fn_name": "count_odd_pentaFib", "inputs": [[0], [1], [2]], "outputs": [[0], [1], [1]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,659 |
def count_odd_pentaFib(n):
|
c622eba5764304b05f3184066d77926b | UNKNOWN | Create a function `longer` that accepts a string and sorts the words in it based on their respective lengths in an ascending order. If there are two words of the same lengths, sort them alphabetically. Look at the examples below for more details.
```python
longer("Another Green World") => Green World Another
longer("Darkness on the edge of Town") => of on the Town edge Darkness
longer("Have you ever Seen the Rain") => the you Have Rain Seen ever
```
Assume that only only Alphabets will be entered as the input.
Uppercase characters have priority over lowercase characters. That is,
```python
longer("hello Hello") => Hello hello
```
Don't forget to rate this kata and leave your feedback!!
Thanks | ["def longer(s):\n return ' '.join(sorted(s.split(), key=lambda w: (len(w), w)) )", "def longer(s):\n return ' '.join(sorted(s.split(' '),key = lambda x: (len(x),x)))", "def longer(s):\n return ' '.join(sorted(s.split(), key=lambda item: (len(item), item)))", "def longer(s): #or longer = lambda s: if you're more daring :D\n return \" \".join(sorted(s.split(\" \"),key=lambda x:(len(x),x)))", "def longer(strng):\n def length_string(s):\n return len(s)\n initial_list = sorted(strng.split())\n result = \" \".join(sorted(initial_list, key = length_string))\n return result", "def longer(s):\n return ' '.join(sorted(sorted(s.split(' ')), key=len))", "longer = lambda s: \" \".join(sorted(s.split(\" \"),key=lambda x:(len(x),x)))", "# Why not both? :)\n\ndef longer(s):\n return \" \".join(sorted(list(s.split()), key=lambda x: (len(x), x)))\n \nlonger = lambda s: \" \".join(sorted(list(s.split()), key=lambda x: (len(x), x))) ", "def longer(s):\n words = s.split(' ')\n return ' '.join(sorted(words, key = lambda x: (len(x),x)))", "def longer(sentence):\n def conditional(word):\n return len(word), word\n words = sentence.split(\" \")\n words = sorted(words, key=conditional)\n return ' '.join(words)"] | {"fn_name": "longer", "inputs": [["Another Green World"], ["Darkness on the edge of Town"], ["Have you ever Seen the Rain"], ["Like a Rolling Stone"], ["This will be our Year"], ["hello Hello"]], "outputs": [["Green World Another"], ["of on the Town edge Darkness"], ["the you Have Rain Seen ever"], ["a Like Stone Rolling"], ["be our This Year will"], ["Hello hello"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,278 |
def longer(s):
|
f7e029d6215fc64dbdf1fdf0c9fedd4d | UNKNOWN | You are stacking some boxes containing gold weights on top of each other. If a box contains more weight than the box below it, it will crash downwards and combine their weights. e.g. If we stack [2] on top of [1], it will crash downwards and become a single box of weight [3]
```
[2]
[1] --> [3]
```
Given an array of arrays, return the bottom row (i.e. the last array) after all crashings are complete.
```
crashing_weights([[1, 2, 3], --> [[1, 2, ], [[1, , ]],
[2, 3, 1], --> [2, 3, 4], --> [2, 2, ],
[3, 1, 2]]) [3, 1, 2]] --> [3, 4, 6]]
therefore return [3, 4, 6]
```
## More details
boxes can be stacked to any height, and the crashing effect can snowball:
```
[3]
[2] [5]
[4] --> [4] --> [9]
```
Crashing should always start from as high up as possible -- this can alter the outcome! e.g.
```
[3] [3]
[2] [5] [2] [3]
[1] --> [1] --> [6], not [1] --> [3]
```
Weights will always be integers. The matrix (array of arrays) may have any height or width > 1, and may not be square, but it will always be "nice" (all rows will have the same number of columns, etc). | ["from functools import reduce\n\ndef crashing_weights(weights):\n return reduce(lambda a, b: [a1 + b1 if a1 > b1 else b1 for a1, b1 in zip(a, b)], weights)", "def crashing_weights(weights):\n lst = [0] * len(weights[0])\n for line in weights:\n lst = [b if a <= b else a+b for a,b in zip(lst, line)]\n return lst", "def crashing_weights(weights):\n if len(weights) < 2:\n return weights[0]\n result = []\n for row in zip(*weights):\n cur = row[0]\n for nxt in row[1:]:\n cur = cur + nxt if cur > nxt else nxt\n result.append(cur)\n return result\n", "from itertools import *\n\ndef crashing_weights(arr):\n arr = list(zip(*arr))\n return [list(accumulate(i,lambda x,y: x+y if x>y else y))[-1] for i in arr]", "from functools import reduce\n\ndef crashing_weights(weights):\n return [reduce(lambda x,y: x*(x>y) + y, pile) for pile in zip(*weights)]", "def crashing_weights(a):\n li = [list(i) for i in zip(*a)]\n for i in range(len(li)):\n for j in range(len(li[i]) - 1):\n if li[i][j] > li[i][j + 1]:\n li[i][j + 1] += li[i][j]\n li[i][j] = 0\n return [list(i) for i in zip(*li)][-1]", "from functools import reduce\n\ndef crashing_weights(weights):\n return reduce(crash_if_heavier, weights)\n\ndef crash_if_heavier(upper_row, lower_row):\n return [wl if wu <= wl else wu + wl for wu, wl in zip(upper_row, lower_row)]", "def crashing_weights(weights):\n w=zip(*weights)\n ans=[]\n for i in w:\n i=list(i)[::-1]\n while len(i)>1 and i!=sorted(i, reverse=True):\n for j in range(len(i)-1,0,-1):\n if i[j-1]<i[j]:\n i[j-1]+=i[j]\n del i[j]\n break\n ans.append(i[0])\n return ans", "def crashing_weights(weights):\n r=[]\n for t in zip(*weights):\n l=list(t)\n for i in range(1,len(l)):\n if l[i-1]>l[i]:\n l[i]+=l[i-1]\n r.append(l[-1])\n return r", "def crashing_weights(weights):\n result = []\n for row in zip(*weights):\n if len(row) < 2:\n return weights[0]\n cur = row[0]\n for nxt in row[1:]:\n cur = cur + nxt if cur > nxt else nxt\n result.append(cur)\n return result\n"] | {"fn_name": "crashing_weights", "inputs": [[[[1]]], [[[1, 2]]], [[[2], [1]]]], "outputs": [[[1]], [[1, 2]], [[3]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,353 |
def crashing_weights(weights):
|
9ec356b22ee87015c29ade1500272651 | UNKNOWN | A chess position can be expressed as a string using the Forsyth–Edwards Notation (FEN). Your task is to write a parser that reads in a FEN-encoded string and returns a depiction of the board using the Unicode chess symbols (♔,♕,♘,etc.). The board should be drawn from the perspective of the active color (i.e. the side making the next move).
Using the CodeWars dark theme is strongly recommended for this kata. Otherwise, the colors will appear to be inverted.
The complete FEN format contains 6 fields separated by spaces, but we will only consider the first two fields: Piece placement and active color (side-to-move). The rules for these fields are as follows:
The first field of the FEN describes piece placement.
Each row ('rank') of the board is described one-by-one, starting with rank 8 (the far side of the board from White's perspective) and ending with rank 1 (White's home rank). Rows are separated by a forward slash ('/').
Within each row, the contents of the squares are listed starting with the "a-file" (White's left) and ending with the "h-file" (White's right).
Each piece is identified by a single letter: pawn = P, knight = N, bishop = B, rook = R, queen = Q and king = K. White pieces are upper-case (PNBRQK), while black pieces are lowercase (pnbrqk).
Empty squares are represented using the digits 1 through 8 to denote the number of consecutive empty squares.
The piece placement field is followed by a single space, then a single character representing the color who has the next move ('w' for White and 'b' for Black).
Four additional fields follow the active color, separated by spaces. These fields can be ignored.
Using this encoding, the starting position is:
```rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1```
Using the characters "_" and "▇" to represent dark and light unoccupied spaces, respectively, the starting position using the Unicode pieces would be:
♖♘♗♕♔♗♘♖
♙♙♙♙♙♙♙♙
▇_▇_▇_▇_
_▇_▇_▇_▇
▇_▇_▇_▇_
_▇_▇_▇_▇
♟♟♟♟♟♟♟♟
♜♞♝♛♚♝♞♜
After the move 1. Nf3, the FEN would be...
```rnbqkbnr/pppppppp/8/8/8/5N2/PPPPPPPP/RNBQKB1R b KQkq - 1 1```
...and because we draw the board from the perspective of the active color, the Unicode board would be:
♜_♝♛♚♝♞♜
♟♟♟♟♟♟♟♟
▇_♞_▇_▇_
_▇_▇_▇_▇
▇_▇_▇_▇_
_▇_▇_▇_▇
♙♙♙♙♙♙♙♙
♖♘♗♕♔♗♘♖
Symbols
*Again, note that these colors are inverted from the Unicode character names because most people seem to use the dark theme for CodeWars.
Empty white square: ▇ (2587)
Empty black square: _ (FF3F)
White king (K): ♚ (265A)
White queen (Q): ♛ (265B)
White rook (R): ♜ (265C)
White bishop (B): ♝ (265D)
White knight (N): ♞ (265E)
White pawn (P): ♟ (265F)
Black king (k): ♔ (2654)
Black queen (q): ♕ (2655)
Black rook (r): ♖ (2656)
Black bishop (b): ♗ (2657)
Black knight (n): ♘ (2658)
Black pawn (p): ♙ (2659)
NB: Empty squares must have the proper colors. The bottom-right and top-left squares on a chess board are white. | ["from pprint import *\nuni= {'q': '\\u2655', 'B': '\\u265D', 'p': '\\u2659', 'K': '\\u265A',\n 'N': '\\u265E', 'Q': '\\u265B', 'P': '\\u265F', 'R': '\\u265C',\n 'n': '\\u2658', 'r': '\\u2656', 'b': '\\u2657', 'k': '\\u2654',\n 1:\"\\u2587\",0:\"\\uFF3F\"}\ndef parse_fen(string):\n board=[[1,0,1,0,1,0,1,0] if not i%2 else [0,1,0,1,0,1,0,1] for i in range(8) ]\n\n col,row=0,0\n pos=0\n placement,turn=string.split(\" \")[:2]\n\n while pos<len(placement):\n if placement[pos]==\"/\":\n row+=1\n col=0\n\n elif (placement[pos]).isdigit():\n col+=int(placement[pos])\n\n else:\n board[row][col] = uni[placement[pos]]\n col+=1\n\n pos+=1\n\n board = [[uni[i] if type(i) is int else i for i in x] for x in board]\n\n if turn==\"b\":\n board=[list(v)[::-1] for v in zip(*[i[::-1] for i in zip(*board)])]\n \n return \"\\n\".join([\"\".join(i) for i in board])+\"\\n\"\n\n", "fen_notation = \"rnbqkbnrpc/CPRNBQKBNR\"\nchess_board = '''\\u2656\\u2658\\u2657\\u2655\\u2654\\u2657\\u2658\\u2656\\u2659\\uff3f\n\\u2587\\u265f\\u265c\\u265e\\u265d\\u265b\\u265a\\u265d\\u265e\\u265c'''\ntable = dict(list(zip(fen_notation, chess_board)))\n\ndef parse_fen(fen_string):\n rev = lambda p: p[1][::(-1) ** (p[0] % 2)]\n board = list('/'.join(map(rev, enumerate(['Cc'*4] * 8))))\n idx, (game, turn) = 0, fen_string.split()[:2]\n for c in game:\n if c.isdigit(): idx += int(c)\n else:\n board[idx] = c\n idx += 1\n return rev((turn == 'b', ''.join(map(table.get, board)))) + '\\n'\n", "def parse_fen(string):\n unicodes = {\"p\":\"\\u2659\", \"n\":\"\\u2658\", \"b\":\"\\u2657\", \"r\":\"\\u2656\", \"q\":\"\\u2655\", \"k\":\"\\u2654\",\n \"P\":\"\\u265F\", \"N\":\"\\u265E\", \"B\":\"\\u265D\", \"R\":\"\\u265C\", \"Q\":\"\\u265B\", \"K\":\"\\u265A\",\n \"black\":\"\\u2587\", \"white\":\"\\uff3f\"}\n \n black,white = unicodes[\"black\"],unicodes[\"white\"] \n empty = [list((black+white))*4 if i % 2 == 0 else list((white+black))*4 for i in range(8)]\n\n field_one,active,*rest = string.split(\" \") \n rows = field_one.split(\"/\")\n\n if active != \"w\":\n rows = [i[::-1] for i in rows[::-1]]\n \n for row_index,row in enumerate(rows):\n count = 0\n for char in row:\n if char.isdigit():\n count += int(char)\n else:\n empty[row_index][count] = unicodes[char]\n count += 1\n\n return \"\\n\".join([\"\".join(i) for i in empty])+\"\\n\"", "TOME = {0:'\u2587', 1:'\uff3f', 'K':'\u265a', 'Q':'\u265b', 'R':'\u265c', 'B':'\u265d', 'N':'\u265e', 'P':'\u265f', 'k':'\u2654', 'q':'\u2655', 'r':'\u2656', 'b':'\u2657', 'n':'\u2658', 'p':'\u2659'}\n\ndef parse_fen(s):\n bd,color,*_ = s.split()\n bd = [formatRow(row, x&1) for x,row in enumerate(bd.split('/'))]\n if color=='b':\n bd = (r[::-1] for r in reversed(bd))\n return '\\n'.join(bd) + '\\n'\n\ndef formatRow(row,p):\n out = ''.join( TOME[c] if not c.isdigit() else 'x'*int(c) for i,c in enumerate(row))\n return ''.join(c if c!='x' else TOME[p^i&1] for i,c in enumerate(out))", "def parse_fen(string):\n placement, active, *_ = string.split()\n board = []\n for color, pieces in enumerate(placement.split('/')):\n color %= 2\n rank = []\n for piece in pieces:\n if piece.isdigit():\n spaces = int(piece)\n for i in range(spaces): rank.append(empty[(color+i)%2])\n color ^= spaces % 2\n else:\n rank.append(symbols[piece])\n color ^= 1\n board.append(rank)\n d = 1 if active == 'w' else -1\n return '\\n'.join(''.join(c for c in rank[::d]) for rank in board[::d]) + '\\n'\n\nsymbols = dict(list(zip('PNBRQKpnbrqk', '\u265f\u265e\u265d\u265c\u265b\u265a\u2659\u2658\u2657\u2656\u2655\u2654')))\nempty = '\u2587\uff3f'\n", "BOARD = '\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587'\nPIECES = dict(zip('kqrbnpKQRBNP', '\u2654\u2655\u2656\u2657\u2658\u2659\u265a\u265b\u265c\u265d\u265e\u265f'))\n\ndef parse_fen(string):\n board = list(map(list, BOARD.splitlines()))\n pieces, color = string.split()[:2]\n\n for r, rank in enumerate(pieces.split('/')):\n f = 0\n for square in rank:\n if square.isdigit():\n f += int(square)\n else:\n board[r][f] = PIECES[square]\n f += 1\n return '\\n'.join(map(''.join, board if color == 'w' else [rank[::-1] for rank in board[::-1]])) + '\\n'", "BOARD = '\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587'\nPIECES = dict(zip('kqrbnpKQRBNP', '\u2654\u2655\u2656\u2657\u2658\u2659\u265a\u265b\u265c\u265d\u265e\u265f'))\n\ndef parse_fen(string):\n board = list(map(list, BOARD.splitlines()))\n pieces, color, *_ = string.split()\n\n i = 0 if color == 'w' else 7\n\n for r, rank in enumerate(pieces.split('/')):\n f = 0\n for square in rank:\n if square.isdigit():\n f += int(square)\n else:\n board[abs(r - i)][abs(f - i)] = PIECES[square]\n f += 1\n return '\\n'.join(map(''.join, board)) + '\\n'", "def parse_fen(string):\n ranks = string.split('/')\n game_info_fields = ranks[7].split(' ')\n ranks[7] = game_info_fields[0] # trimming out the unused fields after the last rank\n color = game_info_fields[1]\n \n pretty_pieces = {'r' : '\u2656', 'n' : '\u2658', 'b' : '\u2657', 'q' : '\u2655', 'k' : '\u2654', 'p' : '\u2659', \n 'R' : '\u265c', 'N' : '\u265e', 'B' : '\u265d', 'Q' : '\u265b', 'K' : '\u265a', 'P' : '\u265f'}\n squares = ['\u2587', '\uff3f']\n board = [[squares[(i + j) % 2] for i in range(0, 8)] for j in range(0, 8)]\n \n for row in range(0, 8):\n rank = ranks[row]\n column = 0\n for char in rank:\n if char.isnumeric():\n column += int(char)\n else:\n board[row][column] = pretty_pieces[char]\n column += 1\n\n stringify = '\\n'.join([ ('').join(board[i]) for i in range(0, 8)])\n return stringify + '\\n' if color is 'w' else stringify[::-1] + '\\n'"] | {"fn_name": "parse_fen", "inputs": [["8/8/8/8/8/8/8/8 w - -"], ["8/8/8/8/8/8/8/8 b - -"], ["k7/8/8/8/8/8/8/7K w - -"], ["k7/8/8/8/8/8/8/7K b - -"], ["rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"], ["7k/1p4rp/p2B4/3P1r2/1P6/8/P6P/R6K b - - 0 31"], ["r3kr2/1qp2ppp/p3p3/3nP3/1pB5/1P2P3/P4PPP/2RQ1RK1 b q - 2 19"], ["2r2rk1/pp1qbppp/3p1n2/4p1B1/4P3/2NQ1P2/PPP3PP/2KR3R w - - 1 13"], ["Q3N3/N7/8/P2P2P1/2P2P1B/3R1B2/1P2PK1P/1R6 w - -"], ["3k4/8/3PK3/8/8/8/8/8 w - -"], ["3k4/3q4/8/8/8/8/3K4/3Q4 w - -"]], "outputs": [["\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n"], ["\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n"], ["\u2654\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u265a\n"], ["\u265a\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2654\n"], ["\u2656\u2658\u2657\u2655\u2654\u2657\u2658\u2656\n\u2659\u2659\u2659\u2659\u2659\u2659\u2659\u2659\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u265f\u265f\u265f\u265f\u265f\u265f\u265f\u265f\n\u265c\u265e\u265d\u265b\u265a\u265d\u265e\u265c\n"], ["\u265a\uff3f\u2587\uff3f\u2587\uff3f\u2587\u265c\n\u265f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u265f\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\u265f\u2587\n\u2587\uff3f\u2656\uff3f\u265f\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\u265d\u2587\uff3f\u2659\n\u2659\u2656\u2587\uff3f\u2587\uff3f\u2659\uff3f\n\u2654\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n"], ["\u2587\u265a\u265c\uff3f\u265b\u265c\u2587\uff3f\n\u265f\u265f\u265f\u2587\uff3f\u2587\uff3f\u265f\n\u2587\uff3f\u2587\u265f\u2587\uff3f\u265f\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u265d\u2659\u2587\n\u2587\uff3f\u2587\u265f\u2658\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2659\uff3f\u2587\uff3f\u2659\n\u2659\u2659\u2659\uff3f\u2587\u2659\u2655\uff3f\n\uff3f\u2587\u2656\u2654\uff3f\u2587\uff3f\u2656\n"], ["\u2587\uff3f\u2656\uff3f\u2587\u2656\u2654\uff3f\n\u2659\u2659\uff3f\u2655\u2657\u2659\u2659\u2659\n\u2587\uff3f\u2587\u2659\u2587\u2658\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\u2659\u2587\u265d\u2587\n\u2587\uff3f\u2587\uff3f\u265f\uff3f\u2587\uff3f\n\uff3f\u2587\u265e\u265b\uff3f\u265f\uff3f\u2587\n\u265f\u265f\u265f\uff3f\u2587\uff3f\u265f\u265f\n\uff3f\u2587\u265a\u265c\uff3f\u2587\uff3f\u265c\n"], ["\u265b\uff3f\u2587\uff3f\u265e\uff3f\u2587\uff3f\n\u265e\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\u265f\u2587\uff3f\u265f\uff3f\u2587\u265f\u2587\n\u2587\uff3f\u265f\uff3f\u2587\u265f\u2587\u265d\n\uff3f\u2587\uff3f\u265c\uff3f\u265d\uff3f\u2587\n\u2587\u265f\u2587\uff3f\u265f\u265a\u2587\u265f\n\uff3f\u265c\uff3f\u2587\uff3f\u2587\uff3f\u2587\n"], ["\u2587\uff3f\u2587\u2654\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\u265f\u265a\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n"], ["\u2587\uff3f\u2587\u2654\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2655\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u2587\uff3f\u2587\uff3f\u2587\n\u2587\uff3f\u2587\u265a\u2587\uff3f\u2587\uff3f\n\uff3f\u2587\uff3f\u265b\uff3f\u2587\uff3f\u2587\n"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 7,147 |
def parse_fen(string):
|
fc013dadfad5f7b22470b95859f1d9d8 | UNKNOWN | Complete the function that calculates the derivative of a polynomial. A polynomial is an expression like: 3x^(4) - 2x^(2) + x - 10
### How to calculate the derivative:
* Take the exponent and multiply it with the coefficient
* Reduce the exponent by 1
For example: 3x^(4) --> (4*3)x^((4-1)) = 12x^(3)
### Good to know:
* The derivative of a constant is 0 (e.g. 100 --> 0)
* Anything to the 0th exponent equals 1 (e.g. x^(0) = 1)
* The derivative of the sum of two function is the sum of the derivatives
Notes:
* The exponentiation is marked with "^"
* Exponents are always integers and >= 0
* Exponents are written only if > 1
* There are no spaces around the operators
* Leading "+" signs are omitted
See the examples below.
## Examples
```python
derivative("-100") = "0"
derivative("4x+1") = "4" # = 4x^0 + 0
derivative("-x^2+3x+4") = "-2x+3" # = -2x^1 + 3x^0 + 0
``` | ["import re\n\nmy_regexp = (r'(?P<sign>[+\\-]?)'\n r'(?P<coeff>\\d*)'\n r'x'\n r'(?:\\^(?P<exp>\\d+))?')\n\nas_int = lambda s: int(s) if s else 1\n\ndef derivative(eq):\n result = ''\n for monom in re.finditer(my_regexp, eq):\n sign, coeff, exp = monom.groups()\n coeff,exp = list(map(as_int, (coeff,exp)))\n coeff *= exp\n exp -= 1\n result += ('{sign}{coeff}' if exp==0 else \n '{sign}{coeff}x' if exp==1 else\n '{sign}{coeff}x^{exp}'\n ).format(sign=sign, coeff=coeff, exp=exp)\n return result if result else '0'\n \n", "import re\n\nDERIVATE = re.compile(r'([+-]?)(\\d*)x\\^?(\\d*)')\n\ndef derivative(eq):\n rawDerivate = ''.join('{}{}x^{}'.format(sign, int(coef or '1')*int(exp or '1'), int(exp or '1')-1) \n for sign,coef,exp in DERIVATE.findall(eq))\n derivate = re.sub(r'x\\^0|\\^1\\b', '', rawDerivate)\n return derivate or '0'", "from re import finditer, sub\n\ndef derivative(equation):\n mx = ''\n \n for exp in finditer(r'([\\+\\-])?(\\d*)?x\\^?(\\d+)?', equation):\n sign = -1 if exp.group(1) == '-' else 1\n scalar = int(exp.group(2)) if exp.group(2) else 1\n power = int(exp.group(3)) if exp.group(3) else 1\n\n mx += f'{sign*power*scalar}x^{(power - 1)}+' \n mx = sub(r'x\\^0\\b', '', mx)\n mx = sub(r'x\\^1\\b', 'x', mx)\n mx = sub('\\+\\-', '-', mx)\n if not mx:\n return '0'\n return mx[:-1]\n", "import re\nderivative=lambda s:re.sub(r'\\^1(?=[-+])','',re.sub(r'\\+-','-','+'.join([['',f'{int(i[0]if i[0]and i[0]not in\"+-\"else[1,-1][i[0]==\"-\"])*int(i[-1]or 1)}'][bool(i[-2])]+(f'x^{[0,int(i[-1])-1][bool(i[-2])]}'if i[-1]else'') for i in re.findall(r'([-+]?\\d*)(x?)\\^?(\\d*)', s)]))).strip('+') or '0'", "import re\n\ndef derivative(eq):\n monos = re.findall(r'([+-]?)(\\d*)x\\^?(\\d*)', eq)\n result = ''\n for sign, coef, exp in monos:\n exp = int(exp or '1')\n coef = int(coef or '1') * exp\n result += f'{sign}{coef}x^{exp-1}'\n result = re.sub(r'x\\^0|\\^1\\b', '', result)\n return result or '0'", "import re\n\ndef derivative(eq):\n res = []\n \n # change bare \"x\"s to \"1x\" for easier processing\n eq = re.sub(r'\\bx', '1x', eq)\n \n # extract constants, variables and exponents\n for const, var, exp in re.findall(r'([+-]?\\d+)(x?)\\^?(\\d*)', eq):\n \n # if constant only, derivative = 0\n if not var:\n continue\n \n # if no exponent found (= 1), derivative = const\n if not exp:\n res.append(const)\n continue\n \n # if exponent > 1, calculate derivative\n const, exp = int(const), int(exp)\n const *= exp\n if exp == 2:\n res.append('%+dx' % const)\n else:\n res.append('%+dx^%d' % (const, exp - 1))\n \n # construct the final result and return it\n res = ''.join(res).strip('+') \n return res if res else '0'\n", "import re\nnomial = re.compile(r'(?P<sign>[\\+-]?)(?P<coef>[0-9]*)(?P<x>[a-z]?)\\^?(?P<exp>[0-9]*)')\n\ndef derive(eq):\n if not eq: return ''\n m = nomial.match(eq)\n c = int(m.group('coef') or '1')\n exp = int(m.group('exp') or '1')\n if not m.group('x'): r = \"\" \n elif not m.group('exp'): r = m.group('sign')+ str(c)\n elif m.group('exp') == '2': r = m.group('sign')+str(c * 2)+m.group('x')\n else: r = m.group('sign')+str(c*exp)+m.group('x')+'^'+str(exp-1)\n return r + derive(eq[m.end():])\n\ndef derivative(eq):\n return derive(eq) or '0'", "import re\nstr2int = lambda s: int(s + '1' * (not s[-1:].isdigit()))\n\ndef monomial(args):\n c, p = map(str2int, args)\n return '%+d' % (c * p) + 'x' * (p > 1) + '^%d' % (p - 1) * (p > 2)\n\ndef derivative(eq):\n return ''.join(map(monomial, re.findall(\"(-?\\d*)x\\^?(\\d*)\", eq))).lstrip('+') or '0'", "def derivative(eq):\n r = '+'.join([s for s in [derive(w) for w in eq.replace('+', ' ').replace('-', ' -').replace('-x', '-1x').split()] if s])\n return r.replace('+-','-') if r else '0'\n\ndef derive(term):\n if 'x' not in term: return ''\n if '^' not in term: \n return term.split('x')[0] if term.split('x')[0] else '1'\n a, b = [int(w) if w else 1 for w in term.split('x^')]\n a, b = a * b, b - 1\n return ('' if a == 1 else str(a)) + 'x' + ('^' + str(b) if b > 1 else '')", "from re import findall\n\ndef derivative(eq):\n monos = [\"{}\", \"{}x\", \"{}x^{}\"]\n\n res = \"\"\n for t in findall(\"(\\+|-)?(\\d+)?x(?:\\^(\\d+))?\", eq):\n a, b = (int(x) if x else 1 for x in t[1:])\n res += t[0] + monos[(b>1) + (b>2)].format(a*b, b-1)\n \n return res if res else \"0\""] | {"fn_name": "derivative", "inputs": [["4x+1"], ["-4x-1"], ["x^2+2x+1"], ["0"], ["-100"], ["-x^2+3x+4"], ["-x^5-x^4-x^3"], ["10x^9+10x^3+10x"], ["100x^5+12x^3-3x-3"], ["-1000x^7+200x^4+6x^2+x+1000"]], "outputs": [["4"], ["-4"], ["2x+2"], ["0"], ["0"], ["-2x+3"], ["-5x^4-4x^3-3x^2"], ["90x^8+30x^2+10"], ["500x^4+36x^2-3"], ["-7000x^6+800x^3+12x+1"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,842 |
def derivative(eq):
|
d8809f31f68d4f817381fa1bc6de110e | UNKNOWN | Write a function
```javascript
tripledouble(num1,num2)
```
```python
triple_double(num1, num2)
```
which takes numbers `num1` and `num2` and returns `1` if there is a straight triple of a number at any place in `num1` and also a straight double of the **same** number in `num2`.
If this isn't the case, return `0`
## Examples
```python
triple_double(451999277, 41177722899) == 1
# num1 has straight triple 999s and num2 has straight double 99s
triple_double(1222345, 12345) == 0
# num1 has straight triple 2s but num2 has only a single 2
triple_double(12345, 12345) == 0
triple_double(666789, 12345667) == 1
``` | ["def triple_double(num1, num2):\n return any([i * 3 in str(num1) and i * 2 in str(num2) for i in '0123456789'])", "def triple_double(num1, num2):\n for x in range(10):\n if str(x) * 3 in str(num1):\n if str(x) * 2 in str(num2):\n return 1\n return 0", "def triple_double(num1, num2):\n num1, num2 = str(num1), str(num2)\n for num in '0123456789':\n if num * 3 in num1 and num * 2 in num2:\n return 1\n return 0", "def triple_double(num1, num2):\n for i in range(10):\n if str(i) * 3 in str(num1):\n if str(i) * 2 in str(num2):\n return 1\n else:\n return 0\n return 0", "import re\ndef triple_double(num1, num2):\n str = \"{0}|{1}\".format(num1,num2)\n regex = re.compile(r'(\\d)(\\1){2}.*\\|.*(\\1){2}')\n match = regex.search(str)\n return True if match else False", "def triple_double(num1, num2):\n num1 = str(num1)\n num2 = str(num2)\n nums = ['1','0','2','3','4','5','6','7','8','9','0']\n for i in nums:\n if i * 3 in num1 and i * 2 in num2:\n return 1\n return 0", "import re\n\ndef triple_double(*args):\n return bool(re.search(r'(\\d)(\\1){2}.*\\ .*(\\1){2}', '%s %s' % args))", "def triple_double(num1, num2):\n DECIMAL_BASE = 10\n tripples = []\n previous, previous_previous = None, None\n\n while num1:\n (num1, rem) = divmod(num1, DECIMAL_BASE)\n if rem == previous and previous == previous_previous:\n tripples.append(rem)\n previous_previous = previous\n previous = rem\n \n while num2:\n (num2, rem) = divmod(num2, DECIMAL_BASE)\n if rem == previous and rem in tripples:\n return 1\n previous = rem\n return 0", "import re\n\ndef triple_double(num1, num2):\n triples = re.findall(r'(\\d)\\1{2}', str(num1))\n doubles = re.findall(r'(\\d)\\1{1}', str(num2))\n return len(set(triples) & set(doubles))", "import re\ndef triple_double(num1, num2):\n #code me ^^\n r3 = re.compile(r'(\\d)\\1\\1')\n f = r3.findall(str(num1))\n if len(f)>0: \n r2 = re.compile(f[0]+'{2}')\n if len(r2.findall(str(num2))):\n return 1\n return 0"] | {"fn_name": "triple_double", "inputs": [[451999277, 41177722899], [1222345, 12345], [12345, 12345], [666789, 12345667], [10560002, 100], [1112, 122]], "outputs": [[1], [0], [0], [1], [1], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,263 |
def triple_double(num1, num2):
|
9db0faf52c8dddc67eef8d83c9d11956 | UNKNOWN | A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: `2332, 110011, 54322345`
For a given number ```num```, write a function which returns an array of all the numerical palindromes contained within each number. The array should be sorted in ascending order and any duplicates should be removed.
In this kata, single digit numbers and numbers which start or end with zeros (such as `010` and `00`) are **NOT** considered valid numerical palindromes.
If `num` contains no valid palindromes, return `"No palindromes found"`.
Otherwise, return `"Not valid"` if the input is not an integer or is less than `0`.
## Examples
```
palindrome(1221) => [22, 1221]
palindrome(34322122) => [22, 212, 343, 22122]
palindrome(1001331) => [33, 1001, 1331]
palindrome(1294) => "No palindromes found"
palindrome("1221") => "Not valid"
```
---
### Other Kata in this Series:
Numerical Palindrome #1
Numerical Palindrome #1.5
Numerical Palindrome #2
Numerical Palindrome #3
Numerical Palindrome #3.5
Numerical Palindrome #4
Numerical Palindrome #5 | ["def palindrome(num):\n if not isinstance(num, int) or num < 0:\n return \"Not valid\"\n n = str(num)\n l = len(n)\n result = {int(n[i:j]) for i in range(l-1) for j in range(i+2, l+1) if int(n[i]) and n[i:j] == n[i:j][::-1]}\n return sorted(result) if result else \"No palindromes found\"\n", "pal = lambda s: all(a==b for a, b in zip(s[:len(s)//2], s[::-1]))\n\ndef palindrome(num):\n if type(123)!=type(num) : return 'Not valid' \n n = str(num)\n if any(not c.isdigit() for c in n): return 'Not valid'\n R, l = [], len(n)\n for i in range(2, l+1):\n for j in range(l-i+1):\n t = n[j:j+i]\n if pal(t) and t[0]!= '0':R.append(int(t))\n return sorted(set(R)) if R else 'No palindromes found'", "def is_pal(s):\n h = len(s) // 2\n return all(a == b for a, b in zip(s[:h], s[::-1][:h]))\n\ndef palindrome(num):\n if not isinstance(num, int) or num < 0:\n return 'Not valid'\n s = str(num)\n pals = set()\n for i, ch in enumerate(s):\n if ch == '0':\n continue\n for j in range(i + 2, len(s) + 1):\n test = s[i:j]\n if is_pal(test):\n pals.add(test)\n return sorted(int(x) for x in pals) or 'No palindromes found'\n", "from itertools import combinations_with_replacement as combs\n\ndef palindrome(num):\n is_palindrome = lambda chunk: chunk == chunk[::-1] and len(chunk) > 1 and not (chunk.startswith('0') or chunk.endswith('0'))\n s, l = str(num), len(str(num))\n if isinstance(num, int) and num > 0:\n lst = list(set(int(s[i:j]) for i,j in combs(range(l+1), 2) if is_palindrome(s[i:j])))\n else: \n return 'Not valid'\n return sorted(lst) if len(lst) else 'No palindromes found'", "def palindrome(num):\n if not isinstance(num, int) or num < 0:\n return \"Not valid\"\n\n k = []\n s = str(num)\n for i,x in enumerate(s):\n string = [x]\n for j in s[i+1:]:\n string.append(j)\n\n if string == string[::-1] and ''.join(string) not in k and string[-1] != '0':\n k.append(''.join(string))\n \n return k and sorted(int(x) for x in k) or \"No palindromes found\"", "def palindrome(num):\n if not (isinstance(num, int) and num > 0):\n return 'Not valid'\n s = str(num)\n result = set()\n for i in range(0, len(s)-1):\n for j in range(i+2, len(s)+1):\n if s[i] == '0':\n continue\n x = s[i:j]\n if x == x[::-1]:\n result.add(int(x))\n if result:\n return sorted(result)\n return 'No palindromes found'", "def palindrome(n):\n if type(n) != int or n <0 :return 'Not valid'\n n, p = str(n), set()\n for i in range(len(n)):\n for j in range(i + 2, len(n) + 1):\n sub = n[i:j]\n if sub == sub[::-1] and sub[0]!='0'!=sub[-1] : p.add(sub)\n return sorted(map(int,p)) or 'No palindromes found'", "def palindrome(num):\n if type(num) != int:\n return \"Not valid\"\n elif num < 0:\n return \"Not valid\"\n else:\n l = list(str(num))\n pals = []\n for i in range(len(l)):\n r_l = l[i+1:] \n for j in range(len(r_l)):\n seq = l[i:i+1]+r_l[:j+1]\n print(seq)\n if len(seq)%2==0:\n mid = int(len(seq)/2)\n fr = seq[:mid]\n bk = seq[mid:][::-1] \n else:\n mid = len(seq)//2\n fr = seq[:mid]\n bk = seq[mid+1:][::-1] \n if fr == bk:\n pal = int(''.join(seq))\n if pal%10 != 0 and pal not in pals: \n pals.append(pal)\n if pals:\n return sorted(pals)\n else:\n return \"No palindromes found\"\n \n \n \n \n \n", "def check_array(array):\n if len(array) > 1:\n mid = int(len(array) / 2)\n if len(array) % 2 == 0:\n mid = int(len(array) / 2)\n first = array[:mid]\n second = array[mid:]\n else:\n first = array[:mid]\n second = array[mid + 1:]\n second.reverse()\n if first == second:\n str_arr = \"\"\n for i in array:\n str_arr += str(i)\n pal = int(str_arr)\n pal2 = str(pal)\n if pal2 == str_arr:\n return pal\n\ndef palindrome(num): \n if isinstance(num, int) != True or num < 0 : return \"Not valid\"\n if num < 10: return \"No palindromes found\"\n \n array = []\n for i in str(num):\n array.append(int(i))\n array_list = [] \n for i in range(len(array)):\n part = array[i:]\n p = check_array(part)\n if p != None and p != 0:\n array_list.append(p)\n for j in range(len(part)):\n back = part[:-j]\n b = check_array(back)\n if b != None and b != 0:\n array_list.append(b)\n \n array_set = set(array_list)\n result = list(array_set)\n result.sort()\n if len(result) == 0: \n return \"No palindromes found\"\n else: \n return result", "def palindrome(num):\n if not isinstance(num, int) or num<0:\n return 'Not valid'\n check=str(num)\n total=set()\n for i in range(2, len(check)+1):\n for j in range(len(check)-i+1):\n if check[j:j+i][0]==\"0\" or check[j:j+i][-1]==\"0\":\n continue\n if is_palin(check[j:j+i]):\n total.add(int(check[j:j+i]))\n return sorted(total) if total else \"No palindromes found\"\ndef is_palin(s):\n return s[::-1]==s"] | {"fn_name": "palindrome", "inputs": [[2], [34322122], [10015885], [4444], [1002001], [141221001], [1551], [13598], ["ACCDDCCA"], ["1551"], [-4505]], "outputs": [["No palindromes found"], [[22, 212, 343, 22122]], [[88, 1001, 5885]], [[44, 444, 4444]], [[1002001]], [[22, 141, 1001, 1221]], [[55, 1551]], ["No palindromes found"], ["Not valid"], ["Not valid"], ["Not valid"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 5,938 |
def palindrome(num):
|
b9204557c2589cfe982fe026e56d26ad | UNKNOWN | # Task
You are given three integers `l, d and x`. Your task is:
```
• determine the minimal integer n
such that l ≤ n ≤ d, and the sum of its digits equals x.
• determine the maximal integer m
such that l ≤ m ≤ d, and the sum of its digits equals x.
```
It is guaranteed that such numbers always exist.
# Input/Output
- `[input]` integer `l`
- `[input]` integer `d`
`1 ≤ l ≤ d ≤ 10000.`
- `[input]` integer `x`
`1 ≤ x ≤ 36`
- `[output]` an integer array
Array of two elements, where the first element is `n`, and the second one is `m`.
# Example
For `l = 500, d = 505, x = 10`, the output should be `[505, 505]`.
For `l = 100, d = 200, x = 10`, the output should be `[109, 190]`. | ["def min_and_max(l, d, x):\n listOfCorect = [num for num in list(range(l,d+1)) if sum(map(int,str(num))) == x] \n return [min(listOfCorect), max(listOfCorect)]", "def min_and_max(l, d, x):\n for n in range(l, d+1):\n if sum(map(int, str(n))) == x: break\n \n for m in range(d, l-1, -1):\n if sum(map(int, str(m))) == x: break\n \n return [n, m]", "def min_and_max(l, d, x):\n return [next(i for i in range(l, d+1) if sum(int(n) for n in str(i)) == x),\n next(i for i in range(d, l-1, -1) if sum(int(n) for n in str(i)) == x)]", "def min_and_max(l, d, x):\n def min_or_max(l, d, x, end, step):\n return next(i for i in range(l, d+end, step) if sum(map(int,list(str(i)))) == x)\n return [min_or_max(l, d, x, 1, 1), min_or_max(d, l, x, 0, -1)]", "func = lambda n: sum(map(int, str(n)))\n\n# Fuck it, brute-force\ndef min_and_max(l, d, x):\n while func(l) != x: l += 1\n while func(d) != x: d -= 1\n return [l, d]", "def min_and_max(l, d, x):\n for i in range(l,d+1):\n if sum(map(int,list(str(i)))) == x:\n n = i\n break\n for i in reversed(list(range(l,d+1))):\n if sum(map(int,list(str(i)))) == x:\n m = i\n break\n return [n, m]\n", "from operator import itemgetter\ndef min_and_max(l, d, x):\n return list(itemgetter(0,-1)([i for i in range(l,d+1) if sum(map(int,list(str(i)))) == x]))", "def min_and_max(l, d, x):\n arr = [i for i in range(l, d+1) if sum(map(int, str(i))) == x]\n return [arr[0],arr[-1]]\n", "def min_and_max(l,d,x):\n d_sum=lambda n:sum(map(int,str(n)))\n min=next(i for i in range(l,d+1) if d_sum(i)==x)\n max=next(i for i in range(d,l-1,-1) if d_sum(i)==x)\n return [min,max]"] | {"fn_name": "min_and_max", "inputs": [[100, 200, 10], [123, 456, 5], [99, 501, 5], [99, 234, 1], [99, 234, 19], [99, 5001, 27], [99, 5001, 28], [2000, 7000, 3]], "outputs": [[[109, 190]], [[131, 410]], [[104, 500]], [[100, 100]], [[199, 199]], [[999, 4995]], [[1999, 4996]], [[2001, 3000]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,746 |
def min_and_max(l, d, x):
|
24af369e15e760402d6d802ea59acb8f | UNKNOWN | Bleatrix Trotter the sheep has devised a strategy that helps her fall asleep faster. First, she picks a number N. Then she starts naming N, 2 × N, 3 × N, and so on.
Whenever she names a number, she thinks about all of the digits in that number. She keeps track of which digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) she has seen at least once so far as part of any number she has named. Once she has seen each of the ten digits at least once, she will fall asleep.
Bleatrix must start with N and must always name (i + 1) × N directly after i × N.
For example, suppose that Bleatrix picks N = 1692. She would count as follows:
N = 1692. Now she has seen the digits 1, 2, 6, and 9.
2N = 3384. Now she has seen the digits 1, 2, 3, 4, 6, 8, and 9.
3N = 5076. Now she has seen all ten digits, and falls asleep.
The purpose of this kata is to return the last number Bleatrix Trotter sees before falling asleep.
Input
Will always be positive integer or zero
Output
The last number Bleatrix Trotter sees or "INSOMNIA" (-1 in Rust and C++) if she will count forever
Please note, this challenge is not my idea. It's from Google Code Jam 2016 | ["def trotter(n):\n i, numStr, numList =0,'',['0','1','2','3','4','5','6','7','8','9']\n if n==0:\n return('INSOMNIA')\n while all([i in numStr for i in numList])!=True:\n i+=1\n numStr = numStr+str(n*i)\n return(i*n)", "def trotter(k):\n if k == 0:\n return \"INSOMNIA\"\n n, d = k, set(str(k))\n while len(d) < 10:\n n, d = n+k, d | set(str(n+k))\n return n", "def trotter(n):\n if n == 0: return \"INSOMNIA\"\n seen, current = set(str(n)), n\n while len(seen) < 10:\n current += n\n seen.update(str(current))\n return current", "def trotter(n, i=1, digits=set()):\n return n*(i-1) if len(digits) == 10 else 'INSOMNIA' if i > 900 else trotter(n, i+1, digits.union(set(str(n*i))))", "def trotter(n):\n digits = set()\n for i in range(n, 10 ** 10, n or 10 ** 10):\n digits.update(str(i))\n if len(digits) == 10:\n return i\n return 'INSOMNIA'", "def trotter(n):\n seek = {str(e) for e in range(10)}\n for k in range(1, 73):\n seek -= {e for e in str(n * k)}\n if not seek: return n * k\n return 'INSOMNIA' ", "def trotter(n):\n if not n: return \"INSOMNIA\"\n \n seen, o = set(str(n)), n\n while len(seen) != 10:\n n += o\n seen |= set(str(n))\n return n", "def trotter(n):\n if not n:\n return 'INSOMNIA'\n dict={0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}\n increment=n\n while True:\n for i in str(n):\n dict[int(i)]=dict.get(int(i), 0)+1\n if next((j for j in dict.values() if j==0), 1):\n break\n n+=increment\n return n", "def trotter(n):\n if n==0: return \"INSOMNIA\"\n seen, k = set(str(n)), 1\n while (not set(\"1234567890\").issubset(seen)):\n k += 1\n seen.update(str(k*n))\n return n*k", "def trotter(k):\n if not k:\n return \"INSOMNIA\"\n d = set()\n for n in range(k, k*73, k):\n d.update(set(str(n)))\n if len(d) == 10:\n return n"] | {"fn_name": "trotter", "inputs": [[1692], [2], [7], [100], [1], [11], [163444], [206929], [459923], [691520], [0], [12500], [1250000]], "outputs": [[5076], [90], [70], [900], [10], [110], [653776], [620787], [4139307], [2074560], ["INSOMNIA"], [900000], [90000000]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,076 |
def trotter(n):
|
4040530085ed3d6a4a511c03d6562675 | UNKNOWN | ## If/else syntax debug
While making a game, your partner, Greg, decided to create a function to check if the user is still alive called `checkAlive`/`CheckAlive`/`check_alive`. Unfortunately, Greg made some errors while creating the function.
`checkAlive`/`CheckAlive`/`check_alive` should return true if the player's health is greater than 0 or false if it is 0 or below.
```if-not:csharp
The function receives one parameter `health` which will always be a whole number between -10 and 10.
``` | ["def check_alive(health):\n if health <= 0:\n return False\n else:\n return True\n \nprint(check_alive(0))", "def check_alive(health):\n if health <= 0:\n return False\n else:\n return True", "def check_alive(health: int):\n return health > 0", "def check_alive(health):\n if health < 0:\n return False\n elif health == 0:\n return False\n else:\n return True", "def check_alive(health: int) -> bool:\n \"\"\" Return `true` if the player's health is greater than 0 or `false` if it is 0 or below. \"\"\"\n return health > 0", "def check_alive(health):\n if health in range(-10,0):\n return False\n elif health == 0:\n return False\n else:\n return True", "def check_alive(health):\n# If Cond. to check the player's health\n if(health > 0):\n# True / False must be T / F not true / false\n return True\n else:\n return False", "def check_alive(check_alive):\n x = check_alive\n if x > 0:\n return True\n else:\n return False", "def check_alive(health):\n if health <= 0:\n return False\n else:\n return True\n \ncheck_alive(2)", "def check_alive(health):\n if(-10 <= health <= 0):\n return False\n elif 0 < health <= 10:\n return True", "def check_alive(health):\n if health <= 0:\n return bool()\n else:\n return bool(True)", "def check_alive(health):\n return health > 0", "check_alive = (0).__lt__", "def check_alive(health):\n return (lambda x: True if x > 0 else False)(health)", "check_alive = 0..__lt__", "def check_alive(health):\n if health <= 0:\n return False\n else:\n return True\n check_alive(health)", "def check_alive(health):\n if health <= 0 or health == 0:\n return False\n else:\n return True", "def check_alive(health):\n return False if health < 1 else True\n \n# if():\n# health < 0\n# return false\n# else:\n# return true\n\n", "health = list(range(-10,10))\ndef check_alive(health):\n if(health > 0):\n return True\n else:\n return False\n\n", "def check_alive(health):\n if 0 >= health:\n return False\n else:\n return True", "def check_alive(health):\n -10<health<10\n if health <= 0:\n return False\n else:\n return True", "import unittest\n\n\ndef check_alive(health):\n return True if health > 0 else False\n \n \nclass TestCheckAlive(unittest.TestCase):\n def test_should_return_true_when_health_is_greater_than_0(self):\n self.assertEqual(check_alive(health=1), True)\n\n def test_should_return_false_when_health_is_0(self):\n self.assertEqual(check_alive(health=0), False)\n\n def test_should_return_false_when_health_is_negative_int(self):\n self.assertEqual(check_alive(health=-1), False)\n", "check_alive=lambda n:n>0", "def check_alive2(func):\n def wrapper(*args, **kwargs):\n \n result = func(*args, **kwargs)\n return result\n return wrapper\n\n@check_alive2\ndef check_alive(health):\n return True if health>=1 else False", "def check_alive(health):\n if health <=0:\n return False\n elif health==0:\n return False\n else:\n return True", "def check_alive(health):\n if health < 1:\n return False\n \n else:\n return True\n# I dont know why 1 worked.. I shuffled throught whole numbers beggining from -10 to 10 and 1\n# happened to be the number at which the code worked. Any reasons as to why this worked they way it did?\n", "def check_alive(health):\n if health >= 1:\n return True\n if health <= 0:\n return False", "def check_alive(health):\n if (0<health<=10):\n return True \n else:\n return False", "def check_alive(health):\n val=True\n if health<= 10 and health>=-10:\n if health>0:\n return(True)\n else:\n return (False)\n else:\n return('Nombre non effectif')\n", "def check_alive(health = 0):\n return health > 0", "def check_alive(health):\n if -11< health <1:\n return False\n elif 0<health<11:\n return True", "#Defines the function\ndef check_alive(health):\n#Checks if health parameter is less than or equal to 0.\n if health <= 0:\n#if health is less than or equal to 0 you would be dead. So returns false\n return False\n else:\n#if health is greater than zero you would not be dead. So returns true.\n return True", "def check_alive(health):\n if health > 0:\n return True\n else:\n return False\n \n \n \n \n #if():\n # health <= 0\n#return False\n #else:\n # return True\n", "def check_alive(health):\n if health > 0:\n return True\n else:\n return False\ncheck_alive(-10)", "def check_alive(health):\n if health <= 0:\n return bool(False)\n else:\n return bool(True)", "def check_alive(health):\n if health <= 0:\n return False\n else:\n return True\n #pogchamp\n", "def check_alive(health):\n if health >0 and health <=10:\n return True\n elif health <=0 and health >=(-10):\n return False", "def check_alive(health):\n while -10 <= health <=10:\n if health <= 0:\n return False\n else:\n return True", "def check_alive(health):\n if health < 0 or health <= 0: #checking health less than 0 for - integer and less than equal to zero\n return False\n else:\n return True", "def check_alive(health):\n if health<=0: #dont forget to add a semicolon\n return False #make sure its capital\n else:\n return True", "def check_alive(health):\n if health <= 10 or health >= -10: \n if health > 0:\n return True\n else:\n return False\n return Error", "def check_alive(health):\n if health <= 0 and health >= -10:\n return False\n elif health > 0 and health <=10:\n return True\n else: \n return \"Impossible!\"", "def check_alive(health):\n #if(health <= 0): \n # return False\n #else:\n # return True\n return True if health > 0 else False", "def check_alive(health):\n if(health < 0):\n return False\n if(health == 0):\n return False\n else:\n return True", "1==\"true\"\n0==\"false\"\ndef check_alive(health):\n if health <= 0:\n return 0\n else:\n return 1", "def check_alive(health):\n if health > 0 <= 10:\n return True\n else:\n return False", "def check_alive(health):\n if health == 0 or health < 0:\n return False\n else:\n return True", "def check_alive(health):\n if health <= 0:\n return 1!=1 \n else:\n return 1==1 \nprint (check_alive(4))", "def check_alive(health):\n alive = 0\n if health > 0: \n alive = 1\n return alive", "def check_alive(health):\n# if health <= 0:\n# return False\n# else:\n# return True\n return False if health <= 0 else True", "def check_alive(health):\n if(health <= 0):\n# health < 0\n return False\n else:\n return True", "def check_alive(health):\n if health <= 0:\n return False\n else:\n return True\n\nprint((check_alive(-1)))\n", "def check_alive(health:float):\n if health <= 0:\n return False\n else:\n return True ", "def check_alive(health):\n if (health == 0):\n return False\n if(health < 10 and health > 0) or (health < 0 and health < -10):\n return True\n else:\n return False", "def check_alive(h):\n \n return True if h>0 else False", "def check_alive(health):\n if health <= 0:\n return False\n else:\n return True\n \nprint(check_alive(3))", "def check_alive(health):\n return (health>=1 and health<=10)", "def check_alive(health):\n if(health <= 0 and health >= -10):\n return False\n elif (health > 0 and health <= 10):\n return True\n else:\n print(\"Put a correct number\")", "def check_alive(h):\n return h>0", "def check_alive(health):\n if (health == 0):\n return False\n else:\n if (health < 0): \n return False\n else:\n return True", "def check_alive(health):\n Heal = True\n if health <= 0:\n Heal = False\n return Heal", "def check_alive(x):\n if x <= 0:\n return False\n else:\n return True", "def check_alive(health):\n if health<=0:\n return False\n else:\n return True\n return health\ncheck_alive(9)", "def check_alive(health):\n if health <= 0:\n return (False)\n else :\n return (True)\n \ncheck_alive(10)", "def check_alive(health):\n return health > 0 and True", "def check_alive(health):\n if health >0:\n x = True\n else:\n x = False\n return x", "def check_alive(health):\n if health >= 1:\n return True\n elif health <= 0:\n return False", "def check_alive(health):\n alive = True\n \n if health <= 0:\n alive = False\n \n return alive\n \n \n", "def check_alive(health):\n if health > 0:\n return True \n if health <= 0:\n return False", "def check_alive(health):\n if health <10 and health>-10:\n if health <= 0:\n return False\n else:\n return True", "def check_alive(health):\n if health >= -10 & health <= 10: \n if health > 0:\n return True\n else:\n return False ", "def check_alive(health):\n x = True\n y = False\n if health < 1:\n return y\n else:\n return x", "def check_alive(health):\n check=(health>0)\n return check", "def check_alive(health):\n if health >= 0 and health != 0:\n return True\n else: \n return False", "def check_alive(health):\n return False if health <= 0 else True\n #if health <= 0: return False\n #else: return True\n", "def check_alive(health):\n '''the format supplied is garbage and not pythonic. Let us make it more elegant'''\n '''Also, Trump sucks'''\n return False if health <=0 else True", "def check_alive(health):\n # the folowing line checks if the user's health is less than or equal to 0.\n if health <= 0:\n result = False\n # the following line will be used if line 3 is false.\n else:\n result = True\n return result", "def check_alive(health):\n return 0 < health", "def check_alive(health):\n if health < 10 and health > 0:\n return True\n else:\n return False", "def check_alive(health):\n if ((health >= -10) and (health <= 10) ):\n if(health > 0): \n return True\n else: \n if(health <= 0):\n return False", "def check_alive(hp):\n if hp <= 0:\n return False\n else:\n return True\n \ntest=check_alive(1)", "def check_alive(health):\n if health >= 1:\n return True\n else:\n return False\n return check_alive", "def check_alive(health):\n if(health >= -10) and (health <= 10):\n if health <= 0:\n return False\n else:\n return True", "def check_alive(health):\n if health >= -10 and health <= 10:\n if health > 0:\n return True\n else:\n return False\n else:\n return False", "def check_alive(health):\n if(health<=0):\n return False\n else:\n return True\n \ncheck_alive(-2)", "def check_alive(health):\n if health <= 0:\n return health != health\n else:\n return health == health", "def check_alive(health):\n if health >= 1:\n return True\n else: \n health <= 0\n return False", "def check_alive(health):\n if health <= 0:\n return False\n else:\n return True\n\nprint(check_alive(-7))", "def check_alive(health):\n return 0 if health <= 0 else 1", "def check_alive(health):\n \n if(health <= 0):\n return False\n else:\n return True\n \n maximum(-10, 10)", "def check_alive(health):\n if health <= 0 or health is None:\n return False\n elif health > 0:\n return True", "def check_alive(health):\n return health > 0 if health in range(-10,10) else False", "def check_alive(health):\n # Check if health ess or equal to 0\n if health <= 0:\n return False\n # Else\n else:\n return True", "def check_alive(health):\n if(health > 0):\n return 1\n else:\n return 0", "health = 0\ndef check_alive(health):\n if health > 0:\n return True\n else:\n return False\ncheck_alive(health)", "def check_alive(health):\n if health <= 0 and health >= -10:\n return False\n elif health > 0 and health <= 10:\n return True", "def check_alive(health):\n if health <= 0: #needs = because 0 health is also not alive!\n return False\n else:\n return True #True and False need uppercase"] | {"fn_name": "check_alive", "inputs": [[5], [0], [-5]], "outputs": [[true], [false], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 13,339 |
def check_alive(health):
|
a871e168a03972ee33f78ff5b685b89b | UNKNOWN | Looking at consecutive powers of `2`, starting with `2^1`:
`2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, ...`
Note that out of all the digits `0-9`, the last one ever to appear is `7`. It only shows up for the first time in the number `32768 (= 2^15)`.
So let us define LAST DIGIT TO APPEAR as the last digit to be written down when writing down all the powers of `n`, starting with `n^1`.
## Your task
You'll be given a positive integer ```1 =< n <= 10000```, and must return the last digit to appear, as an integer.
If for any reason there are digits which never appear in the sequence of powers, return `None`/`nil`.
Please note: The Last digit to appear can be in the same number as the penultimate one. For example for `n = 8`, the last digit to appear is `7`, although `3` appears slightly before it, in the same number:
`8, 64, 512, 4096, 32768, ...` | ["digits = lambda x: set(str(x))\n\ndef LDTA(n):\n if digits(n) == digits(n*n):\n return None\n \n seen = []\n x = n\n \n while len(seen) < 10:\n for d in str(x):\n if d not in seen:\n seen.append(d)\n x *= n\n \n return int(seen[-1])", "def LDTA(n):\n x,s = n,set(str(n))\n for _ in range(30):\n x *= n\n for d in str(x):\n s.add(d)\n if len(s)==10: return int(d)", "import math\ndef LDTA(n):\n if math.log10(n) == int(math.log10(n)): return None\n d = {0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}\n c = n\n while 1:\n for i in str(c):\n d[int(i)] = 1\n if sum(d.values()) == 10:\n return int(i)\n c *= n\n return -1", "import math\ndef LDTA(n):\n if(n==1 or math.log10(n)%1 == 0):\n return None\n else:\n power = 1\n digits = [d for d in range(0,10)]\n while(digits):\n number = [int(x) for x in str(n**power)]\n for x in number:\n if(x in digits):\n last_one = x\n digits.remove(x)\n power+=1\n return last_one", "def LDTA(n):\n digits = []\n num = 1\n pow = 1\n while num < n**pow and pow < 20:\n num *= n\n pow += 1\n if len(digits) == 10:\n return digits[-1]\n else:\n for d in str(num):\n if int(d) not in digits:\n digits.append(int(d))\n return None", "def LDTA(n):\n if set(str(n)) == set(str(n ** 2)):\n return\n res, i = [], 0\n while True:\n i += 1\n for digit in str(n ** i):\n if digit not in res:\n res.append(digit)\n if len(res) >= 10:\n return int(res[-1])\n", "def LDTA(n):\n remaining = set(range(10))\n for i in range(1, 100):\n for s in str(n**i):\n t = int(s)\n remaining.discard(t)\n if not remaining:\n return t", "def LDTA(n):\n if n in (1, 10, 100, 1000, 10000):\n return None\n digits = set(\"0123456789\")\n k = 1\n while True:\n p = str(n**k)\n for digit in p:\n digits -= {digit}\n if len(digits) == 1:\n return int(digits.pop())\n k += 1", "from itertools import islice\n\ndef iter_powers(n):\n x = n\n while True:\n yield from map(int, str(x))\n x *= n\n\n\ndef LDTA(n):\n appear = set(range(10))\n for x in islice(iter_powers(n), 1000):\n appear.discard(x)\n if len(appear) == 1:\n return appear.pop()", "def is_enough(lst):\n return len(lst) >= 10\n\ndef LDTA(n):\n res = []\n for i in range(1, 20):\n c = str(n ** i)\n for digit in c:\n if digit not in res:\n res.append(digit)\n if is_enough(res): break\n if is_enough(res): break\n if is_enough(res):\n return int(res[-1])\n return"] | {"fn_name": "LDTA", "inputs": [[100], [2], [3], [8], [1111], [3000]], "outputs": [[null], [7], [0], [7], [9], [5]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,079 |
def LDTA(n):
|
b52a652969fc8e77e65d8f34b7ce9876 | UNKNOWN | Task
======
Make a custom esolang interpreter for the language [InfiniTick](https://esolangs.org/wiki/InfiniTick). InfiniTick is a descendant of [Tick](https://esolangs.org/wiki/tick) but also very different. Unlike Tick, InfiniTick has 8 commands instead of 4. It also runs infinitely, stopping the program only when an error occurs. You may choose to do the [Tick](https://www.codewars.com/kata/esolang-tick) kata first.
Syntax/Info
======
InfiniTick runs in an infinite loop. This makes it both harder and easier to program in. It has an infinite memory of bytes and an infinite output amount. The program only stops when an error is reached. The program is also supposed to ignore non-commands.
Commands
======
`>`: Move data selector right.
`<`: Move data selector left.
`+`: Increment amount of memory cell. Truncate overflow: 255+1=0.
`-`: Decrement amount of memory cell. Truncate overflow: 0-1=255.
`*`: Add ascii value of memory cell to the output tape.
`&`: Raise an error, ie stop the program.
`/`: Skip next command if cell value is zero.
`\`: Skip next command if cell value is nonzero.
Examples
======
**Hello world!**
The following is a valid hello world program in InfiniTick.
```
'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++**>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>++++++++++++++++++++++++++++++++*>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*<<*>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*<<<<*>>>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>+++++++++++++++++++++++++++++++++*&'
```
Notes
======
* Please be wordy and post your likes/dislikes in the discourse area.
* If this kata is a duplicate or uses incorrect style, this is not an issue, this is a suggestion.
* Please don't edit this kata just to change the estimated rank. Thank you! | ["def interpreter(tape):\n memory, ptr, output, iCmd = {}, 0, \"\", 0\n \n while True:\n cmd = tape[iCmd]\n if cmd == \">\": ptr += 1\n elif cmd == \"<\": ptr -= 1\n elif cmd == \"+\": memory[ptr] = (memory.get(ptr, 0) + 1) % 256\n elif cmd == \"-\": memory[ptr] = (memory.get(ptr, 0) - 1) % 256\n elif cmd == \"*\": output += chr(memory.get(ptr, 0))\n elif cmd == \"&\": break\n elif cmd == \"/\": iCmd += memory.get(ptr, 0) == 0\n elif cmd == \"\\\\\": iCmd += memory.get(ptr, 0) != 0\n iCmd = (iCmd+1) % len(tape)\n \n return output", "def interpreter(tape):\n memory, ptr, output, skip, i = {0: 0}, 0, \"\", False, 0\n \n while True:\n command = tape[i]\n i = (i + 1) % len(tape)\n \n if command in \"><+-*&/\\\\\" and skip:\n skip = False\n continue\n \n if command == \">\": ptr += 1\n elif command == \"<\": ptr -= 1\n elif command == \"+\": memory[ptr] = (memory.get(ptr, 0) + 1) % 256\n elif command == \"-\": memory[ptr] = (memory.get(ptr, 0) - 1) % 256\n elif command == \"*\": output += chr(memory.get(ptr, 0))\n elif command == \"&\": break\n elif command == \"/\" and memory[ptr] == 0: skip = True\n elif command == \"\\\\\" and memory[ptr] != 0: skip = True\n \n return output", "import itertools\n\ndef interpreter(tape): \n cells, cell, out, skip = {}, 0, '', False\n for c in itertools.cycle(tape):\n if not skip:\n if c == '>': cell += 1\n if c == '<': cell -= 1\n if c == '+': cells[cell] = 1 if cell not in cells else 0 if cells[cell] == 255 else cells[cell] + 1\n if c == '-': cells[cell] = 255 if cell not in cells else 255 if cells[cell] == 0 else cells[cell] - 1\n if c == '*': out += chr(cells.get(cell, 0))\n if c == '&': break\n skip = (c == '/' and cells.get(cell, 0) == 0) or (c == '\\\\' and cells.get(cell, 0))\n return out", "def interpreter(tape):\n infTick = Ticker()\n infTick.run(tape)\n return infTick.out\n \nclass Ticker():\n error = lambda x:None\n doc = {'>':'_incr', '<':'_decr', '*':'_addA', \n '+':'_icrC', '-':'_dcrC', '/':'_skpZ', '\\\\':'_skpN', '&':'_error'}\n \n def __init__(self):\n self.cell = 0\n self.dat = [0] * 255\n self.out = ''\n self.skip = 0\n self.end = 0\n \n def skip(f):\n def wrap(cls):\n if not cls.skip:\n return f(cls)\n cls.skip = 0\n return wrap\n\n def run(self, com):\n while not self.end and len(self.out) != 256:\n [getattr(self, self.doc.get(k, 'error'))() for k in com]\n\n def _skpZ(self):\n if self.dat[self.cell] == 0:\n self.skip = 1\n \n def _skpN(self):\n if self.dat[self.cell] != 0:\n self.skip = 1\n \n @skip\n def _error(self):\n self.end = 1\n \n @skip\n def _addN(self):#!\n self.dat[self.cell] = ord(self.out[-1])\n\n @skip\n def _dcrC(self):#-\n self.dat[self.cell] -= 1\n \n @skip\n def _icrC(self):#+\n self.dat[self.cell] += 1\n \n @skip\n def _addA(self):#*\n self.out += chr(self.dat[self.cell]%256)\n \n @skip\n def _incr(self):#>\n self.cell += 1\n \n @skip\n def _decr(self):#<\n self.cell -= 1", "def interpreter(tape):\n test = Ticker(tape)\n test.run()\n return test.out\n \nclass Ticker():\n error = lambda x:None\n doc = {'>':'_incr', '<':'_decr', '*':'_addA', \n '+':'_icrC', '-':'_dcrC', '/':'_skpZ', '\\\\':'_skpN', '&':'_error'}\n \n def __init__(self, tape):\n self.com = tape\n self.cell = 0\n self.dat = [0] * 255\n self.out = ''\n self.skip = 0\n self.end = 0\n \n def skip(f):\n def wrap(cond):\n if not cond.skip:\n return f(cond)\n cond.skip = 0\n return wrap\n\n def run(self):\n while not self.end and len(self.out) != 256:\n [getattr(self, self.doc.get(k, 'error'))() for k in self.com]\n\n def _skpZ(self):\n if self.dat[self.cell] == 0:\n self.skip = 1\n \n def _skpN(self):\n if self.dat[self.cell] != 0:\n self.skip = 1\n \n @skip\n def _error(self):\n self.end = 1\n \n @skip\n def _addN(self):#!\n self.dat[self.cell] = ord(self.out[-1])\n\n @skip\n def _dcrC(self):#-\n self.dat[self.cell] -= 1\n \n @skip\n def _icrC(self):#+\n self.dat[self.cell] += 1\n #\n @skip\n def _addA(self):#*\n self.out += chr(self.dat[self.cell]%256)\n \n @skip\n def _incr(self):#>\n self.cell += 1\n \n @skip\n def _decr(self):#<\n self.cell -= 1\n \n", "from collections import defaultdict\nfrom itertools import cycle\n\ndef interpreter(tape):\n i, skip, D, res = 0, False, defaultdict(int), []\n for c in cycle(tape):\n if skip: skip = False\n elif c == '>': i += 1\n elif c == '<': i -= 1\n elif c == '+': D[i] = (D[i] + 1)%256\n elif c == '-': D[i] = (D[i] - 1)%256\n elif c == '*': res.append(chr(D[i]))\n elif c == '&': break\n elif c == '/': skip = not D[i]\n elif c == '\\\\': skip = D[i]\n return ''.join(res)", "from collections import defaultdict\nfrom itertools import cycle\n\nvalid = ('<', '>', '+', '-', '*', '/', '\\\\', '&')\n\ndef interpreter(tape):\n memory = defaultdict(int)\n pointer = 0 \n input = cycle(c for c in tape if c in valid)\n output = '' \n \n while True:\n c = next(input)\n if c == '>': pointer += 1\n elif c == '<': pointer -= 1\n elif c == '+': memory[pointer] = (memory[pointer] + 1) % 256\n elif c == '-': memory[pointer] = (memory[pointer] - 1) % 256\n elif c == '*': output += chr(memory[pointer])\n elif c == '/' and not memory[pointer]: next(input)\n elif c == '\\\\' and memory[pointer]: next(input)\n elif c == '&': return output", "class InfiniTick:\n def __init__(self):\n self.mem = [0]\n self.pointer = 0\n \n def move_right(self):\n self.pointer += 1\n if self.pointer == len(self.mem):\n self.mem.append(0)\n \n def move_left(self):\n if self.pointer != 0:\n self.pointer -= 1\n else:\n self.mem.insert(0,0)\n self.pointer = 0\n\n def increment(self):\n self.mem[self.pointer] += 1\n if self.mem[self.pointer] > 255:\n self.mem[self.pointer] = 0\n \n def decrement(self):\n self.mem[self.pointer] -= 1\n if self.mem[self.pointer] < 0:\n self.mem[self.pointer] = 256 + self.mem[self.pointer]\n \n def output(self):\n return chr(self.mem[self.pointer])\n\n def process(self, tape):\n result = \"\"\n i = 0\n \n while True:\n if tape[i] == \">\":\n self.move_right()\n elif tape[i] == \"<\":\n self.move_left()\n elif tape[i] == \"+\":\n self.increment()\n elif tape[i] == \"-\":\n self.decrement()\n elif tape[i] == \"*\":\n result += self.output()\n elif tape[i] == \"&\":\n break\n elif tape[i] == \"/\":\n if self.mem[self.pointer] == 0:\n i += 1\n elif tape[i] == \"\\\\\":\n if self.mem[self.pointer] != 0:\n i += 1\n i += 1\n if i == len(tape):\n i = 0\n elif i > len(tape):\n i = 1\n \n return result\n \ndef interpreter(tape):\n tick = InfiniTick()\n return tick.process(tape)", "def interpreter(tape):\n selector = 0\n output = \"\"\n array = [0]\n commandIndex = 0\n \n while(True):\n command = tape[commandIndex%len(tape)]\n \n if command == '>':\n selector+=1;\n if selector == len(array):\n array.append(0)\n \n if command == '<':\n if selector == 0:\n array = [0] + array \n else:\n selector-=1;\n \n if command == '+':\n array[selector]+=1;\n if array[selector] == 256:\n array[selector] = 0\n if command == '-':\n array[selector]-=1;\n if array[selector] == -1:\n array[selector] = 255\n if command == '/':\n if array[selector] == 0:\n commandIndex += 1\n if command == '\\\\':\n if array[selector] != 0:\n commandIndex += 1\n if command == '*':\n output = output + chr(array[selector])\n if command == '&':\n return output \n commandIndex+=1 \n return output", "def interpreter(tape):\n data, pos, res = [0 for i in range(tape.count('*'))], 0, \"\"\n while 1:\n try:\n for i in iter([i for i in tape]):\n if i == \"+\": data[pos] = (data[pos] + 1) %256\n elif i == \"-\": data[pos] = (data[pos] - 1) %256\n elif i == \">\": pos += 1\n elif i == \"<\": pos -= 1\n elif i == \"*\": res += chr(data[pos])\n elif i == \"/\" and data[pos] == 0: next(tape)\n elif i == \"\\\\\" and data[pos] != 0: next(tape)\n elif i == \"&\": return res\n except:\n pass"] | {"fn_name": "interpreter", "inputs": [["\\h*&"], ["+-*&"]], "outputs": [["\u0000"], ["\u0000"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 9,870 |
def interpreter(tape):
|
355c7b26aff4c01c7de192f281b7fdfd | UNKNOWN | Sam has opened a new sushi train restaurant - a restaurant where sushi is served on plates that travel around the bar on a conveyor belt and customers take the plate that they like.
Sam is using Glamazon's new visual recognition technology that allows a computer to record the number of plates at a customer's table and the colour of those plates. The number of plates is returned as a string. For example, if a customer has eaten 3 plates of sushi on a red plate the computer will return the string 'rrr'.
Currently, Sam is only serving sushi on red plates as he's trying to attract customers to his restaurant. There are also small plates on the conveyor belt for condiments such as ginger and wasabi - the computer notes these in the string that is returned as a space ('rrr r' //denotes 4 plates of red sushi and a plate of condiment).
Sam would like your help to write a program for the cashier's machine to read the string and return the total amount a customer has to pay when they ask for the bill. The current price for the dishes are as follows:
* Red plates of sushi ('r') - $2 each, but if a customer eats 5 plates the 5th one is free.
* Condiments (' ') - free.
```
Input: String
Output: Number
Examples:
Input: 'rr' Output: 4
Input: 'rr rrr' Output: 8
Input: 'rrrrr rrrrr' Output: 16
``` | ["def total_bill(s):\n return 2*(s.count(\"r\") - s.count(\"r\")//5)", "def total_bill(s):\n num = s.count('r') \n return (num-num//5)*2", "def total_bill(s):\n s = s.replace(\" \",\"\")\n return 2 * (len(s)-len(s)//5)", "def total_bill(s):\n return (s.count('r') - s.count('r') // 5) * 2", "def total_bill(s):\n sushi = s.count(\"r\")\n discount = int (sushi/5)\n sushi-=discount\n return sushi*2", "from math import ceil\n\ndef total_bill(s):\n return 2 * ceil(s.count('r') * 4 / 5)", "def total_bill(s):\n n,r=divmod(s.count('r'),5)\n return 8*n+2*r", "import re\ndef total_bill(s):\n return len(re.sub(r\"r{5}\", \"rrrr\", re.sub(r\"\\s+\", \"\", s))) * 2\n", "def total_bill(s):\n plates = s.count('r')\n discount = int(plates/5)\n return (plates-discount)*2"] | {"fn_name": "total_bill", "inputs": [["rr"], ["rr rrr"], ["rr rrr rrr rr"], ["rrrrrrrrrrrrrrrrrr rr r"], [""]], "outputs": [[4], [8], [16], [34], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 816 |
def total_bill(s):
|
b6890618c3dbb6984841f3cd698fb43f | UNKNOWN | In this kata your mission is to rotate matrix counter - clockwise N-times.
So, you will have 2 inputs:
1)matrix
2)a number, how many times to turn it
And an output is turned matrix.
Example:
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
times_to_turn = 1
It should return this:
[[4, 8, 12, 16],
[3, 7, 11, 15],
[2, 6, 10, 14],
[1, 5, 9, 13]])
Note: all matrixes will be square. Also random tests will have big numbers in input (times to turn)
Happy coding! | ["def ccw(matrix):\n return [list(row) for row in zip(*map(reversed, matrix))]\n\ndef rotate_against_clockwise(matrix, times):\n for __ in range(times % 4):\n matrix = ccw(matrix)\n return matrix", "import numpy as np\n\ndef rotate_against_clockwise(matrix, times):\n return np.rot90(matrix, times).tolist()", "def rotate_against_clockwise(m, t):\n return rotate_against_clockwise([list(r) for r in zip(*m)][::-1], t % 4 - 1) if t else m", "def rotate_against_clockwise(matrix, times):\n if times == 0:\n return matrix\n else:\n matrix = [list(row) for row in zip(*matrix)][::-1]\n return rotate_against_clockwise(matrix, times % 4 - 1)\n", "rotate_against_clockwise=lambda a,n:rotate_against_clockwise(list(zip(*a))[::-1],n-1) if n%4 else list(map(list,a))", "def rotate_against_clockwise(matrix, times):\n return list(map(list,zip(*matrix)))[::-1] if times % 4 == 1 else rotate_against_clockwise(list(map(list,zip(*matrix)))[::-1], times-1)", "def rotate_against_clockwise(m, n):\n for _ in range(n % 4): m = [[r[i] for r in m] for i in range(len(m))][::-1]\n return m", "def rotate_against_clockwise(matrix, times):\n for i in range(3 - (times + 3) % 4):\n matrix = list(map(list, zip(*matrix[::-1])))\n return matrix"] | {"fn_name": "rotate_against_clockwise", "inputs": [[[[1, 2], [3, 4]], 1], [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 1], [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 2], [[[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30, 31, 32], [33, 34, 35, 36, 37, 38, 39, 40], [41, 42, 43, 44, 45, 46, 47, 48], [49, 50, 51, 52, 53, 54, 55, 56], [57, 58, 59, 60, 61, 62, 63, 64]], 3]], "outputs": [[[[2, 4], [1, 3]]], [[[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]]], [[[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]]], [[[57, 49, 41, 33, 25, 17, 9, 1], [58, 50, 42, 34, 26, 18, 10, 2], [59, 51, 43, 35, 27, 19, 11, 3], [60, 52, 44, 36, 28, 20, 12, 4], [61, 53, 45, 37, 29, 21, 13, 5], [62, 54, 46, 38, 30, 22, 14, 6], [63, 55, 47, 39, 31, 23, 15, 7], [64, 56, 48, 40, 32, 24, 16, 8]]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,293 |
def rotate_against_clockwise(matrix, times):
|
1d939ed2b2726581cc30c0fd7c454fe3 | UNKNOWN | # Task
Your task is to find the similarity of given sorted arrays `a` and `b`, which is defined as follows:
you take the number of elements which are present in both arrays and divide it by the number of elements which are present in at least one array.
It also can be written as a formula `similarity(A, B) = #(A ∩ B) / #(A ∪ B)`, where `#(C)` is the number of elements in C, `∩` is intersection of arrays, `∪` is union of arrays.
This is known as `Jaccard similarity`.
The result is guaranteed to fit any floating-point type without rounding.
# Example
For `a = [1, 2, 4, 6, 7]` and `b = [2, 3, 4, 7]`:
```
elements [2, 4, 7] are present in both arrays;
elements [1, 2, 3, 4, 6, 7] are present in at least one of the arrays.
So the similarity equals to 3 / 6 = 0.5.```
# Input/Output
- `[input]` integer array `a`
A `sorted` array of positive integers.
All elements are `different` and are `less than 100`.
`1 ≤ a.length ≤ 100`
- `[input]` integer array `b`
An array in the same format as `a`.
- `[output]` a float number
The similarity of the arrays.
```Haskell
In Haskell the two arrays are passed as a touple.
``` | ["def similarity(a, b):\n try:\n return len(set(a) & set(b)) / len(set(a) | set(b))\n except:\n return 0", "def similarity(*args):\n a,b = map(set, args)\n return len(a&b) / len(a|b)", "def similarity(a, b):\n c = a + b\n lst1 = []\n lst2 = []\n for i in set(c):\n if c.count(i) > 1:\n lst1.append(i)\n lst2.append(i)\n else:\n lst2.append(i)\n return len(lst1) / len(lst2)", "def similarity(a, b):\n a,b = set(tuple(a)),set(tuple(b))\n return len(a.intersection(b)) / len(a.union(b))", "def similarity(a, b):\n a, b = set(list(a)), set(list(b))\n return len(a.intersection(b)) / len(a.union(b))", "def similarity(a, b):\n a, b = set(a), set(b)\n return len(a & b) / len(a | b)", "def similarity(a, b):\n sa, sb = set(a), set(b)\n return len(sa & sb) / len(sa | sb)", "def similarity(a, b):\n return len(set(a).intersection(set(b))) / len(set(a).union(set(b)))", "def similarity(a, b):\n #coding and coding..\n return float(len(set(a) & set(b)))/len(set(a) | set(b))", "def similarity(a, b):\n \n x = list (set(a + b))\n z = [num for num in a if num in a and num in b]\n #time to count\n try:\n return len(z) / len (x)\n except ZeroDivisionError:\n return 0\n\n\n \n"] | {"fn_name": "similarity", "inputs": [[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [4, 5, 6]], [[1, 2, 4, 6, 7], [2, 3, 4, 7]], [[1, 2, 6, 8, 9], [0, 1, 4, 5, 6, 8, 9]], [[0, 1, 3, 4, 5, 6, 9, 14, 15, 16, 17, 18, 19], [1, 4, 10, 12, 13, 14, 15, 16]]], "outputs": [[1], [0], [0.5], [0.5], [0.3125]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,320 |
def similarity(a, b):
|
27aab3dca063715359bf4a66ff008ace | UNKNOWN | # Base reduction
## Input
A positive integer:
```
0 < n < 1000000000
```
## Output
The end result of the base reduction.
If it cannot be fully reduced (reduced down to a single-digit number), return -1.
Assume that if 150 conversions from base 11 take place in a row, the number cannot be fully reduced.
## Description
Base reduction is a process where a number is inputted, repeatedly converted into another base, and then outputted if it cannot be reduced anymore. If it cannot be fully reduced, return -1.
During the base conversions, the number is converted from the lowest base it can be converted from into base 10. For example, 123 would be converted from base 4 to base 10, since base 4 is the lowest base that 123 can be in (123 base 3 is impossible; in base 3, there is no digit 3).
If the lowest possible base the number can be converted into is 10, convert the number from base 11 to base 10. For example, 53109 would be converted from base 11 to base 10, since base 10 is the lowest base it can be in.
In the end, you should get a number that cannot be reduced by this process (a single digit number).
## Example
Starting with 5312:
```
5312 base 6 = 1196 base 10
1196 base 11 = 1557 base 10
1557 base 8 = 879 base 10
879 base 11 = 1054 base 10
1054 base 6 = 250 base 10
250 base 6 = 102 base 10
102 base 3 = 11 base 10
11 base 2 = 3 base 10
```
The output would be 3. | ["def basereduct(x):\n for _ in range(150):\n x = int(str(x), int(max(str(x))) + 1 + ('9' in str(x)))\n if x < 10: return x\n return -1", "def basereduct(x):\n limit = x * 1000000\n while x >= 10 and x <= limit:\n s = str(x)\n base = int(max(s)) + 1\n x = int(s, 11 if base == 10 else base)\n return x if x < 10 else -1", "def basereduct(x):\n for _ in range(150): \n s = str(x) \n x = int(s, max(int(c) for c in s) + 1 if '9' not in s else 11)\n if x < 10: return x\n return -1\n", "def basereduct(x, f=0):\n s = str(x)\n if len(s) == 1:\n return x\n elif f == 150:\n return -1\n elif \"9\" in s:\n f += 1\n return basereduct(int(s, 11), f)\n else:\n return basereduct(int(s, int(max(s)) + 1), 0)", "def basereduct(n):\n for _ in range(150):\n b = int(max(str(n))) + 1\n n = int(str(n), 11 if b==10 else b)\n if n < 10:\n return n\n return -1", "def basereduct(x):\n c=0\n while(len(str(x))>1):\n b=max(map(int,str(x)))+1\n if b==10:\n b=11\n i=0\n n=0\n for d in str(x):\n n=n*b+int(d)\n x=n\n c+=1\n if c>150:\n return -1\n return x", "def basereduct(x):\n s = str(x)\n b = 10\n m = max(list(s))\n if m == '9':\n b = 11\n else:\n b = int(m) + 1\n k = 0\n while len(s) > 1:\n t = int(s, b)\n s = str(t)\n m = max(list(s))\n if m == '9':\n b = 11\n else:\n b = int(m) + 1\n k += 1\n if k == 200:\n break\n if k == 200:\n return -1\n return int(s, b)\n", "def basereduct(x):\n count = 0\n while x >= 10:\n if count == 150: return -1\n s = str(x)\n b = max(map(int, s)) + 1\n if b == 10: b, count = 11, count+1\n x = int(s, b)\n return x", "def basereduct(n):\n base_numbers = {'0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6, '6': 7, '7': 8, '8': 9, '9': 11}\n conversion = 0\n while len(str(n)) > 1:\n n = int(str(n), base_numbers[max(str(n))])\n conversion += 1\n if conversion > 150:\n return -1\n return n", "def basereduct(x):\n count = 0\n while len(str(x)) > 1:\n base = max(int(i) for i in str(x))\n if base == 9:\n x = int(str(x), 11)\n else:\n x = int(str(x), base + 1)\n count += 1\n if count >= 150:\n return -1\n return x"] | {"fn_name": "basereduct", "inputs": [[10], [5], [7], [7], [15]], "outputs": [[2], [5], [7], [7], [3]]}
| INTRODUCTORY | PYTHON3 | CODEWARS | 2,607 |
def basereduct(x):
|
edaed45536c38b601ff9596f199b5bfc | UNKNOWN | The Story:
Aliens from Kepler 27b have immigrated to Earth! They have learned English and go to our stores, eat our food, dress like us, ride Ubers, use Google, etc. However, they speak English a little differently. Can you write a program that converts our English to their Alien English?
Task:
Write a function converting their speech to ours. They tend to speak the letter `a` like `o` and `o` like a `u`.
```python
>>> convert('hello')
'hellu'
>>> convert('codewars')
'cudewors'
``` | ["def convert(st):\n return st.replace('o','u').replace('a','o')", "def convert(s):\n return s.translate(str.maketrans('ao', 'ou'))", "def convert(st):\n return st.translate(str.maketrans('ao','ou'))", "def convert(st):\n return st.translate(str.maketrans('oa', 'uo'))", "def convert(stg):\n alien = str.maketrans(\"ao\", \"ou\")\n return stg.translate(alien)", "trans = str.maketrans(\"ao\", \"ou\")\nconvert = lambda st: st.translate(trans)", "def convert(english):\n alien_english = english.replace(\"o\", \"u\").replace(\"a\", \"o\")\n return alien_english", "def convert(st): \n for x,y in [['o','u'],['a','o']]:\n st = st.replace(x,y)\n \n return st", "def convert(st):\n return str.translate(st, str.maketrans(\"ao\", \"ou\"))", "convert=lambda s:s.translate({97:111,111:117})"] | {"fn_name": "convert", "inputs": [["codewars"], ["hello"]], "outputs": [["cudewors"], ["hellu"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 829 |
def convert(st):
|
b90475c49c757e8b53e4299f9c1da53f | UNKNOWN | Consider the number `1176` and its square (`1176 * 1176) = 1382976`. Notice that:
* the first two digits of `1176` form a prime.
* the first two digits of the square `1382976` also form a prime.
* the last two digits of `1176` and `1382976` are the same.
Given two numbers representing a range (`a, b`), how many numbers satisfy this property within that range? (`a <= n < b`)
## Example
`solve(2, 1200) = 1`, because only `1176` satisfies this property within the range `2 <= n < 1200`. See test cases for more examples. The upper bound for the range will not exceed `1,000,000`.
Good luck!
If you like this Kata, please try:
[Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)
[Alphabet symmetry](https://www.codewars.com/kata/59d9ff9f7905dfeed50000b0)
[Upside down numbers](https://www.codewars.com/kata/59f7597716049833200001eb) | ["ls = ['11', '13', '17', '19', '23', '29', '31', '37', '41', '43', '47', '53', '59', '61', '67', '71', '73', '79', '83', '89', '97']\ndef solve(a,b):\n i = a\n s = 0\n while i < b:\n if (i*i-i)%100==0 and str(i)[:2] in ls and str(i*i)[:2] in ls:\n s += 1\n i += 1\n return s", "from itertools import count\n\nPRIMES = ['11', '13', '17', '19', '23', '29', '31', '37', '41', '43', '47', '53', '59', '61', '67', '71', '73', '79', '83', '89', '97']\nSET_PRIMES = set(PRIMES)\nTAILS = ['00', '01', '25', '76'] # 2 digits numbers that fulfill the condition 11(76)*11(76) = ...(76)\n\ndef solve(a,b):\n maxMissingDigits = len(str(b))-4\n matches = 0\n for nd in range(maxMissingDigits+1):\n for p in PRIMES:\n if nd == maxMissingDigits and int(p + '0'*(nd+2)) > b: # All next generated numbers would be > b, so break\n break\n for t in TAILS:\n digs = count(0)\n while True:\n d = (\"{:0>\"+str(nd)+\"}\").format(next(digs)) if nd else '' # Digits to insert in the middle of the number\n val = int(p+d+t) # val = 2 digits prime + missing digits (up to maxMissingDigits) + 2 digits tail\n if val > b or len(d) > nd: break # Generated value is too high or if the digits to insert exceed the current number of digits sought for, break\n if str(val**2)[:2] in SET_PRIMES and a <= val:\n matches += 1\n if not d: break # If no digits to insert, the loop has to be broken manually after its first iteration\n return matches", "PRIMES = set([str(num) for num in range(3, 100) if all(num % x != 0 for x in [2] + list(range(3, int(num ** 0.5)+1, 2)))])\n\ndef solve(a, b):\n return sum(1 for x in range(max(a, 1000), b) if x % 100 == x*x % 100 and str(x)[:2] in PRIMES and str(x*x)[:2] in PRIMES)", "from bisect import bisect_left, bisect\n\ndef is_prime(n):\n if n < 2: return False\n if n == 2: return True\n if n % 2 == 0: return False\n return all(n % i for i in range(3, int(n**0.5)+1, 2))\n\ndef is_symmetry(n):\n return str(n ** 2)[:2] in SPRIMES\n\nSPRIMES = [str(i) for i in range(11, 100, 2) if is_prime(i)]\nBASE = [i for i in range(0, 100) if (i*i) % 100 == i]\ncandidates = (\n i + d\n for i in range(1100, 10000000+1, 100)\n if str(i)[:2] in SPRIMES\n for d in BASE\n)\nNS = [x for x in candidates if is_symmetry(x)]\n\n\ndef solve(a, b):\n return bisect(NS, b-1) - bisect_left(NS, a)", "two_digit_primes = set('11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97'.split())\n\n# pregenerate eligible numbers\nnumbers = []\nfor n in range(11, 9799 +1):\n if str(n)[:2] in two_digit_primes:\n for ending in (0, 1, 25, 76):\n candidate = n*100 + ending\n if str(candidate**2)[:2] in two_digit_primes:\n numbers.append(candidate)\n \ndef solve(a, b):\n return sum(1 for n in numbers if a <= n < b)\n", "from math import sqrt\ndef solve(a,b):\n i = a\n s = 0\n while i < b:\n if prope(i):\n s += 1\n i += 1\n return s\n\ndef prope(n): \n return (n*n-n)%100==0 and prime(int(str(n)[:2])) and prime(int(str(n*n)[:2]))\n\ndef prime(n):\n if n == 2:\n return True\n i = 2\n while i< sqrt(n)+1:\n if n % i==0:\n return False\n i+=1\n return True", "p = '11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97'.split()\nli = [i for i in range(1,1000000) if str(i)[:2] in p and str(i*i)[:2] in p and str(i*i)[-2:]==str(i)[-2:]]\nsolve=lambda a,b:sum(1 for i in li if a<=i<=b)", "def solve(a,b):\n a1 = (a + 99) // 100 * 100\n b1 = b // 100 * 100\n print((a1, b1))\n if a1 > b1: return sum(isok(x) for x in range(a, b))\n n = sum(isok(x) for x in range(a, a1)) + sum(isok(x) for x in range(b1, b))\n for k in range(a1, b1, 100):\n if str(k)[:2] in p2:\n for i in (0, 1, 25, 76):\n if str((k+i)**2)[:2] in p2:\n n += 1\n return n\n\ndef isok(n):\n return n % 100 in (0, 1, 25, 76) and str(n)[:2] in p2 and str(n*n)[:2] in p2\n\np2 = '11', '13', '17', '19', '23', '29', '31', '37', '41', '43', '47', '53', '59', '61', '67', '71', '73', '79', '83', '89', '97'\n", "primes = {11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97}\nendings = {'00','01','25','76'}\n\ndef solve(a,b):\n if b < 1176: return 0\n output = 0\n if a<1176: a=1176\n for i in [x for x in range(a,b) if str(x)[-2:] in endings]:\n if int(str(i)[:2]) not in primes:\n continue\n if int(str(i*i)[:2]) in primes:\n output += 1\n return output", "def is_prime(n):\n if n<2:\n return False\n elif n==2:\n return True\n elif n%2==0:\n return False\n x=3\n while(x*x<=n):\n if n%x==0:\n return False\n x+=2\n return True\n\nprimes=set([x for x in range(1,100) if is_prime(x)])\n\ndef get_seq():\n r=[]\n for x in range(1,1000001):\n if int(str(x)[:2]) in primes:\n y=x*x\n if int(str(y)[:2]) in primes and str(x)[-2:]==str(y)[-2:]:\n r.append(x)\n return r\n \nseq=set(get_seq())\n\ndef solve(a,b):\n r=0\n for x in range(a,b):\n if x in seq:\n r+=1\n return r"] | {"fn_name": "solve", "inputs": [[2, 1200], [1176, 1200], [2, 100000], [2, 1000000], [100000, 1000000]], "outputs": [[1], [1], [247], [2549], [2302]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 5,579 |
def solve(a,b):
|
c6e2d70204916af2c63758c2b538c312 | UNKNOWN | # Introduction
Digital Cypher assigns to each letter of the alphabet unique number. For example:
```
a b c d e f g h i j k l m
1 2 3 4 5 6 7 8 9 10 11 12 13
n o p q r s t u v w x y z
14 15 16 17 18 19 20 21 22 23 24 25 26
```
Instead of letters in encrypted word we write the corresponding number, eg. The word scout:
```
s c o u t
19 3 15 21 20
```
Then we add to each obtained digit consecutive digits from the key. For example. In case of key equal to `1939` :
```
s c o u t
19 3 15 21 20
+ 1 9 3 9 1
---------------
20 12 18 30 21
m a s t e r p i e c e
13 1 19 20 5 18 16 9 5 3 5
+ 1 9 3 9 1 9 3 9 1 9 3
--------------------------------
14 10 22 29 6 27 19 18 6 12 8
```
# Task
Write a function that accepts an array of integers `code` and a `key` number. As the result, it should return string containg a decoded message from the `code`.
# Input / Output
The `code` is a array of positive integers.
The `key` input is a positive integer.
# Example
``` javascript
decode([ 20, 12, 18, 30, 21],1939); ==> "scout"
decode([ 14, 10, 22, 29, 6, 27, 19, 18, 6, 12, 8],1939); ==> "masterpiece"
```
# Digital cypher series
- [Digital cypher vol 1](https://www.codewars.com/kata/592e830e043b99888600002d)
- [Digital cypher vol 2](https://www.codewars.com/kata/592edfda5be407b9640000b2)
- [Digital cypher vol 3 - missing key](https://www.codewars.com/kata/5930d8a4b8c2d9e11500002a) | ["from itertools import cycle\nfrom string import ascii_lowercase\n\ndef decode(code, key):\n keys = cycle(map(int, str(key)))\n return ''.join(ascii_lowercase[n - next(keys) - 1] for n in code)", "def decode(code, key):\n key=str(key)\n return \"\".join([chr(code[i] +96 - int(key[i%len(key)])) for i in range(0, len(code))])", "decode=lambda c,k:''.join(chr(a-int(b)+96)for a,b in zip(c,str(k)*30))", "def decode(code, key):\n base_dict = {}\n alpha = \"abcdefghijklmnopqrstuvwxyz\"\n for i in range(1,27):\n base_dict[i] = alpha[i-1]\n\n key_extended = []\n count = 0\n for i in range(len(code)):\n try :\n key_extended.append(int(str(key)[count]))\n except IndexError :\n count = 0\n key_extended.append(int(str(key)[count]))\n count += 1\n\n key_applied = []\n for i in range(len(code)) :\n key_applied.append(code[i] - key_extended[i])\n\n decrypt = \"\"\n for elt in key_applied :\n decrypt += base_dict[elt]\n \n return decrypt", "def decode(code, key):\n k = [int(k) for k in str(key)]\n n = len(k)\n return ''.join(chr(c - k[i % n] + 96) for i, c in enumerate(code))", "from itertools import cycle\nfrom operator import sub\n\n\ndef decode(code, key):\n key = cycle(list(map(int, str(key))))\n message = list(map(sub, code, key))\n return ''.join([chr(x + ord('a') - 1) for x in message])\n", "def decode(code, key):\n k = str(key)\n while len(k) < len(code):\n k *= 2\n return ''.join(chr(x - int(y) + 96) for x, y in zip(code, k))", "import itertools\n\ndef decode(code, key):\n return ''.join(chr(96+i-int(j)) for i, j in zip(code, itertools.cycle(str(key))))\n", "from itertools import cycle\n\ndef decode(code, key):\n k = cycle( list(map(int, str(key))) )\n return ''.join( chr(96+c-next(k)) for c in code )"] | {"fn_name": "decode", "inputs": [[[20, 12, 18, 30, 21], 1939], [[14, 10, 22, 29, 6, 27, 19, 18, 6, 12, 8], 1939]], "outputs": [["scout"], ["masterpiece"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,893 |
def decode(code, key):
|
0cf67a5ec0ff9c3c6053e3f00c5308be | UNKNOWN | Your friend has been out shopping for puppies (what a time to be alive!)... He arrives back with multiple dogs, and you simply do not know how to respond!
By repairing the function provided, you will find out exactly how you should respond, depending on the number of dogs he has.
The number of dogs will always be a number and there will always be at least 1 dog.
```r
The expected behaviour is as follows:
- Your friend has fewer than 10 dogs: "Hardly any"
- Your friend has at least 10 but fewer than 51 dogs: "More than a handful!"
- Your friend has at least 51 but not exactly 101 dogs: "Woah that's a lot of dogs!"
- Your friend has 101 dogs: "101 DALMATIANS!!!"
Your friend will always have between 1 and 101 dogs, inclusive.
``` | ["def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n return dogs[0] if n <= 10 else dogs[1] if n <=50 else dogs[3] if n == 101 else dogs[2]", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n if n <= 10:\n return dogs[0]\n elif n <= 50:\n return dogs[1]\n elif n < 101:\n return dogs[2] \n else:\n return dogs[3]", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n if n <= 10: return dogs[0] \n if n <= 50: return dogs[1] \n if n == 101: return dogs[3]\n return dogs[2]", "responses = [\n (lambda n: n < 11, \"Hardly any\"), \n (lambda n: n < 51, \"More than a handful!\"), \n (lambda n: n == 101, \"101 DALMATIONS!!!\"),\n (lambda n: True, \"Woah that's a lot of dogs!\")\n]\n\nhow_many_dalmatians = lambda n: next(r for p, r in responses if p(n))", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n if n <= 10:\n respond = 0\n elif n <= 50:\n respond = 1\n elif n == 101:\n respond = 3\n else:\n respond = 2\n \n return dogs[respond]", "DOGS = ((100, '101 DALMATIONS!!!'), (50, 'Woah that\\'s a lot of dogs!'),\n (10, 'More than a handful!'))\n\n\ndef how_many_dalmatians(n):\n return next((msg for dogs, msg in DOGS if n > dogs), 'Hardly any')\n", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\",\"101 DALMATIONS!!!\"];\n return dogs[(n>10)+(n>50)+(n==101)+(n>101)] ", "def how_many_dalmatians(n):\n return \"Hardly any\" if n <= 10 else(\"More than a handful!\" if n <= 50 else(\"101 DALMATIONS!!!\"if n == 101 else \"Woah that's a lot of dogs!\"))", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n if number <= 10:\n return dogs[0]\n elif number <= 50:\n return dogs[1]\n elif number != 101:\n return dogs[2]\n else:\n return dogs[3]\n", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n if number <= 10:\n return dogs[0] \n elif (number <= 50): \n return dogs[1]\n elif number == 101: \n return dogs[3]\n else:\n return dogs[2]", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n respond = dogs[0] if number <= 10 else dogs[1] if number <= 50 else dogs[3] if number == 101 else dogs[2]\n \n return respond", "how_many_dalmatians=lambda n: [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"][sum([n>10, n>50, n>=101])]", "DOGS = ((100, '101 DALMATIONS!!!'), (50, 'Woah that\\'s a lot of dogs!'),\n (10, 'More than a handful!'), (0, 'Hardly any'))\n\n\ndef how_many_dalmatians(n):\n return next(msg for total_dogs, msg in DOGS if n > total_dogs)\n", "def how_many_dalmatians(n: int) -> str:\n \"\"\" Get a defined string from the list based on given number. \"\"\"\n dogs = (\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\")\n return dogs[0] if n <= 10 else dogs[1] if n <= 50 else dogs[3] if n == 101 else dogs[2]", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n #respond:\n if n <= 10: \n return dogs[0] \n elif n <= 50: \n return dogs[1] \n elif n == 101: \n return dogs[3] \n else:\n return dogs[2]\n \n return respond", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n \n if n <= 10: return dogs[0] \n if n > 10 and n <= 50: return dogs[1] \n if n == 101: return dogs[3] \n else: return dogs[2] ", "def how_many_dalmatians(n):\n \n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n \n if n == 101:\n return dogs[3]\n \n elif n >50:\n return dogs[2]\n \n elif n <= 10:\n return dogs[0]\n \n else:\n return dogs[1]", "def how_many_dalmatians(n):\n dogs= [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n respond = dogs[0] if n <= 10 else (dogs[1] if n <= 50 else (dogs[3] if n == 101 else dogs[2]))#dogs[2] is 101 DALMATIONS!!! \n\n return respond", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n return dogs[(number > 10) + (number > 50) + (number == 101)]", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if n > 100:\n respond = dogs[3]\n elif n > 50:\n respond = dogs[2]\n elif n > 10:\n respond = dogs[1]\n else:\n respond = dogs[0]\n return respond", "def how_many_dalmatians(number):\n reaction = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n return reaction[0] if number <= 10 else reaction[1] if number <= 50 else reaction[3] if number == 101 else reaction[2]\n", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n\n if number <= 10 :\n respond = dogs[0]\n elif number <= 50 :\n respond = dogs[1]\n elif number <= 100 :\n respond = dogs[2]\n else:\n number = 101\n respond = dogs[3]\n return(respond)", "def how_many_dalmatians(n):\n n = int(n)\n if n <= 10:\n return \"Hardly any\"\n elif n <= 50:\n return \"More than a handful!\"\n elif n <= 100:\n return \"Woah that's a lot of dogs!\"\n elif n == 101:\n return \"101 DALMATIONS!!!\"", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n respond = \"\"\n if n <= 10:\n return dogs[0]\n elif n <= 50:\n return dogs[1] \n elif n == 101: \n return dogs[3] \n else: \n return dogs[2]\n \n #return dogs[0] if number <= 10 elif number <= 50 then dogs[1] elif number = 101 dogs[3] else dogs[2]\n", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n if n == 101:\n return dogs[3] \n \n elif n == None:\n return dogs[2]\n\n elif 51 < n < n ** n: \n return dogs[2] \n \n elif 10 < n <= 50: \n return dogs[1] \n \n elif n <= 10: \n return dogs[0] \n \n\n", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n if n <= 10:\n return dogs[0]\n elif n <= 50:\n return dogs[1]\n elif n < 101:\n return dogs[2]\n elif n == 101:\n return dogs[3]\n", "def how_many_dalmatians(n):\n if n<=10:\n return \"Hardly any\"\n if n<=50:\n return \"More than a handful!\"\n if n<=100:\n return \"Woah that's a lot of dogs!\"\n if n>=101:\n return \"101 DALMATIONS!!!\"\n \n \n", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n return dogs[0] if number <= 10 else dogs[1] if 10< number <= 50 else dogs[3] if number == 101 else dogs[2]\n \n", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if n <= 10:\n return dogs[0] \n if n <= 50:\n return dogs[1] \n if n == 101:\n return dogs[3] \n return dogs[2]\n return n", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n return dogs[0] if number <= 10 else dogs[1] if number <= 50 else dogs[-1] if number == 101 else dogs[2]\n", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n if number <= 10: \n return dogs[0] \n elif number <= 50:\n return dogs[1]\n elif number >50 and number!=101:\n return dogs[2]\n elif number == 101:\n return dogs[3] \n else:\n dogs[2]", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n if n <= 10:\n x = 0\n elif n <= 50:\n x = 1\n elif n == 101:\n x = 3\n else: \n x = 2\n \n return dogs[x]", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n return dogs[(n>10)+(n>50)+(n==101)]", "def how_many_dalmatians(n):\n dogs=[\"Hardly any\", \"Woah that's a lot of dogs!\", \"More than a handful!\", \"101 DALMATIONS!!!\"];\n return dogs[(n>10)*((n<=50)+2*(n==101)+1)]", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n return dogs [(n==101)+(50<n<=101)+(n>10)]", "d=[\"Hardly any\",\n \"More than a handful!\",\n \"Woah that's a lot of dogs!\",\n \"101 DALMATIONS!!!\"]\ndef how_many_dalmatians(n):\n return d[3] if n==101 else d[0] if n<=10 else d[1] if n<=50 else d[2] ", "def how_many_dalmatians(number): return \"Hardly any\" if number <= 10 else \"More than a handful!\" if number <= 50 else \"101 DALMATIONS!!!\" if number == 101 else \"Woah that's a lot of dogs!\"", "L = (\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\")\n\ndef how_many_dalmatians(n):\n return L[(n > 10) + (n > 50) + (n == 101)]", "def how_many_dalmatians(number):\n if number <=10:\n return \"Hardly any\"\n elif 10 < number <= 50:\n return \"More than a handful!\"\n if number == 101: \n return \"101 DALMATIONS!!!\"\n else:\n return \"Woah that's a lot of dogs!\"\n", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n respond = {n<=10: dogs[0], n<= 50 and n > 10: dogs[1], n==101: dogs[3]}.get(True, dogs[2])\n\n return respond", "def how_many_dalmatians(n):\n respond = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n\n if n <= 10:\n return respond[0]\n elif n <= 50:\n return respond[1]\n elif n == 101:\n return respond[3]\n return respond[2]", "DOGS = [\n \"Hardly any\",\n \"More than a handful!\",\n \"Woah that's a lot of dogs!\",\n \"101 DALMATIONS!!!\",\n]\n\n\ndef how_many_dalmatians(number):\n if number <= 10:\n respond = DOGS[0]\n elif number <= 50:\n respond = DOGS[1]\n elif number == 101:\n respond = DOGS[3]\n else:\n respond = DOGS[2]\n return respond\n", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n return dogs[3] if n > 100 else dogs[2] if n > 50 else dogs[1] if n > 10 else dogs[0]", "'''def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n respond = if number <= 10 then dogs[0] else if (number <= 50 then dogs[1] else (number = 101 dogs[3] else dogs[2]\n \nreturn respond'''\n \ndef how_many_dalmatians(n):\n answers = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n respond = 3 if n == 101 else 2 if n > 50 else 1 if n > 10 else 0\n return answers[respond]", "def how_many_dalmatians(n):\n if n<=10:\n return 'Hardly any'\n if n<=50:\n return 'More than a handful!'\n if n==101:\n return '101 DALMATIONS!!!'\n else:\n return 'Woah that\\'s a lot of dogs!'\n", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n if number <= 10: \n return dogs[0] \n elif number <= 50: \n return dogs[1] \n elif number < 101: \n return dogs[2]\n elif number == 101:\n return dogs[3]\n", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if number == 101:\n return dogs[3] \n elif number > 50:\n return dogs[2]\n elif number > 11:\n return dogs[1]\n else:\n return dogs[0]\n \n# respond = if number <= 10 then dogs[0] else if (number <= 50 then dogs[1] else (number = 101 dogs[3] else dogs[2] \n", "def how_many_dalmatians(number):\n dogs=[\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n if number <= 10:\n return dogs[0]\n elif 10<number <= 50:\n return dogs[1]\n elif number == 101:\n return dogs[3]\n elif 50<number<101:\n return dogs[2]", "def how_many_dalmatians(number):\n#dogs [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if 1 <= number <= 10:\n return \"Hardly any\"\n elif 11 <= number <= 50:\n return \"More than a handful!\"\n elif 51 <= number <= 100:\n return \"Woah that's a lot of dogs!\"\n elif number == 101:\n return \"101 DALMATIONS!!!\"", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if 10 >= n:\n return dogs[0]\n elif 50 >= n > 10:\n return dogs[1]\n elif 100 >= n > 50:\n return dogs[2]\n elif n > 100 :\n return dogs[3]", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n respond = dogs[0] if n <= 10 else (dogs[1] if n <= 50 else dogs[2])\n return respond if n != 101 else dogs[-1]", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n if n <= 10:\n return dogs[0] \n elif n <= 50:\n return dogs[1] \n elif n == 101: \n return dogs[3] \n elif n >= 50:\n return dogs[2]", "def how_many_dalmatians(number: int) -> str:\n dogs = [\n \"Hardly any\",\n \"More than a handful!\",\n \"Woah that's a lot of dogs!\",\n \"101 DALMATIONS!!!\",\n ]\n respond = (\n dogs[0]\n if number <= 10\n else dogs[1]\n if number <= 50\n else dogs[2]\n if number >= 50 and number <= 100\n else dogs[3]\n )\n return respond", "def how_many_dalmatians(n):\n if n <= 10:\n return 'Hardly any'\n elif n <= 50:\n return 'More than a handful!'\n elif n != 101:\n return \"Woah that's a lot of dogs!\"\n else:\n return '101 DALMATIONS!!!'", "def how_many_dalmatians(n):\n d = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n # respond = if number <= 10 then dogs[0] else if (number <= 50 then dogs[1] else (number = 101 dogs[3] else dogs[2]\n return d[0] if n <= 10 else d[1] if n <= 50 else d[3] if n==101 else d[2]", "def how_many_dalmatians(n):\n \n #respond = if number <= 10 then dogs[0] else if (number <= 50 then dogs[1] else (number = 101 dogs[3] else dogs[2]\n if n == 101:\n return \"101 DALMATIONS!!!\"\n elif n < 11:\n return \"Hardly any\"\n elif n < 51:\n return \"More than a handful!\"\n else: \n return \"Woah that's a lot of dogs!\"", "def how_many_dalmatians(n):\n if n >= 1 and n <= 10:\n return \"Hardly any\"\n elif n >= 11 and n <= 50:\n return \"More than a handful!\"\n elif n >= 51 and n <= 100:\n return \"Woah that's a lot of dogs!\"\n return \"101 DALMATIONS!!!\"", "def how_many_dalmatians(n):\n dogs = (\"Hardly any\", \n \"More than a handful!\", \n \"Woah that's a lot of dogs!\", \n \"101 DALMATIONS!!!\")\n if n <= 10:\n return dogs[0]\n if n <= 50:\n return dogs[1] \n if n == 101:\n return dogs[3] \n else:\n return dogs[2]", "def how_many_dalmatians(n):\n dogs=[\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n respond=''\n if n<= 10:\n respond=dogs[0] \n elif n <= 50:\n respond=dogs[1] \n elif n <=100:\n respond=dogs[2] \n \n elif n==101 :\n respond=dogs[3]\n \n return respond", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n respond = \"\"\n if n <= 10:\n return dogs[0]\n elif n <= 50:\n return dogs[1]\n elif n == 101:\n return dogs[3]\n return dogs[2]", "def how_many_dalmatians(n):\n dogs=[\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n if n <= 10:\n return dogs[0]\n if n <= 50:\n return dogs[1]\n if n == 101:\n return dogs[3]\n else:\n return dogs[2]\n #respond = if number <= 10 then dogs[0] else if number <= 50 then dogs[1] else (number == 101 dogs[3] else dogs[2])\n \n #return respond\n", "# Your friend has been out shopping for puppies (what a time to be alive!)... \n# He arrives back with multiple dogs, and you simply do not know how to respond!\n# By repairing the function provided, you will find out exactly how you should respond, \n# depending on the number of dogs he ha\n\ndef how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if(number <= 10):\n return dogs[0] \n elif(number <= 50):\n return dogs[1]\n elif(number == 101):\n return dogs[3]\n else:\n return dogs[2]", "def how_many_dalmatians(n):\n # dogs [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n if n <= 10: \n return \"Hardly any\"\n elif n <= 50: \n return \"More than a handful!\"\n elif n == 101: \n return \"101 DALMATIONS!!!\"\n else: \n return \"Woah that's a lot of dogs!\" \n", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n if n < 11:\n return dogs[0]\n elif n > 11 and n < 52:\n return dogs[1]\n elif n > 50 and n < 101:\n return dogs[2]\n elif n == 101:\n return dogs[3]", "def how_many_dalmatians(n):\n return \"Hardly any\" if n <= 10 else \"More than a handful!\" if n <= 50 else \"Woah that's a lot of dogs!\" if n < 101 else \"101 DALMATIONS!!!\"", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n if n <= 10: return dogs[0]\n if 10 < n <= 50: return dogs[1]\n if 50 < n <= 100: return dogs[2]\n else: return dogs[3]", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n if number <= 10:\n respond = dogs[0]\n else:\n if number <= 50: \n respond = dogs[1]\n else: \n respond = dogs[2] \n if number == 101: \n respond = dogs[3] \n return respond", "def how_many_dalmatians(n):\n a = (\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\")\n return a[0] if n <= 10 else a[1] if n <= 50 else a[3] if n == 101 else a[2]", "def how_many_dalmatians(n):\n if n<=10:\n return \"Hardly any\"\n elif n>10 and n<=50:\n return \"More than a handful!\"\n elif n>50 and n<=100:\n return \"Woah that's a lot of dogs!\"\n else:\n return \"101 DALMATIONS!!!\"", "def how_many_dalmatians(n):\n d=[\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n return d[0] if n <= 10 else d[1] if n <= 50 else d[2] if n < 101 else d[3] \n", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n if n <= 10:\n respond = dogs[0] \n elif n <= 50:\n respond = dogs[1]\n else:\n if n == 101:\n respond = dogs[3]\n else:\n respond = dogs[2]\n return respond", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n response = ''\n if n == 101:\n response = dogs[3]\n elif n <= 10:\n response = dogs[0]\n elif n <= 50:\n response = dogs[1]\n else:\n return dogs[2]\n return response\n", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if number <= 10 :\n respond = dogs[0]\n elif number <= 50 :\n respond = dogs[1]\n elif number <= 101 :\n respond = dogs[2]\n if number == 101 :\n respond = dogs[3]\n \n return respond", "def how_many_dalmatians(n):\n dogs = ['Hardly any', 'More than a handful!', 'Woah that\\'s a lot of dogs!', '101 DALMATIONS!!!']\n if n <= 10:\n return dogs[0]\n elif n <= 50:\n return dogs[1]\n elif n == 101:\n return dogs[3]\n else:\n return dogs[2]", "def how_many_dalmatians(n):\n if n<=10:\n return 'Hardly any'\n elif n<=50:\n return \"More than a handful!\"\n else:\n if n==101:\n return \"101 DALMATIONS!!!\"\n else:\n return \"Woah that's a lot of dogs!\"", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n\n \n if n <= 10:\n ans = dogs[0]\n elif n <= 50:\n ans = dogs[1]\n elif n == 101:\n ans = dogs[3]\n else:\n ans = dogs[2]\n return ans", "def how_many_dalmatians(n):\n return \"Hardly any\" if n <= 10 else \"More than a handful!\" if n <= 50 else \"Woah that's a lot of dogs!\" if n <= 100 else \"101 DALMATIONS!!!\" ", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n return dogs[0] if n <= 10 else (dogs[1] if 10 < n <=50 else (dogs[3] if n == 101 else dogs[2]))", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n result = \"\"\n if n <= 10:\n result = dogs[0]\n elif (n <= 50):\n result = dogs[1] \n elif n == 101:\n result = dogs[3]\n else:\n result = dogs[2]\n \n return result", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if n == 101:\n return dogs[3]\n elif n <= 10:\n return dogs[0] \n elif n <= 50 and n > 10:\n return dogs[1]\n else:\n return dogs[2]\n \n", "def how_many_dalmatians(n):\n dogs= [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n \n if n <= 10:\n return dogs[0]\n elif n <= 50:\n return dogs[1]\n elif n == 101:\n return dogs[3]\n elif n <= 100:\n return dogs[2]\n return None", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n if n <= 10: \n\n return dogs[0] \n\n elif n <= 50: \n\n return dogs[1] \n \n if n == 101: \n \n return dogs[3] \n \n else: \n \n return dogs[2]\n \n", "def how_many_dalmatians(n):\n if n <= 10:\n return \"Hardly any\"\n if n <= 50:\n return \"More than a handful!\"\n if n <= 100:\n return \"Woah that's a lot of dogs!\"\n if n == 101:\n return \"101 DALMATIONS!!!\"\n\n", "def how_many_dalmatians(n):\n dogs= [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if 1<n<11:\n return dogs[0]\n if 10<n<51:\n return dogs[1]\n if 51<n<101:\n return dogs[2]\n if n == 101:\n return dogs[3]\n", "def how_many_dalmatians(n):\n return [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \n \"101 DALMATIONS!!!\"][int(n>10) + int(n>50) + int(n==101)]", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n if number <= 10: \n return dogs[0]\n elif number <= 50:\n return dogs[1] \n elif number > 100:\n return dogs[3]\n elif number > 50: \n return dogs[2]", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n# respond = if n <= 10 then dogs[0] else if (number <= 50 then dogs[1] else (number = 101 dogs[3] else dogs[2]\n \n if n <= 10: return dogs[0]\n elif n <= 50: return dogs[1]\n elif n == 101: return dogs[3]\n else: return dogs[2]\n \n# return respond\n", "def how_many_dalmatians(n):\n dogs = {\n n <= 10: \"Hardly any\", \n 10 < n <= 50: \"More than a handful!\", \n n == 101: \"101 DALMATIONS!!!\"\n }\n return dogs.get(True, \"Woah that's a lot of dogs!\")\n", "def how_many_dalmatians(n):\n msg = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n idx = {\n 0: n <= 10,\n 1: 10 < n <= 50,\n 2: 50 < n <= 100,\n 3: n >= 101\n }\n for k, v in idx.items():\n if v:\n return msg[k]", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n #respond = dogs[0] if number <= 10 else if (number <= 50 dogs[1] else (number = 101 dogs[3] else dogs[2]\n \n if number <= 10:\n return dogs[0]\n elif number <= 50:\n return dogs[1]\n elif number < 101:\n return dogs[2]\n else:\n return dogs[3]\n \n \n#return respond\n", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if n <= 10:\n respond = dogs[0]\n return respond\n elif n<= 50:\n respond = dogs[1]\n return respond\n if n < 101:\n respond = dogs[2]\n return respond\n elif n == 101:\n respond = dogs[3]\n return respond", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n respond = \"\"\n if n <= 10:\n respond = dogs[0]\n elif n <= 50:\n respond = dogs[1]\n else:\n if n == 101:\n respond = dogs[3]\n else:\n respond = dogs[2]\n return respond", "def how_many_dalmatians(n):\n respond = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n if n <= 10 :\n return respond[0]\n elif n <= 50:\n return respond[1]\n elif n <= 100:\n return respond[2]\n elif n > 100:\n return respond[3]\n \n", "def how_many_dalmatians(n):\n if n <= 10:\n return \"Hardly any\"\n elif 10 < n <= 50:\n return \"More than a handful!\"\n elif 50 < n < 101:\n return \"Woah that's a lot of dogs!\"\n elif n == 101:\n return \"101 DALMATIONS!!!\"\n \n \n\n", "dogs=[\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n\n\nhow_many_dalmatians=lambda n: dogs[0] if n<=10 else dogs[1] if n<=50 else dogs[3] if n==101 else dogs[2]", "def how_many_dalmatians(n):\n dogs=[\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n if n<=10:\n r=dogs[0]\n \n elif n>10 and n<=50:\n r=dogs[1]\n\n elif n==101:\n r=dogs[3]\n else:\n r=dogs[2]\n \n return r", "def how_many_dalmatians(n):\n if n == 101:\n return '101 DALMATIONS!!!'\n elif n in range(11):\n return 'Hardly any'\n elif n in range(11, 51):\n return 'More than a handful!'\n else:\n return 'Woah that\\'s a lot of dogs!'", "def how_many_dalmatians(n):\n if n == 101:\n return \"101 DALMATIONS!!!\"\n elif 51<= n <=100:\n return \"Woah that's a lot of dogs!\"\n elif n <= 10:\n return \"Hardly any\"\n else:\n return \"More than a handful!\"", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n if n <= 10:\n return dogs[0]\n if n > 10 and n <= 50:\n return dogs[1]\n if n > 50 and n <= 100:\n return dogs[2]\n if n == 101:\n return dogs[3]\n else:\n return dogs[2]\n\n\n\n", "def how_many_dalmatians(n):\n return \"101 DALMATIONS!!!\" if n == 101 else \"Hardly any\" if n <= 10 else \"More than a handful!\" if n <= 50 else \"Woah that's a lot of dogs!\"\n", "def how_many_dalmatians(n):\n dogs=[\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n \n if n<= 10:\n r=dogs[0]\n return r\n elif n <= 50:\n r=dogs[1]\n return r\n elif n==101:\n r=dogs[3]\n return r\n else: \n r=dogs[2]\n return r\n \n", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if number <= 10: return dogs[0] \n elif number <= 50: return dogs[1] \n elif number < 101: return dogs[2] \n elif number >= 101: return dogs[3]", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n if number == 101:\n return dogs[3]\n if number <= 10:\n return dogs[0] \n if number <= 50:\n return dogs[1] \n if number > 50:\n return dogs[2] \n", "def how_many_dalmatians(number):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n #respond = if number <= 10 then dogs[0] else if (number <= 50 then dogs[1] else (number = 101 dogs[3] else dogs[2]\n \n if number <= 10:\n respond = dogs[0]\n elif number <= 50:\n respond = dogs[1]\n elif number == 101:\n respond = dogs[3]\n else:\n respond = dogs[2]\n \n return respond", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if n <= 10:\n return dogs[0]\n elif n <= 50:\n return dogs[1]\n elif n > 50 and n <= 100:\n return dogs[2]\n else:\n return dogs[3]", "def how_many_dalmatians(n):\n if n <=10:\n return \"Hardly any\"\n elif n<=50:\n return \"More than a handful!\"\n elif n == 101:\n return \"101 DALMATIONS!!!\"\n elif n>50 and n<101:\n return \"Woah that's a lot of dogs!\"", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n if n <= 10:\n return dogs[0]\n elif n <= 50:\n return dogs[1]\n elif n <= 100:\n return dogs[2]\n elif n == 101:\n return dogs[3]\n \n \n #respond = if number <= 10 then dogs[0] else if (number <= 50 then dogs[1] else (number = 101 dogs[3] else dogs[2]\n", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"];\n\n if n == 101:\n return dogs[3]\n elif n < 101 and n > 50:\n return dogs[2]\n elif n <= 50 and n > 10:\n return dogs[1]\n else:\n return dogs[0]", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n \n if n <= 10:\n return dogs[0]\n if n <= 50:\n return dogs[1]\n if n <= 100:\n return dogs[2]\n if n <= 101:\n return dogs[3]"] | {"fn_name": "how_many_dalmatians", "inputs": [[26], [8], [14], [80], [100], [50], [10], [101]], "outputs": [["More than a handful!"], ["Hardly any"], ["More than a handful!"], ["Woah that's a lot of dogs!"], ["Woah that's a lot of dogs!"], ["More than a handful!"], ["Hardly any"], ["101 DALMATIONS!!!"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 33,352 |
def how_many_dalmatians(n):
|
8be5c701e43b92742c84eec2619bd96e | UNKNOWN | Raj was to move up through a pattern of stairs of a given number **(n)**. Help him to get to the top using the function **stairs**.
##Keep in mind :
* If **n<1** then return ' ' .
* There are a lot of spaces before the stair starts except for **pattern(1)**
##Examples :
pattern(1)
1 1
pattern(6)
1 1
1 2 2 1
1 2 3 3 2 1
1 2 3 4 4 3 2 1
1 2 3 4 5 5 4 3 2 1
1 2 3 4 5 6 6 5 4 3 2 1
pattern(12)
1 1
1 2 2 1
1 2 3 3 2 1
1 2 3 4 4 3 2 1
1 2 3 4 5 5 4 3 2 1
1 2 3 4 5 6 6 5 4 3 2 1
1 2 3 4 5 6 7 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 0 0 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 0 1 1 0 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 0 1 2 2 1 0 9 8 7 6 5 4 3 2 1 | ["def stairs(n):\n return \"\\n\".join(step(i).rjust(4 * n - 1) for i in range(1, n+1))\n\n\ndef step(n):\n h = \" \".join(str(i % 10) for i in range(1, n+1))\n return f\"{h} {h[::-1]}\"", "from itertools import chain\n\ndef stairs(n):\n if n < 1:\n return \" \"\n w = 4 * n - 1\n xs = [str(i % 10) for i in chain(range(1, n + 1), range(n, 0, -1))]\n return \"\\n\".join(\" \".join(xs[:i] + xs[-i:]).rjust(w) for i in range(1, n + 1))", "from itertools import chain\n\ngen = lambda x: chain(range(1, x+1), range(x, 0, -1))\nconcat = lambda x: ' '.join(str(y%10) for y in gen(x))\npadding = lambda size: lambda x: f\"{concat(x): >{size}}\"\n\ndef stairs(n):\n return '\\n'.join(map(padding(4*n-1), range(1, n+1)))", "def stairs(n):\n return '\\n'.join(' '.join([str(j%10) for j in range(1, i+1)] + [str(j%10) for j in range(i, 0, -1)]).rjust(4*n-1) for i in range(1, n+1))", "def stairs(n):\n a = [' '.join([str(e)[-1] for e in range(1, i+2)] + [str(i - e + 1)[-1] for e in range(i+1)]) for i in range(n)]\n return '\\n'.join(e.rjust(4 * n - 1) for e in a)", "def stairs(n):\n l, s = [], []\n for i in range(1, n+1):\n l.append(str(i % 10))\n s.append(' '.join(l + l[::-1]))\n return '\\n'.join(r.rjust(len(s[-1])) for r in s)", "def create_line(number):\n nums_for_line = [num if num < 10 else num % 10 for num in range(1, number + 1)]\n result = nums_for_line + nums_for_line[::-1]\n return ' '.join(map(str, result))\n\ndef stairs(number):\n lines = [create_line(num) for num in range(1, number + 1)]\n max_length = number * 4 - 1\n return '\\n'.join(line.rjust(max_length) for line in lines)", "def stairs(n):\n c,r = '1 2 3 4 5 6 7 8 9 0'.split(),[]\n for i in range(n):\n temp = [c[j%10] for j in range(i+1)]\n r.append((\" \".join(temp) + \" \" + \" \".join(temp[::-1])).rjust(n*4-1))\n return \"\\n\".join(r)", "def stairs(n):\n r = lambda n: [str(i % 10) for i in range(1, n + 1)]\n up_down = lambda n: r(n) + r(n)[::-1]\n steps = [\" \".join(up_down(i)) for i in range(1, n + 1)]\n l = len(steps[-1])\n return \"\\n\".join([r.rjust(l) for r in steps])\n"] | {"fn_name": "stairs", "inputs": [[3], [7], [10], [16]], "outputs": [[" 1 1\n 1 2 2 1\n1 2 3 3 2 1"], [" 1 1\n 1 2 2 1\n 1 2 3 3 2 1\n 1 2 3 4 4 3 2 1\n 1 2 3 4 5 5 4 3 2 1\n 1 2 3 4 5 6 6 5 4 3 2 1\n1 2 3 4 5 6 7 7 6 5 4 3 2 1"], [" 1 1\n 1 2 2 1\n 1 2 3 3 2 1\n 1 2 3 4 4 3 2 1\n 1 2 3 4 5 5 4 3 2 1\n 1 2 3 4 5 6 6 5 4 3 2 1\n 1 2 3 4 5 6 7 7 6 5 4 3 2 1\n 1 2 3 4 5 6 7 8 8 7 6 5 4 3 2 1\n 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8 9 0 0 9 8 7 6 5 4 3 2 1"], [" 1 1\n 1 2 2 1\n 1 2 3 3 2 1\n 1 2 3 4 4 3 2 1\n 1 2 3 4 5 5 4 3 2 1\n 1 2 3 4 5 6 6 5 4 3 2 1\n 1 2 3 4 5 6 7 7 6 5 4 3 2 1\n 1 2 3 4 5 6 7 8 8 7 6 5 4 3 2 1\n 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1\n 1 2 3 4 5 6 7 8 9 0 0 9 8 7 6 5 4 3 2 1\n 1 2 3 4 5 6 7 8 9 0 1 1 0 9 8 7 6 5 4 3 2 1\n 1 2 3 4 5 6 7 8 9 0 1 2 2 1 0 9 8 7 6 5 4 3 2 1\n 1 2 3 4 5 6 7 8 9 0 1 2 3 3 2 1 0 9 8 7 6 5 4 3 2 1\n 1 2 3 4 5 6 7 8 9 0 1 2 3 4 4 3 2 1 0 9 8 7 6 5 4 3 2 1\n 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1\n1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,181 |
def stairs(n):
|
af4b7684cccea1afcb6fc041bace8b8a | UNKNOWN | In case you might be unlucky enough not to know the best dark fantasy franchise ever, Berserk tells the story of a man that, hating gratuitous violence, decided to become a mercenary (thus one who sells violence, no gratuity anymore!) and starts an epic struggle against apparently unsormountable odds, unsure if he really wants to pursue a path of vengeance or to try to focus on his remaining and new loved ones.
*The main character, Gatsu,ready to start yet another Tuesday*
Ok, the first part was a joke, but you can read more about the tale of the main character, a "Byronic hero" for wikipedia, in other pages like [here](https://en.wikipedia.org/wiki/Berserk_(manga%29).
After an insanely long waiting, finally fans got the [follow up](https://en.wikipedia.org/wiki/Berserk_(2016_TV_series%29) of [the acclaimed 90s show](https://en.wikipedia.org/wiki/Berserk_(1997_TV_series%29).
Regrettably, while the first adaption was considerably shortened, the latter was quite butchered, missing entire parts, like the "lost children" arc, but that would have actual children butchered and thus you might get why it was decided to skip it. And fan could somehow cope with it, if it was not for the very meager use of CG (Computer Graphic).
Luckily, I am a simple man and every time Gatsu swings his humongous sword, that is enough to make me forget about everything else.
Your goal is to build a Berserk Rater function that takes an array/list of events of each episode (as strings) and calculate a rating based on that: you start with a score of 0 (hey, it's a work from Miura-sensei, I have great expectations to satisfy!) and you have to:
* subtract 2 each time "CG" is mentioned (case insensitive);
* add 5 every time "Clang" is mentioned (case insensitive);
* if a sentence has both "Clang" and "CG", "Clang" wins (add 5);
* remove 1 every time neither is mentioned (I get bored easily, you know, particularly if you remove important parts and keep side character whining for half an episode).
You should then return a string, structured like this:
* if the finale score is less than 0: "worstest episode ever";
* if the score is between 0 and 10: the score itself, as a string;
* if the finale score is more than 10: "bestest episode ever".
Examples:
```python
berserk_rater(["is this the CG from a P2 game?","Hell, no! Even the CG in the Dreamcast game was more fluid than this!","Well, at least Gatsu does his clang even against a mere rabbit", "Hey, Cosette was not in this part of the story!", "Ops, everybody dead again! Well, how boring..."])=="worstest episode ever"
berserk_rater(["missing the Count arc","lame CG","Gatsu doing its clang against a few henchmen", "even more lame CG"])=="0"
berserk_rater(["Farnese unable to shut the fuck up","awful CG dogs assaulting everybody", "Gatsu clanging the pig apostle!"])=="2"
berserk_rater(["spirits of the dead attacking Gatsu and getting clanged for good", "but the wheel spirits where really made with bad CG", "Isidoro trying to steal the dragon Slayer and getting a sort of clang on his face", "Gatsu vs. the possessed horse: clang!", "Farnese whining again...","a shame the episode ends with that scrappy CG"])=="10"
berserk_rater(["Holy chain knights being dicks", "Serpico almost getting clanged by Gatsu, but without losing his composure","lame CG","Luka getting kicked","Gatsu going clang against the angels", "Gatsu clanging vs Mozgus, big time!"])=="bestest episode ever"
```
Extra cookies if you manage to solve it all using a `reduce/inject` approach.
Oh, and in case you might want a taste of clang to fully understand it, [click](https://www.youtube.com/watch?v=IZgxH8MJFno) (one of the least gory samples I managed to find). | ["def berserk_rater(synopsis):\n n = sum([score(s.upper()) for s in synopsis])\n return 'worstest episode ever' if n < 0 else 'bestest episode ever' if n > 10 else str(n)\n \ndef score(s):\n return 5 if 'CLANG' in s else -2 if 'CG' in s else -1", "import re\n\nCG = re.compile(r\"\\bcg\\b\", flags=re.I)\nCLANG = re.compile(r\"\\bclang\", flags=re.I)\n\n\ndef berserk_rater(synopsis):\n score = sum(\n (5 if CLANG.search(line) else (-2 if CG.search(line) else -1))\n for line in synopsis\n )\n return (\n \"worstest episode ever\"\n if score < 0\n else \"bestest episode ever\"\n if score > 10\n else str(score)\n )", "from functools import reduce; berserk_rater=lambda s: (lambda score: \"worstest episode ever\" if score<0 else \"bestest episode ever\" if score>10 else str(score))(reduce(lambda a,b: a+(lambda b: 5 if \"clang\" in b else -2 if \"cg\" in b else -1)(b.lower()),s,0))", "def berserk_rater(synopsis):\n ball = 0\n ball = sum([ball + 5 if \"clang\" in i.lower() else ball - 2 if \"cg\" in i.lower() else ball - 1 for i in synopsis])\n return \"worstest episode ever\" if ball < 0 else str(ball) if ball <=10 else \"bestest episode ever\"", "berserk_rater = lambda x: (lambda x: \"worstest episode ever\" if x < 0 else \"bestest episode ever\" if x > 10 else str(x))(sum(map(lambda x: (lambda x: 5 if \"clang\" in x else -2 if \"cg\" in x else -1)(x.lower()), x)))", "def berserk_rater(synopsis):\n scores = []\n for sentence in synopsis:\n # Remove punctuation\n s = ''.join([c for c in sentence.lower() if c == ' ' or c.isalpha() or c.isdigit()])\n words = s.split()\n # Count the appropriate words\n cg = words.count('cg')\n clang = sum(1 for w in words if w.startswith('clang'))\n # Decide sentence scoore\n if clang:\n scores.append(5)\n elif cg:\n scores.append(-2)\n else:\n scores.append(-1)\n \n score = sum(scores)\n # Decode overall score\n if score < 0:\n return 'worstest episode ever'\n if score > 10:\n return 'bestest episode ever'\n return str(score)", "def berserk_rater(a):\n r = 0\n for s in map(str.lower,a):\n if 'clang' in s: r += 5\n elif 'cg' in s: r -=2\n else: r -= 1 \n return 'worstest episode ever' if r<0 else str(r) if 0<=r<=10 else 'bestest episode ever'", "def berserk_rater(l):\n score = 0\n for i in l:\n if 'cg' in i.lower() and 'clang' in i.lower(): score += 5\n elif 'clang' in i.lower(): score += 5\n elif 'cg' in i.lower(): score -= 2\n else: score -= 1\n \n if score < 0: return 'worstest episode ever'\n elif score > 10: return 'bestest episode ever'\n else: return str(score)", "def berserk_rater(synopsis):\n s=0\n for sentence in synopsis:\n if 'clang' in sentence.lower():\n s+=5\n elif 'cg' in sentence.lower():\n s-=2\n else:\n s-=1\n if s<0:\n return 'worstest episode ever'\n elif s>10:\n return 'bestest episode ever'\n else:\n return str(s)"] | {"fn_name": "berserk_rater", "inputs": [[["is this the CG from a P2 game?", "Hell, no! Even the CG in the Dreamcast game was more fluid than this!", "Well, at least Gatsu does his clang even against a mere rabbit", "Hey, Cosette was not in this part of the story!", "Ops, everybody dead again! Well, how boring..."]], [["missing the Count arc", "lame CG", "Gatsu doing its clang against a few henchmen", "even more lame CG"]], [["Farnese unable to shut the fuck up", "awful CG dogs assaulting everybody", "Gatsu clanging the pig apostle!"]], [["spirits of the dead attacking Gatsu and getting clanged for good", "but the wheel spirits where really made with bad CG", "Isidoro trying to steal the dragon Slayer and getting a sort of clang on his face", "Gatsu vs. the possessed horse: clang!", "Farnese whining again...", "a shame the episode ends with that scrappy CG"]], [["Holy chain knights being dicks", "Serpico almost getting clanged by Gatsu, but without losing his composure", "lame CG", "Luka getting kicked", "Gatsu going clang against the angels", "Gatsu clanging vs Mozgus, big time!"]]], "outputs": [["worstest episode ever"], ["0"], ["2"], ["10"], ["bestest episode ever"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,205 |
def berserk_rater(synopsis):
|
ac5f649ee683daf445c4b23754c8a3b1 | UNKNOWN | Write a function that checks the braces status in a string, and return `True` if all braces are properly closed, or `False` otherwise. Available types of brackets: `()`, `[]`, `{}`.
**Please note, you need to write this function without using regex!**
## Examples
```python
'([[some](){text}here]...)' => True
'{([])}' => True
'()[]{}()' => True
'(...[]...{(..())}[abc]())' => True
'1239(df){' => False
'[()])' => False
')12[x]34(' => False
```
Don't forget to rate this kata! Thanks :) | ["brackets = {\"}\":\"{\",\"]\":\"[\",\")\":\"(\"}\n\ndef braces_status(s):\n stack = []\n \n for c in s:\n if c in \"[({\":\n stack.append(c)\n elif c in \"])}\":\n if not stack or stack.pop() != brackets[c]:\n return False\n \n return not stack", "def braces_status(string):\n s = \"\".join([b for b in string if b in '(){}[]'])\n while any(b in s for b in ['()','{}','[]']):\n s = s.replace('()','').replace('{}','').replace('[]','')\n return True if len(s) == 0 else False", "parens = dict([')(', '][', '}{'])\nopens = set(parens.values())\n\ndef braces_status(s):\n stack = []\n for c in s:\n if c in opens:\n stack.append(c)\n elif c in parens:\n if not (stack and stack.pop() == parens[c]):\n return False\n return not stack", "def braces_status(string):\n stack = []\n corresp = {')':'(', '}':'{', ']':'['}\n for c in (s for s in string if s in \"()[]{}\"):\n if c in '([{': \n stack.append(c)\n elif not stack or stack.pop() != corresp[c]:\n return False\n return not stack", "def braces_status(s):\n paren = {')': '(', ']': '[', '}': '{'}\n opened = []\n for c in s:\n if c in paren.values():\n opened.append(ord(c))\n elif c in paren:\n if not opened or opened.pop() != ord(paren[c]):\n return False\n return not opened", "def braces_status(string):\n s = \"\".join(list(filter(lambda ch: ch in \"{[()]}\",list(string))))\n while '{}' in s or '()' in s or '[]' in s:\n s=s.replace('{}','')\n s=s.replace('[]','')\n s=s.replace('()','')\n return s==''", "def braces_status(string):\n if \"(]\" in string or \"(}\" in string or \"[)\" in string or \"[}\" in string or \"{)\" in string or \"{]\" in string or string.count(\"(\")!= string.count(\")\") or string.count(\"[\")!= string.count(\"]\") or string.count(\"{\")!= string.count(\"}\"):\n return False\n else:\n return True", "def braces_status(s):\n matching = {\"}\":\"{\",\"]\":\"[\",\")\":\"(\"}\n stack = []\n for c in s:\n if c in \"[({\":\n stack.append(c)\n elif c in matching and (not stack or stack.pop() != matching[c]):\n return False\n return not stack", "def braces_status(s):\n l = []\n d = {'(': ')', '{': '}', '[': ']'}\n for x in s:\n if x in '({[':\n l.append(d[x])\n elif x in ')}]':\n if not l or not x == l.pop():\n return 0\n return not l", "def braces_status(s):\n order = [\"X\"]\n for i in s:\n if i in \"({[\" : order.append(\")}]\"[\"({[\".index(i)])\n elif i in \")}]\":\n if order.pop()!=i : return 0\n return len(order)==1"] | {"fn_name": "braces_status", "inputs": [["[()]"], ["{[]}"], ["{[()]}"], ["([)]"], ["([[some](){text}here]...)"], ["}"], ["[()]]"], ["[()]{("], ["()[]{}()"], ["[[[["]], "outputs": [[true], [true], [true], [false], [true], [false], [false], [false], [true], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,866 |
def braces_status(s):
|
b3580ee09b70b1cb56d86a1465d1e5c4 | UNKNOWN | Triangular numbers count the number of objects that can form an equilateral triangle. The nth triangular number forms an equilateral triangle with n dots on each side (including the vertices).
Here is a graphic example for the triangular numbers of 1 to 5:
```
n=1: triangular number: 1
*
n=2: triangular number: 3
*
* *
n=3: triangular number: 6
*
* *
* * *
n=4: triangular number: 10
*
* *
* * *
* * * *
n=5: triangular number: 15
*
* *
* * *
* * * *
* * * * *
```
Your task is to implement a function ```triangular_range(start, stop)``` that returns a dictionary of all numbers as keys and the belonging triangular numbers as values, where the triangular number is in the range start, stop (including start and stop).
For example, ```triangular_range(1, 3)``` should return ```{1: 1, 2: 3}``` and ```triangular_range(5, 16)``` should return ```{3: 6, 4: 10, 5: 15}```. | ["def triangular_range(start, stop):\n return {i:i*(i+1)/2 for i in range(stop) if start <= i*(i+1)/2 <= stop}\n", "from math import ceil\n\ndef root(n): return ((1+8*n)**.5-1)/2\n\ndef triangular_range(s,e):\n return {i: -~i*i>>1 for i in range(ceil(root(s)), int(root(e))+1)}", "def triangular_range(start, stop):\n n = t = 1\n result = {}\n while t <= stop:\n if t >= start:\n result[n] = t\n n += 1\n t = n * (n + 1) // 2\n return result\n", "from math import ceil, floor, sqrt\n\n\ndef triangular(n):\n return n * (n + 1) / 2\n\n\ndef quadratic_root(t):\n return (-1 + sqrt(1 + 8 * t)) / 2\n\n\ndef triangular_range(start, stop):\n first = int(ceil(quadratic_root(start)))\n last = int(floor(quadratic_root(stop)))\n\n result = {}\n t = triangular(first)\n for n in range(first, last + 1):\n result[n] = t\n t += n + 1\n\n return result\n", "def triangular_range(start, stop):\n startn = int(math.ceil(-0.5 + math.sqrt(0.25 + 2 * start)))\n stopn = int(math.floor(-0.5 + math.sqrt(0.25 + 2 * stop)))\n return dict((n, n * (n + 1) / 2) for n in range(startn, stopn + 1))", "def tri(number):\n return int(number * (number+1) / 2)\n \ndef quadsol(number):\n return int((math.sqrt(8*number + 1) -1) / 2)\n\ndef triangular_range(start, stop):\n return {x:tri(x) for x in range(quadsol(start), quadsol(stop)+1) if tri(x) in range(start, stop+1)}", "from bisect import bisect_left, bisect_right\nmemo = [0, 1]\n\ndef triangular_range(start, stop):\n while memo[-1] <= stop: memo.append(memo[-1] + len(memo))\n return {i:memo[i] for i in range(bisect_left(memo, start), bisect_right(memo, stop))}", "from math import sqrt\n\ndef triangular_range(start, stop):\n def get_n(sum):\n a = int(round((sqrt(8 * sum) - 1) / 2, 0))\n return a\n\n return {n: int(n*(n+1)/2) for n in range(get_n(start), get_n(stop) + 1) if start <= int(n*(n+1)/2) <= stop}", "def triangular_range(start, stop):\n \n return {n: n * (n + 1) // 2 for n in range(int(start ** .5), stop) if start <= n * (n + 1) // 2 <= stop}", "def triangular_range(start, stop):\n dict = {}\n for trial in range(1, stop + 1):\n triangle_num = sum(range(trial + 1))\n if start <= triangle_num <= stop:\n dict[trial] = triangle_num\n return dict\n\n"] | {"fn_name": "triangular_range", "inputs": [[1, 3], [5, 16]], "outputs": [[{"1": 1, "2": 3}], [{"3": 6, "4": 10, "5": 15}]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,369 |
def triangular_range(start, stop):
|
9a8fadf0cca8b3438142c02c62b80886 | UNKNOWN | In Spanish, the conjugated verb changes by adding suffixes and according to the person we're talking about. There's something similar in English when we talk about "She", "He"or "It" (3rd person singular):
With the verb "run":
**He / She / It runS**
As you can see, the rule (at least with regular verbs) is to add the suffix "-s" in the 3rd person singular. In Spanish it works the same way but we need to remove the **infinitive suffix** and add a specific suffix to all the others persons (I, You, He/She/It, We, You, They).
Verbs in Spanish and the infinitive suffix.
--
In Spanish we assume a verb is on its infitive form when it has one of the infinitives suffixes (**AR**, **ER** or **IR**) at the end:
- Com**er** -> to eat
- Camin**ar** -> to walk
- Viv**ir** -> to live
## How to conjugate
For conjugating in Spanish, we need to remove the infinitive suffix (**ar**, **er** *or* **ir**) and add the personal suffixes corresponding to the person we're talking to. In this kata we'll conjugate the verbs to its **presente indicativo** (simple present) form.
Personal suffixes
--
The personal suffixes changes depending of the **Infinitive suffix**.
If the infinitive suffix is **AR** the personal suffixes are:
- first person singular (Yo / I): -**o**
- second person singular (Tú / You): -**as**
- third person singular (Él, Ella / He, She): -**a**
- first person plural (Nosotros / We): -**amos**
- second person plural (Vosotros / You): -**áis**
- third person plural (Ellos / They): -**an**
If the infinitive suffix is **ER**:
- first person singular (Yo / I): -**o**
- second person singular (Tú / You): -**es**
- third person singular (Él, Ella / He, She): -**e**
- first person plural (Nosotros / We): -**emos**
- second person plural (Vosotros / You): -**éis**
- third person plural (Ellos / They): -**en**
If the infinitive suffix is **IR**:
- first person singular (Yo / I): -**o**
- second person singular (Tú / You): -**es**
- third person singular (Él, Ella / He, She): -**e**
- first person plural (Nosotros / We): -**imos**
- second person plural (Vosotros / You): -**ís**
- third person plural (Ellos / They): -**en**
## Conjugating
Steps for conjugating:
1. Remove the infinitive suffix (ar, er, ir)
2. And add the personal suffixes
- Example: verb **Caminar** (to walk)
- Camin**o** (I walk)
- Camin**as** (You walk)
- Camin**a** (He walks)
- Camin**amos** (We walk)
- Camin**áis** (You guys walk)
- Camin**an** (They walk)
- Example: verb **Comer** (to eat):
- Com**o** (I eat)
- Com**es** (You eat)
- Com**e** (He, She eats)
- Com**emos** (We eat)
- Com**éis** (You guys eat)
- Com**en** (They eat)
- Example: verb **Vivir** (to live):
- Viv**o** (I live)
- Viv**es** (You live)
- Viv**e** (He, She lives)
- Viv**imos** (We live)
- Viv**ís** (You guys live)
- Viv**en** (They live)
## Your Task
You need to write a function called **conjugate** which will return an object with a spanish verb conjugated. The object must look like this:
```
{
"comer": [
"como",
"comes",
"come",
"comemos",
"coméis",
"comen"
]
}
```
Where the key is the verb in its original form (infinitive form) and its value will be an array with the conjugations.
Another example:
```
{
"vivir": [
"vivo",
"vives",
"vive",
"vivimos",
"vivís",
"viven"
]
}
```
## Notes:
1. The conjugations must be in this order:
```
{
verb: [
"first person singular",
"second person singular",
"third person singular",
"first person plural",
"second person plural",
"third person plural"
]
}
```
2.Don't use `JSON.stringify(obj, null, 2)` because the "presentation" of the object isn't important.
3.Don't use accents in Python version
**Buena suerte!**
--- | ["SUFFIXES = {'a': ['o', 'as', 'a', 'amos', 'ais', 'an'],\n 'e': ['o', 'es', 'e', 'emos', 'eis', 'en'],\n 'i': ['o', 'es', 'e', 'imos', 'is', 'en']}\n\ndef conjugate(verb):\n return {verb: [verb[:-2] + s for s in SUFFIXES[verb[-2]]]}", "def conjugate(verb):\n d = {'ar': ['o', 'as', 'a', 'amos', 'ais', 'an'],\n 'er': ['o', 'es', 'e', 'emos', 'eis', 'en'],\n 'ir': ['o', 'es', 'e', 'imos', 'is', 'en']}\n return {verb: [verb[:-2] + v for v in d[verb[-2:]]]}", "personal_suffixes = {\n \"ar\": [\"o\", \"as\", \"a\", \"amos\", \"ais\", \"an\"],\n \"er\": [\"o\", \"es\", \"e\", \"emos\", \"eis\", \"en\"],\n \"ir\": [\"o\", \"es\", \"e\", \"imos\", \"is\", \"en\"],\n}\n\ndef conjugate(verb):\n base, group = verb[:-2], verb[-2:]\n suffixes = personal_suffixes[group]\n return {verb: [f\"{base}{suffix}\" for suffix in suffixes]}", "def conjugate(verb):\n root, oldSuffix = verb[:-2], verb[-2:]\n newSuffix = {\"ar\": [\"o\", \"as\", \"a\", \"amos\", \"ais\", \"an\"],\n \"er\": [\"o\", \"es\", \"e\", \"emos\", \"eis\", \"en\"],\n \"ir\": [\"o\", \"es\", \"e\", \"imos\", \"is\", \"en\"]}\n answer = {verb: []}\n for ns in newSuffix[oldSuffix]:\n answer[verb].append(root + ns)\n return answer", "def conjugate(verb):\n conj = {'ar':('o', 'as', 'a', 'amos', 'ais', 'an'),\n 'er':('o', 'es', 'e', 'emos', 'eis', 'en'),\n 'ir':('o', 'es', 'e', 'imos', 'is', 'en'),}\n return {verb : [verb[:-2] + c for c in conj[verb[-2:]]]}", "conjugators = {\n 'ar': ['o', 'as', 'a', 'amos', 'ais', 'an'],\n 'er': ['o', 'es', 'e', 'emos', 'eis', 'en'],\n 'ir': ['o', 'es', 'e', 'imos', 'is', 'en'],\n}\n\ndef conjugate(verb):\n root, suffix = verb[:-2], verb[-2:]\n cs = conjugators[suffix]\n return {verb: [root+c for c in cs]}", "def conjugate(verb):\n conjugation = verb[-2:]\n \n if conjugation == \"ar\":\n return { verb : [verb[:-2] + \"o\", verb[:-2] + \"as\", verb[:-2] + \"a\", verb[:-2] + \"amos\", verb[:-2] + \"ais\", verb[:-2] + \"an\"] }\n elif conjugation == \"er\":\n return { verb : [verb[:-2] + \"o\", verb[:-2] + \"es\", verb[:-2] + \"e\", verb[:-2] + \"emos\", verb[:-2] + \"eis\", verb[:-2] + \"en\"] }\n elif conjugation == \"ir\":\n return { verb : [verb[:-2] + \"o\", verb[:-2] + \"es\", verb[:-2] + \"e\", verb[:-2] + \"imos\", verb[:-2] + \"is\", verb[:-2] + \"en\"] }", "def conjugate(verb):\n base, infinitive_suffix = verb[:-2], verb[-2:]\n patterns = {'ar': ['o', 'as', 'a', 'amos', 'ais', 'an'], 'er': ['o', 'es', 'e', 'emos', 'eis', 'en'],\n 'ir': ['o', 'es', 'e', 'imos', 'is', 'en']}\n conjugations = [base+suffix for suffix in patterns[infinitive_suffix]]\n return {verb: conjugations}", "def conjugate(verb):\n i=0\n conj=\"\"\n while i<len(verb)-2:\n conj+=verb[i]\n i+=1\n arr=[]\n vow=verb[-2]\n arr.append(conj+\"o\")\n if vow==\"a\":\n arr.append(conj+\"as\")\n arr.append(conj+\"a\")\n else:\n arr.append(conj+\"es\")\n arr.append(conj+\"e\")\n if vow == \"a\":\n arr.append(conj+\"amos\")\n arr.append(conj+\"ais\")\n arr.append(conj+\"an\")\n elif vow == \"e\":\n arr.append(conj+\"emos\")\n arr.append(conj+\"eis\")\n arr.append(conj+\"en\")\n else:\n arr.append(conj+\"imos\")\n arr.append(conj+\"is\")\n arr.append(conj+\"en\")\n obj={verb:arr}\n return obj", "def conjugate(v):\n h=i=v[:-1]\n if h[-1]=='i':\n h=h[:-1]+'e'\n i=v[:-2]\n return {v:[v[:-2]+'o',h+'s',h,v[:-1]+'mos',i+'is',h+'n']}"] | {"fn_name": "conjugate", "inputs": [["caminar"], ["comer"], ["vivir"]], "outputs": [[{"caminar": ["camino", "caminas", "camina", "caminamos", "caminais", "caminan"]}], [{"comer": ["como", "comes", "come", "comemos", "comeis", "comen"]}], [{"vivir": ["vivo", "vives", "vive", "vivimos", "vivis", "viven"]}]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,722 |
def conjugate(verb):
|
b80cfa23776da5400348b33caa2ab877 | UNKNOWN | The first input array is the key to the correct answers to an exam, like ["a", "a", "b", "d"]. The second one contains a student's submitted answers.
The two arrays are not empty and are the same length. Return the score for this array of answers, giving +4 for each correct answer, -1 for each incorrect answer, and +0 for each blank answer, represented as an empty string (in C the space character is used).
If the score < 0, return 0.
For example:
```
checkExam(["a", "a", "b", "b"], ["a", "c", "b", "d"]) → 6
checkExam(["a", "a", "c", "b"], ["a", "a", "b", ""]) → 7
checkExam(["a", "a", "b", "c"], ["a", "a", "b", "c"]) → 16
checkExam(["b", "c", "b", "a"], ["", "a", "a", "c"]) → 0
``` | ["def check_exam(arr1, arr2):\n return max(0, sum(4 if a == b else -1 for a, b in zip(arr1, arr2) if b))", "def check_exam(arr1,arr2):\n score = 0\n for i in range(0,4):\n if arr1[i] == arr2[i]:\n score += 4\n elif arr1[i] == \"\" or arr2[i] == \"\":\n score += 0\n else: \n score -= 1\n \n return score if score >= 0 else 0\n \n", "def check_exam(arr1,arr2):\n score=0\n for i in range(len(arr1)):\n if arr2[i]!='':\n if arr2[i]==arr1[i]:\n score=score+4\n else:\n score=score-1\n return (score if score>0 else 0)", "def check_exam(arr1,arr2):\n score = 0\n for i in range(len(arr1)):\n if arr1[i] == arr2[i]:\n score += 4\n elif arr1[i] != arr2[i] and arr2[i] != '':\n score -= 1\n return score if score > 0 else 0\n \n", "NOTATION = {True: 4, False: -1}\n\ndef check_exam(ref, ans):\n return max(0, sum( NOTATION[r==a] for r,a in zip(ref,ans) if a) )", "def check_exam(arr1,arr2):\n k=0; #a place in memory where we shall store the points\n for x in range(len(arr1)): #lets check every answer in the array\n if arr2[x]!='': #and if the answer is not empty\n if arr1[x]==arr2[x]: k+=4 #we will give +4 point for the correct answer\n else: k-=1 #and -1 for any other (incorect) answers\n if k<1: return 0 #if we have 0 ot negative points we should return just zero\n #so we dont embarice further the poor students\n return k", "def check_exam(answers, solutions):\n return max( sum( [0, -1, 4][(ans == sol) + (sol != '')] for ans, sol in zip(answers, solutions) ) , 0)", "def check_exam(arr1, arr2):\n score = 0\n\n for i in range(0, len(arr1)):\n if arr1[i] == arr2[i]:\n score = score + 4\n elif arr2[i] != \"\":\n score -= 1\n return max(score, 0)\n\n \n \n", "def check_exam(arr1,arr2):\n x = sum([4 if arr1[i] == arr2[i] else 0 if arr2[i] == '' else -1 for i in range(len(arr1))])\n return 0 if x < 0 else x\n", "def check_exam(arr1,arr2):\n \n total = 0\n \n for x,y in zip(arr1, arr2):\n \n if y == '':\n continue\n elif x == y:\n total += 4\n else:\n total -= 1\n \n return total if total>0 else 0\n", "def check_exam(arr1,arr2):\n score = 0\n for n, a in enumerate(arr2):\n if a != '':\n if a == arr1[n]:\n score += 4\n else:\n score -= 1\n return max(score, 0)\n", "def check_exam(arr1,arr2):\n score = 0\n while True:\n for i in range(len(arr2)):\n if arr1[i] == arr2[i]:\n score += 4\n elif arr2[i] == \"\":\n score += 0\n else:\n score -= 1\n if score < 0:\n return 0\n return score\n\n \n \n \n", "def check_anwser(actual, expected):\n if not actual:\n return 0\n return 4 if actual == expected else -1\n\ndef check_exam(arr1,arr2):\n return max(0, sum(map(check_anwser, arr2, arr1)))\n\n", "def check_exam(arr1,arr2):\n point=0\n for e in list(zip(arr1,arr2)):point+=4 if e[0]==e[1] else(0 if e[1]==''else -1)\n return 0 if point<0 else point\n \n \n", "def check_exam(arr1,arr2):\n a=sum(4 if x==y else -1 if y else 0 for x,y in zip(arr1,arr2))\n return a if a>0 else 0", "def check_exam(arr1,arr2):\n points = 0\n for i in range(len(arr1)):\n points += 4 if arr1[i] == arr2[i] else 0 if arr2[i] == '' else -1\n return points if points > 0 else 0\n \n", "def check_exam(arr1,arr2):\n score = 0\n for i in range(0,len(arr1)):\n if not arr2[i]: continue\n if arr1[i] == arr2[i]: score += 4\n elif arr1[i] != arr2[i]: score -= 1\n if score < 0: score = 0\n return score", "def check_exam(arr1,arr2):\n ans = sum([4 if ca==sa else 0 if sa=='' else -1 for ca, sa in zip(arr1, arr2)])\n return ans if ans > 0 else 0", "def check_exam(arr1,arr2):\n return max(sum([0 if arr2[i] == '' else 4 if arr1[i] == arr2[i] else -1 for i in range(0, len(arr1))]), 0)", "def check_exam(*arr):\n return max(0, sum([-1, 4][a==b] if b else 0 for a,b in zip(*arr)))", "def check_exam(arr1,arr2):\n return max(0,sum([4 if arr2[i]==x else 0 if arr2[i]=='' else -1 for (i,x) in enumerate(arr1)]))\n \n", "def check_exam(arr1,arr2):\n score = sum(4 if a == arr1[i] else 0 if not a else -1 for i, a in enumerate(arr2))\n return 0 if score < 0 else score\n \n", "def check_exam(arr1,arr2):\n result = []\n for i in range(len(arr1)):\n if arr2[i] == \"\":\n result.append(0)\n elif arr1[i]==arr2[i]:\n result.append(4)\n else:\n result.append(-1)\n \n return sum(result) if sum(result)>0 else 0\n \n", "def check_exam(arr1,arr2):\n score = 0\n for elt1, elt2 in zip(arr1, arr2) :\n if not elt2 :\n pass\n elif elt1 == elt2 :\n score += 4\n else :\n score -=1\n return max(score, 0)\n \n \n", "def check_exam(arr1,arr2):\n score=0\n for i,j in zip(arr1,arr2):\n if i==j:\n score+=4\n \n if j==\"\" and i!=\"\":\n score+=0\n if i!=\"\" and j!=\"\" and i!=j:\n score-=1\n if score<0:\n return 0\n else:\n return score\n \n", "def check_exam(a1, a2):\n return max(0, sum(4 if i == j else -1 for i, j in zip(a1, a2) if j))", "def check_exam(arr1,arr2):\n return max(0, sum((arr1[i]==arr2[i])*5-1 for i in range(len(arr1)) if arr2[i] != ''))\n \n", "def check_exam(arr1,arr2):\n return max(0, sum(4 if a1 == a2 else -1 for a1, a2 in zip(arr1, arr2) if a2))\n \n", "def check_exam(a,b):\n res = sum(map(lambda x:0 if x[1] == '' else 4 if x[0] == x[1] else -1 ,zip(a,b)))\n return 0 if res<0 else res", "def check_exam(arr1,arr2):\n a = sum([4 if arr1[x] == arr2[x] else -1 if arr2[x] is not '' else 0 for x in range(len(arr1))])\n return a if a >= 0 else 0\n \n", "def check_exam(arr1,arr2):\n return max(sum((-1,4)[a==b] for a,b in zip(arr1,arr2) if b),0)\n \n", "def check_exam(arr1,arr2):\n return max(0, sum([4 if x == y else -1 if y else 0 for x, y in zip(arr1, arr2)]))", "def check_exam(arr1,arr2):\n return max(sum(4 if arr1[i] == arr2[i] else -1 if arr2[i] else 0 for i in range(len(arr1))), 0)\n \n \n", "def check_exam(a,b):\n return max(0, sum((a[i]==b[i])*5-1 for i in range(len(a)) if b[i]))", "def check_exam(arr1,arr2):\n return max(0, sum((arr1[i]==arr2[i])*5-1 for i in range(len(arr1)) if arr2[i]))", "def check_exam(a,b):\n return max(0,sum([4,-1,0][(x!=y)+(y=='')]for x,y in zip(a,b)))", "check_exam=lambda e,a:max(0,sum(4*(x==y)or-1for x,y in zip(e,a)if y))", "def check_exam(correc,copie):\n return max(0, sum((not not reponse)*(5*(reponse==vrai)-1) for vrai,reponse in zip(correc,copie)))\n \n\n\n", "def check_exam(arr1, arr2):\n\n q = 0\n for i,j in zip(arr1,arr2):\n if i == j:\n q += 4\n elif i != j and j != '':\n q -= 1\n if q > 0:\n return q\n else:\n return 0\n", "from typing import List\n\ndef check_exam(arr1: List[str], arr2: List[str]) -> int:\n \"\"\" Get the score of the exam based on correct answers and student's answers. \"\"\"\n _exam_points_sum = sum([0 if not _it[1] else 4 if _it[0] == _it[1] else -1 for _it in zip(arr1, arr2)])\n return _exam_points_sum if _exam_points_sum > 0 else 0", "def check_exam(arr1,arr2):\n total_grade = 0\n for i in range(max(len(arr1),len(arr2))):\n if arr2[i] == arr1[i]:\n total_grade += 4\n elif arr2[i] == \"\":\n total_grade += 0\n elif arr2[i] != arr1[i]:\n total_grade -= 1\n \n return max(total_grade,0)\n \n", "def check_exam(arr1,arr2):\n score = 0\n for i in range(len(arr1)):\n if arr1[i] == arr2[i]:\n score += 4\n elif arr2[i] == '':\n score = score\n elif arr1[i] != arr2[i]:\n score -= 1\n if score < 0:\n return 0\n else:\n return score\n", "def check_exam(arr1,arr2):\n if check0(arr1, arr2)+check1(arr1, arr2)+check2(arr1, arr2)+check3(arr1, arr2)+minus(arr1, arr2)<0:\n return 0\n else:\n return check0(arr1, arr2)+check1(arr1, arr2)+check2(arr1, arr2)+check3(arr1, arr2)+minus(arr1, arr2)\n \ndef minus(arr1, arr2):\n arr0=[i for i in arr2 if len(i)==0]\n return 0*len(arr0)\n\ndef check0(arr1, arr2):\n if arr1[0]==arr2[0]:\n return +4\n else:\n if len(arr2[0])==0:\n return 0\n else:\n return -1\n \ndef check1(arr1, arr2):\n if arr1[1]==arr2[1]:\n return +4\n else:\n if len(arr2[1])==0:\n return 0\n else:\n return -1\n \ndef check2(arr1, arr2):\n if arr1[2]==arr2[2]:\n return +4\n else:\n if len(arr2[2])==0:\n return 0\n else:\n return -1\n \ndef check3(arr1, arr2):\n if arr1[3]==arr2[3]:\n return +4\n else:\n if len(arr2[3])==0:\n return 0\n else:\n return -1", "def check_exam(arr1,arr2):\n sum=0\n i=0\n while(i<len(arr1)):\n if(arr1[i]==arr2[i]):\n sum=sum+4\n i=i+1\n continue\n elif(arr2[i]==\"\"):\n sum=sum\n i=i+1\n continue\n else:\n sum=sum-1\n i=i+1\n if(sum<0):\n sum=0\n return sum\n else:\n return sum\n", "def check_exam(arr1,arr2):\n points = 0\n for a,b in zip(arr1, arr2):\n if a==b:\n points += 4\n elif b and 1!=b:\n points -= 1\n return points if points > 0 else 0\n \n", "def check_exam(arr1,arr2):\n score = 0\n for i in range(len(arr1)): \n if arr2[i] == '':\n continue\n elif arr2[i] != arr1[i]: \n score -= 1\n else: \n score += 4\n \n return max(score,0)\n \n", "def check_exam(arr1,arr2):\n score = 0\n for s in range (0, len(arr1)):\n for a in range (0, len(arr2)):\n if s == a :\n if arr1[s] == arr2[a]:\n score += 4\n elif arr2[a] == \"\":\n score += 0\n elif arr1[s] != arr2[a] :\n score -= 1 \n if score < 0:\n return 0\n else:\n return score\n \n", "def check_exam(arr1='',arr2=''):\n x=0\n for i in range(0,len(arr2),1):\n if arr1[i]==arr2[i]:\n x=x+4\n elif (arr2[i]!=arr1[i]) and (arr2[i]!=''):\n x=x-1\n else:\n x=x\n if x<=0:\n return 0\n else:\n return x\n \n \n", "def check_exam(arr1,arr2):\n result = 0\n for i in range(len(arr1)):\n if arr1[i] == arr2[i]:\n result += 4\n elif arr2[i] == '':\n result += 0\n else:\n result -= 1\n if result > 0:\n return result\n else:\n return 0\n \n", "def check_exam(arr1,arr2):\n score = 0\n for i in range(4):\n if arr1[i] == arr2[i]:\n score = score + 4\n elif arr2[i] == \"\":\n score = score\n else:\n score = score - 1\n if score < 0:\n score = 0\n return score\n \n", "def check_exam(arr1,arr2):\n return max(0, sum([4 if arr1[i] == arr2[i] else 0 if arr2[i] == \"\" else -1 for i in range(len(arr1))]))\n", "def check_exam(arr1,arr2):\n n = len(arr1)\n score = 0\n while n > 0:\n n -= 1\n if arr2[n] == \"\":\n score = score\n elif arr2[n] == arr1[n]:\n score += 4\n else: score -= 1\n return max(score,0)", "def check_exam(arr1,arr2):\n exam_score = 0\n for index in range(0,len(arr1)):\n if arr1[index] == arr2[index]:\n exam_score += 4\n elif arr1[index] != arr2[index]:\n if arr2[index] == \"\":\n exam_score += 0\n else:\n exam_score -=1\n if exam_score < 0:\n return 0\n else:\n return exam_score\n \n \n", "def check_exam(answer_sheet,test):\n score = 0\n for correct, answer in zip(answer_sheet, test):\n if not answer:\n continue\n score += 4 if correct == answer else -1\n return max(0, score)", "def check_exam(arr1: list, arr2: list) -> int:\n \"\"\" \n This function returns the score for this array of answers, \n giving +4 for each correct answer,\n -1 for each incorrect answer, and +0 for each blank answer.\n \"\"\"\n count = 0\n for i in range(len(arr2)):\n if arr2[i] == arr1[i]:\n count += 4\n elif arr2[i] != arr1[i] and not len(arr2[i]) == 0:\n count -= 1\n return count if count > 0 else 0\n", "def check_exam(arr1,arr2):\n sum = 0\n for a,b in zip(arr1, arr2):\n if a==b:\n sum+=4\n elif b == '':\n sum+=0\n else:\n sum-=1\n if sum<0:\n return 0\n else:\n return sum\n \n \n \n \n", "def check_exam(arr1,arr2):\n finalmark=0\n for i in range(len(arr1)):\n if arr1[i] == arr2[i]:\n finalmark+=4\n if arr1[i] != arr2[i] and arr2[i] != '':\n finalmark-=1\n if finalmark < 0:\n finalmark=0\n return finalmark\n \n", "def check_exam(arr1,arr2):\n ret = 0\n for pair in zip(arr1, arr2):\n if pair[1] == \"\": continue\n ret += 4 if pair[0] == pair[1] else -1\n return max(0, ret)", "def check_exam(arr1,arr2):\n score=0\n for i in range(0,len(arr1)):\n if(arr1[i] == arr2[i]):\n score=score+4\n elif(arr2[i]==\"\"):\n score=score\n else:\n score=score-1\n if score<0:\n return 0 \n return score\n \n", "def check_exam(arr1, arr2):\n result = []\n for a, b in zip(arr1, arr2):\n if a == b:\n result.append(4)\n elif len(a) != len(b):\n result.append(0)\n elif a != b:\n result.append(-1)\n \n score = sum(result)\n if score < 0:\n return 0\n else:\n return score\n \n", "def check_exam(arr1,arr2):\n total = 0\n for x, y in zip(arr1, arr2):\n if x == y: total += 4\n elif y: total -= 1\n return total if total > 0 else 0\n \n", "def check_exam(arr1,arr2):\n print(arr1)\n print(arr2)\n total = 0\n# for x in range(len(arr1)):\n# if arr1[x] == arr2[x]: total += 4\n# elif arr2[x] != '': total -= 1\n# return 0 if total < 0 else total\n \n for i in range(len(arr1)):\n if arr1[i] == arr2[i]:\n total += 4\n elif arr2[i] == \"\":\n total += 0\n elif arr1[i] != arr2[i] and arr2[i] != \"\":\n total -= 1 \n return total if total > 0 else 0\n \n \n \n \n", "def check_exam(arr1,arr2):\n mark = 0\n for a1, a2 in zip(arr1, arr2):\n if a1 == a2:\n mark += 4\n elif a1 != a2 and a2 != '':\n mark -=1\n return 0 if mark < 0 else mark\n", "def check_exam(arr1,arr2):\n def grade(a, b):\n if not b:\n return 0\n if a == b:\n return 4\n if a != b:\n return -1\n s = sum(map(lambda x,y:grade(x,y), arr1, arr2))\n return s if s>0 else 0\n \n", "def check_exam(arr1,arr2):\n score = 0\n for i in range (0, int(len(arr2))):\n if arr2[i]:\n if arr1[i] == arr2[i]:\n score +=4\n if arr1[i] != arr2[i]:\n score -=1\n \n if score >=0:\n return score\n else:\n return 0\n \n", "def check_exam(arr1,arr2):\n score = 0\n for i in range(0, 4):\n if arr1[i] == arr2[i]:\n score += 4\n elif arr2[i] == \"\":\n score += 0\n else:\n score -= 1\n if score > 0: \n return score \n else:\n return 0\n", "def check_exam(a1, a2):\n s = 0\n for x, z in zip(a1, a2):\n if not z:\n pass\n elif x == z: s += 4\n else: s -= 1\n return s if s >= 0 else 0", "def check_exam(arr1,arr2):\n result = 0\n for i in range(len(arr1)):\n if arr2[i] == '':\n result += 0\n elif arr1[i] == arr2[i]:\n result += 4\n elif arr1[i] != arr2[i]:\n result -= 1\n return 0 if result < 0 else result\n \n", "def check_exam(arr1,arr2):\n score = 0\n \n for i in range(len(arr2)):\n \n if arr2[i] == arr1[i]:\n score += 4\n elif (arr2[i] != arr1[i]):\n if arr2[i] == '':\n score += 0\n else:\n score -= 1\n if score < 0:\n return 0\n else:\n return score\n \n \n", "def check_exam(arr1,arr2):\n iterator = 0\n score = 0\n while iterator < 4:\n if arr1[iterator] == arr2[iterator]:\n score = score + 4\n iterator = iterator + 1\n elif arr1[iterator] != arr2[iterator] and arr2[iterator] != \"\":\n score = score - 1\n iterator = iterator + 1 \n else:\n iterator = iterator + 1\n if score < 0:\n score = 0\n return score\n \n \n \n \n \n", "def check_exam(arr1,arr2):\n score = 0\n for c, s in zip(arr1, arr2):\n if s == \"\":\n score += 0\n elif s == c:\n score += 4\n else:\n score -= 1\n return score if score > 0 else 0", "def check_exam(arr1,arr2):\n score = 0\n for i in range(len(arr1)):\n if arr2[i] == '':\n continue\n if arr1[i] == arr2[i]:\n score += 4\n else:\n score += -1\n return score if score > -1 else 0\n \n", "def check_exam(arr1,arr2):\n score =0\n for x in range(len(arr2)):\n if arr1[x] ==arr2[x]:\n score+=4\n elif arr2[x]==\"\":\n pass\n else:\n score-=1\n \n if score <0:\n return 0\n return score\n \n", "def check_exam(arr1, arr2):\n return max(0, sum(4 if arr1[i] == arr2[i] else -1 for i in range(len(arr1)) if arr2[i]))\n \n", "def check_exam(arr1,arr2):\n \n sum = 0\n for i, j in zip(arr1, arr2):\n if j == '':\n sum += 0\n elif i == j:\n sum += 4\n else:\n sum += -1\n \n if sum < 0:\n return 0\n else:\n return sum\n \n", "def check_exam(arr1,arr2):\n c = 0\n for i in range(len(arr1)):\n if arr1[i] == arr2[i]:\n c += 4\n elif arr2[i] == '':\n c += 0\n else:\n c -= 1\n if c < 0:\n return 0\n else:\n return c", "def check_exam(arr1,arr2):\n point = 0\n for x,y in zip(arr1,arr2):\n if x != y:\n if y != \"\":\n point -= 1\n else:\n point = point + 0\n elif x == y:\n point += 4 \n if point < 0:\n return 0\n else:\n return point\n", "def check_exam(arr1,arr2):\n i = 0\n result = 0\n while i < len(arr1):\n if arr1[i] == arr2[i]:\n result = result + 4\n elif arr2[i] == \"\":\n result = result + 0\n else:\n result = result - 1\n i = i + 1\n if result < 0:\n return 0\n else:\n return result", "def check_exam(arr1,arr2):\n corr = 0\n blank = 0\n for n in range(4):\n if arr2[n] == arr1[n] and arr2[n] != \"\":\n corr += 1\n elif arr2[n] == \"\":\n blank += 1\n return (4*corr - (4-corr-blank)) if (4*corr - (4-corr-blank)) > 0 else 0\n \n", "def check_exam(arr1,arr2):\n marks_count = 0\n for i in range(0, len(arr2)):\n if arr2[i] == \"\":\n marks_count += 0\n elif arr2[i] == arr1[i]:\n marks_count += 4\n elif arr2[i] != arr1[i]:\n marks_count -= 1\n \n \n if marks_count < 0:\n return 0\n else:\n return marks_count\n \n", "def check_exam(arr1,arr2):\n score = 0\n for key, ans in zip(arr1, arr2):\n if key == ans:\n score += 4\n elif ans != \"\" and ans != key:\n score -= 1\n return score if score > 0 else 0\n \n", "def check_exam(arr1,arr2):\n score = 0\n for x in range(len(arr1)):\n if arr1[x] == arr2[x]:\n score += 4\n elif arr2[x] != \"\" and arr2[x] != arr1[x]:\n score -= 1\n if score < 0:\n score = 0\n return score", "def check_exam(arr1,arr2):\n sum = 0\n for grade in range(len(arr1)):\n if arr1[grade] == arr2[grade]:\n sum += 4\n elif arr2[grade] == \"\":\n sum += 0\n else:\n sum -= 1\n return sum if sum > 0 else 0\n \n", "def check_exam(arr1,arr2):\n grade = 0\n \n counter = len(arr1)\n \n scores = 0\n \n while scores < counter:\n if arr1[scores] == arr2[scores]:\n grade = grade + 4\n elif arr1[scores] == \"\" or arr2[scores] == \"\":\n grade = grade + 0\n else:\n grade = grade - 1\n \n scores+=1\n \n if grade < 0:\n return 0\n else:\n return grade\n \n \n \n", "def check_exam(arr1,arr2):\n grade = 0\n for answer in range(len(arr1)):\n if arr1[answer] == arr2[answer]:\n grade += 4\n elif arr2[answer] == '':\n grade += 0\n else:\n grade -= 1\n return 0 if grade < 0 else grade", "import numpy\n\ndef check_exam(arr1,arr2):\n result = 0\n for i in range(len(arr2)):\n if arr1[i] == arr2[i]:\n result += 4\n else:\n result -= 1\n result += arr2.count(\"\")\n return 0 if result < 0 else result\n \n", "def check_exam(arr1,arr2):\n score = 0\n for i in range(len(arr1)): # To cycle through the array.\n if arr2[i] == \"\": # Blank answer\n score += 0\n elif arr2[i] == arr1[i]: # Correct answer\n score += 4\n else: # Wrong answer\n score -= 1\n \n if score < 0: # To deal with negative scores.\n return 0\n else:\n return score\n \n \n", "def check_exam(arr1,arr2):\n score = 0\n for i in range(len(arr1)):\n if arr1[i] != arr2[i]:\n if arr2[i] != \"\":\n score-=1\n else:\n score+=4\n return score if score>0 else 0\n \n", "def check_exam(arr1,arr2):\n count = 0\n for i in range(len(arr1)):\n if arr2[i] == \"\":\n count += 0\n elif arr1[i]==arr2[i]:\n count += 4\n elif arr1[i]!=arr2[i]:\n count -= 1\n return 0 if count<0 else count\n \n", "def check_exam(arr1,arr2):\n liste = []\n#enumerate bezieht sich auf Position und Wert in einer Liste \n for i, x in enumerate (arr1):\n y = arr2 [i]\n if (x != y) :\n if (y == (\"\")):\n liste.append(0) \n else :\n liste.append(-1)\n else :\n liste.append(4)\n \n #print (liste) \n x = sum(liste)\n if x < 0:\n return (0)\n else:\n return(x) \n \n", "def check_exam(arr1,arr2):\n liste = []\n for i, x in enumerate(arr1) : #weil sich enumerate immer auf Position und WErt (i, x) bezieht\n y = arr2[i]\n if ((x)!=(y)) :\n if y == (\"\") :\n liste.append(0)\n else : \n liste.append(-1)\n else : \n liste.append(4)\n #return(x)\n \n \n \n \n \n \n \n \n\n x = sum(liste)\n if x <0 : \n return(0)\n else : \n return(x)", "def check_exam(arr1,arr2):\n score = 0\n for i,j in zip(arr1,arr2):\n if j == \"\":\n continue\n elif i == j:\n score += 4\n elif i != j:\n score -= 1\n else:\n pass\n if score <= 0:\n return 0\n else:\n return score\n pass\n \n", "def check_exam(arr1,arr2):\n score = 0\n for i in range(len(arr1)):\n validAnswer = arr1[i]\n studentAnswer = arr2[i]\n if studentAnswer == '':\n continue\n \n if studentAnswer == validAnswer:\n score += 4\n else:\n score -= 1\n if score < 0:\n return 0\n else:\n return score\n pass\n \n \n", "def check_exam(arr1,arr2):\n if len(arr1) == len(arr2) and arr1 != [] and arr2 != []:\n score = 0\n for a in range(len(arr1)):\n if arr2[a] == '':\n continue\n elif arr1[a] == arr2[a]:\n score += 4\n else:\n score -= 1\n if score < 0:\n score = 0\n \n return score\n", "def check_exam(arr1,arr2):\n #checking if arr2[i] is blank since otherwise it would say it is different and deduct points\n score = 0\n for i in range(len(arr2)):\n if arr1[i] == arr2[i]:\n score = score + 4\n elif arr2[i] == \"\":\n score = score + 0\n elif arr1[i] != arr2[i]:\n score = score -1\n \n \n if score < 0:\n return 0\n else:\n return score\n \n", "def check_exam(arr1,arr2):\n \n if len(arr1) != len(arr2):\n return 0\n \n score = 0\n \n for i in range(len(arr1)):\n if arr2[i] == \"\":\n continue\n \n if arr1[i] == arr2[i]:\n score += 4\n continue\n \n if arr1[i] != arr2[i]:\n score -= 1\n continue\n \n return max(score, 0)\n \n", "def check_exam(arr1,arr2):\n points = 0 \n for n in range(len(arr1)):\n if arr2[n] != '':\n if arr1[n] == arr2[n]:\n points = points + 4\n else:\n points = points - 1\n if points < 0:\n points = 0\n return points\n", "def check_exam(arr1,arr2):\n print((arr1, arr2))\n i = 0\n result = []\n while i < len(arr1):\n if arr1[i] == arr2[i]:\n result.append(4)\n elif arr2[i] == \"\":\n result.append(0)\n else:\n result.append(-1)\n i += 1\n return sum(result) if sum(result) > 0 else 0\n \n", "def check_exam(arr1,arr2):\n score0 = 0\n score1 = 0\n score2 = 0\n score3 = 0\n if arr1[0] == arr2[0]:\n score0 = 4\n elif arr2[0]==\"\":\n score0 = 0\n elif arr1[0] != arr2[0]: \n score0 = -1\n \n if arr1[1] == arr2[1]:\n score1 = 4\n elif arr2[1]==\"\":\n score1 = 0\n elif arr1[1] != arr2[1]: \n score1 = -1\n \n if arr1[2] == arr2[2]:\n score2 = 4\n elif arr2[2]==\"\":\n score2 = 0\n elif arr1[2] != arr2[2]: \n score2 = -1\n \n if arr1[3] == arr2[3]:\n score3 = 4\n elif arr2[3]==\"\":\n score3 = 0\n elif arr1[3] != arr2[3]: \n score3 = -1\n \n totalscore = score0+score1+score2+score3\n \n if totalscore < 0:\n return 0\n else:\n return totalscore\n \n"] | {"fn_name": "check_exam", "inputs": [[["a", "a", "b", "b"], ["a", "c", "b", "d"]], [["a", "a", "c", "b"], ["a", "a", "b", ""]], [["a", "a", "b", "c"], ["a", "a", "b", "c"]], [["b", "c", "b", "a"], ["", "a", "a", "c"]]], "outputs": [[6], [7], [16], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 27,935 |
def check_exam(arr1,arr2):
|
3fece34ce8172a2c58e4f83243f84352 | UNKNOWN | Say hello!
Write a function to greet a person. Function will take name as input and greet the person by saying hello.
Return null/nil/None if input is empty string or null/nil/None.
Example:
```python
greet("Niks") --> "hello Niks!"
greet("") --> None # Return None if input is empty string
greet(None) --> None # Return None if input is None
``` | ["def greet(name):\n return f\"hello {name}!\" if name else None", "def greet(name):\n if name:\n return f\"hello {name}!\"", "def greet(s):\n if s: return f\"hello {s}!\"", "def greet(name=None):\n return \"hello {}!\".format(name) if name else None\n", "def greet(n):\n if n:\n return f\"hello {n}!\"", "def greet(name):\n if name==None:\n return None\n if name=='':\n return None\n n=len(name) \n if n>=1:\n return \"hello\"+' '+name+'!'", "def greet(name):\n if name == None:\n return None\n \n if len(name) > 0:\n return \"hello \" + name + \"!\"\n else:\n return None", "def greet(name):\n # your code here\n if name == \"\":\n return None\n elif isinstance(name,str):\n return \"hello \"+ name + \"!\"\n else:\n return None", "def greet(name):\n if name is \"\" or name is None: \n return None\n else:\n return f\"hello {name}!\" ", "def greet(name):\n if name in ['', None]:\n return None\n return f\"hello {name}!\""] | {"fn_name": "greet", "inputs": [["Niks"], ["Nick"], [""], [null]], "outputs": [["hello Niks!"], ["hello Nick!"], [null], [null]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,091 |
def greet(name):
|
07a6735faed2dcf5610ccb54a562e549 | UNKNOWN | When you divide the successive powers of `10` by `13` you get the following remainders of the integer divisions:
`1, 10, 9, 12, 3, 4`.
Then the whole pattern repeats.
Hence the following method:
Multiply the right most digit of the number with the left most number
in the sequence shown above, the second right most digit to the second
left most digit of the number in the sequence. The cycle goes on and you sum all these products. Repeat this process until the sequence of sums is stationary.
...........................................................................
Example: What is the remainder when `1234567` is divided by `13`?
`7×1 + 6×10 + 5×9 + 4×12 + 3×3 + 2×4 + 1×1 = 178`
We repeat the process with 178:
`8x1 + 7x10 + 1x9 = 87`
and again with 87:
`7x1 + 8x10 = 87`
...........................................................................
From now on the sequence is stationary and the remainder of `1234567` by `13` is
the same as the remainder of `87` by `13`: `9`
Call `thirt` the function which processes this sequence of operations on an integer `n (>=0)`. `thirt` will return the stationary number.
`thirt(1234567)` calculates 178, then 87, then 87 and returns `87`.
`thirt(321)` calculates 48, 48 and returns `48` | ["array = [1, 10, 9, 12, 3, 4]\n\ndef thirt(n):\n total = sum([int(c) * array[i % 6] for i, c in enumerate(reversed(str(n)))])\n if n == total:\n return total\n return thirt(total)\n", "import itertools as it\n\ndef thirt(n):\n if n < 100: return n\n \n pattern = it.cycle([1, 10, 9, 12, 3, 4])\n \n return thirt(sum(d*n for d,n in zip(list(map(int, str(n)[::-1])), pattern)))\n", "def thirt(n):\n seq = [1, 10, 9, 12, 3, 4]\n s = str(n)\n t = sum(seq[i%6] * int(s[-i-1]) for i in range(len(s)))\n return t if t == n else thirt(t)", "from itertools import cycle\n\ndef thirt(n):\n c = cycle([1, 10, 9, 12, 3, 4])\n m = sum( int(l)*next(c) for l in str(n)[::-1] )\n return m if m == n else thirt(m)", "def thirt(n):\n w = [1, 10, 9, 12, 3, 4]\n while True:\n r = n; q = -1; c = 0; j = 0\n while (q != 0):\n q = int(r / 10)\n c += (r % 10) * w[j % 6]\n r = q\n j += 1\n if (c == n): return c\n n = c", "seq = (1, 10, 9, 12, 3, 4)\n\ndef thirt(n):\n strn = str(n)[::-1]\n m = sum(seq[i % 6] * int(strn[i]) for i in range(len(strn)))\n return n if n == m else thirt(m)", "def thirt(n):\n p = [1, 10, 9, 12, 3, 4]\n ns = sum(int(c) * p[i % len(p)] for i, c in enumerate(str(n)[::-1]))\n return ns if ns == n else thirt(ns)", "from itertools import cycle\ndef thirt(n):\n while True:\n pattern = cycle((1, 10, 9, 12, 3, 4))\n total = sum(int(a) * next(pattern) for a in reversed(str(n)))\n if total == n:\n return total\n n = total", "def thirt(n):\n sequence = [1,10,9,12,3,4]\n numbers = str(n)[::-1]\n sum = 0\n for i in range(len(numbers)):\n sum += int(sequence[i%6])*int(numbers[i])\n if sum == n:\n return sum\n else:\n return thirt(sum)\n \n \n", "from itertools import cycle\n\ndef thirt(n):\n m = -n\n while m != n:\n m = n\n n = sum(x * y for x, y in zip(cycle([1, 10, 9, 12, 3, 4]), map(int, str(n)[::-1])))\n return n"] | {"fn_name": "thirt", "inputs": [[8529], [85299258], [5634], [1111111111], [987654321]], "outputs": [[79], [31], [57], [71], [30]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,106 |
def thirt(n):
|
7563ca66401dc53b6b6b3a5e72c4315b | UNKNOWN | Write a regex to validate a 24 hours time string.
See examples to figure out what you should check for:
Accepted:
01:00 - 1:00
Not accepted:
24:00
You should check for correct length and no spaces. | ["import re\n\n_24H = re.compile(r'^([01]?\\d|2[0-3]):[0-5]\\d$')\n\nvalidate_time = lambda time: bool(_24H.match(time))\n", "import re\n\n\ndef validate_time(timestamp):\n return bool(re.match(r'(2[0-3]|[01]?\\d):[0-5]\\d$', timestamp))\n", "import re\ndef validate_time(time):\n return bool(re.match('^[0-1]?[0-9]:[0-5][0-9]$|^2[0-3]:[0-5][0-9]$', time))", "def validate_time(time):\n import re\n return bool(re.search(r'^((0\\d)|(\\d)|(1\\d)|(2[0-3])):((0[0-9])|([0-5][0-9]))$',time))", "import re\n\ndef validate_time(time):\n return bool(re.match(r'([01]?[0-9]|2[0-3]):[0-5][0-9]', time))", "import re\n\ndef validate_time(time):\n return bool(re.findall('^([01]?[0-9]|2[0-3]):[0-5][0-9]$', time))\n \n", "import re\ndef validate_time(time):\n return bool(re.match('([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]', time)) ", "import re;validate_time=lambda s:bool(re.match('([01]?\\d|2[0-3]):[0-5]\\d$',s))", "import re\ndef validate_time(time):\n pattern = re.compile(r'^[012]?((?<=2)[0-3]|(?<!2)[0-9]):[0-5][0-9]$')\n return bool(re.fullmatch(pattern, time))\n", "from re import search\ndef validate_time(time):\n return bool(search('^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$', time))"] | {"fn_name": "validate_time", "inputs": [["1:00"], ["13:1"], ["12:60"], ["12: 60"], ["24:00"], ["00:00"], ["24o:00"], ["24:000"], [""], ["09:00"], ["2400"], ["foo12:00bar"], ["010:00"], ["1;00"]], "outputs": [[true], [false], [false], [false], [false], [true], [false], [false], [false], [true], [false], [false], [false], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,219 |
def validate_time(time):
|
162ef9c4c07e08e33a8c7493d047bc88 | UNKNOWN | # Personalized greeting
Create a function that gives a personalized greeting. This function takes two parameters: `name` and `owner`.
Use conditionals to return the proper message:
case | return
--- | ---
name equals owner | 'Hello boss'
otherwise | 'Hello guest' | ["def greet(name, owner):\n return \"Hello boss\" if name == owner else \"Hello guest\"", "def greet(name, owner):\n return \"Hello {}\".format(\"boss\" if name == owner else \"guest\")", "def greet(name, owner):\n return f\"Hello {'boss' if name == owner else 'guest'}\"", "def greet(name, owner):\n if name == owner:\n return \"Hello boss\"\n else:\n return \"Hello guest\"\n#Completed by Ammar on 25/8/2019 at 03:24AM.\n", "def greet(name, owner):\n if (name == owner):\n return 'Hello boss'\n else:\n return 'Hello guest'", "def greet(name, owner):\n return 'Hello '+['guest','boss'][name==owner]", "greet=lambda n,o:'Hello '+'gbuoessst'[n==o::2]", "greet = lambda n,o: \"Hello {}\".format([\"guest\",\"boss\"][n==o])", "def greet(name, owner):\n return 'Hello ' + ('guest' if name!=owner else 'boss')", "def greet(a, b):\n return 'Hello boss' if a == b else 'Hello guest'", "def greet(name, owner):\n if name == owner:\n return 'Hello boss'\n return 'Hello guest'", "def greet(name, owner):\n return 'Hello %s' %('boss' if name==owner else 'guest')", "def greet(name: str, owner: str) -> str:\n \"\"\" Get personalized greeting based on passed `name` and `owner`. \"\"\"\n return f\"Hello {'boss' if name == owner else 'guest'}\"", "def greet(name, owner):\n return 'Hello ' + ['boss', 'guest'][name != owner]", "def greet(name, owner):\n return f\"Hello {['guest', 'boss'][name == owner]}\"", "def greet(*s):\n return f\"Hello {['boss','guest'][len(set(s))==len(s)]}\"", "def greet(name, owner):\n return (\"Hello boss\", \"Hello guest\")[name != owner]", "def greet(name, owner):\n return 'Hello {}'.format({owner: 'boss'}.get(name, 'guest'))", "def greet(name, owner):\n greet = 'guest'\n if name == owner: \n greet = 'boss'\n return 'Hello ' + greet", "def greet(name, owner):\n if f'{name}'==f'{owner}':\n return 'Hello boss'\n else:\n return 'Hello guest'", "greet = lambda name, owner: \"Hello %s\"%([\"guest\", \"boss\"][name == owner])", "def greet(name, owner) -> str:\n if name == owner:\n return \"Hello boss\"\n else:\n return \"Hello guest\"", "def greet(name, owner):\n n = 'boss' if name == owner else 'guest'\n return 'Hello {}'.format(n)", "def greet(name, owner):\n a = name\n b = owner\n if a == b :\n return 'Hello boss'\n else :\n return 'Hello guest'", "def greet(name, owner):\n return \" \".join([\"Hello\",\"boss\" if owner == name else \"guest\"])", "def greet(name,owner):\n result = \"\"\n if name == owner:\n result = \"Hello boss\"\n else:\n result = \"Hello guest\"\n return result ", "def greet(a, b):\n return 'Hello {}'.format(['guest', 'boss'][a==b])", "def greet(name, owner):\n string = \"\"\n if name == owner:\n string += \"boss\"\n else:\n string += \"guest\"\n return \"Hello \" + string", "def greet(n, r):\n return 'Hello '+('boss' if n==r else 'guest')", "def greet(name, owner):\n \"\u041f\u0440\u0438\u0432\u0435\u0442\u0441\u0442\u0432\u0443\u0435\u043c \u0411o\u0441\u0441\u0430\"\n return 'Hello boss' if name == owner else 'Hello guest'", "def greet(name, owner):\n if(name == owner):\n x = 'boss'\n else:\n x = 'guest'\n return \"Hello {}\".format(x);", "#using ternary operatior\ndef greet(name, owner):\n return 'Hello boss'if name == owner else 'Hello guest'", "def greet(name, owner):\n if name==owner:\n print('Hello boss')\n return 'Hello boss'\n if name!=owner:\n print('Hello guest')\n return 'Hello guest'\n # Add code here\n", "def greet(name, owner):\n if name==owner:\n return \"Hello boss\"\n else:\n return \"Hello guest\"\nx = greet('Greg', 'Daniel')\nprint(x)", "def greet(name, owner):\n if name == owner:\n s = 'Hello boss'\n else:\n s = 'Hello guest'\n return s", "greet = lambda a, b: f\"Hello {'boss' if a == b else 'guest'}\"", "import unittest\n\nHELLO_BOSS_MSG = 'Hello boss'\nHELLO_GUEST_MSG = 'Hello guest'\n\n\ndef greet(name, owner):\n return 'Hello boss' if name == owner else 'Hello guest'\n \n \nclass TestGreet(unittest.TestCase):\n def test_should_return_hello_boss_msg_when_names_equals_owner(self):\n name, owner = 'Daniel', 'Daniel'\n actual = greet(name, owner)\n self.assertEqual(actual, 'Hello boss')\n\n def test_should_return_hello_guest_msg_when_names_equals_owner(self):\n name, owner = 'Daniel', 'Guest'\n actual = greet(name, owner)\n self.assertEqual(actual, 'Hello guest')\n", "def greet(name, owner):\n # Add code here\n #name = input()\n #owner = input()\n if name == owner:\n return \"Hello boss\"\n else:\n return 'Hello guest'", "def greet(name, owner):\n # Add code here\n if name==owner:\n what = \"boss\"\n else:\n what = \"guest\"\n return \"Hello {}\".format(what)", "def greet(name, owner):\n return{\n owner : 'Hello boss'\n }.get(name, 'Hello guest')", "greet = lambda n, o: \"Hello {0}\".format('boss' if o == n else 'guest')", "def greet(n, m):\n if n==m:\n return 'Hello boss'\n return 'Hello guest'", "def greet(name, owner):\n if name == owner:\n return f'Hello boss'\n else:\n return 'Hello guest'", "def greet(name,name2):\n if str(name) == str(name2):\n return(\"Hello boss\")\n else:\n return(\"Hello guest\")", "def greet(name, owner):\n boss='Hello boss'\n guest='Hello guest'\n if name == 'Daniel' and owner == 'Daniel':\n return boss\n else:\n return guest", "def greet(name, owner):\n # Add code here\n if name == owner:\n return 'Hello boss'\n else:\n return 'Hello guest'\n \n\ngreet('Vasya','Vasya') ", "def greet(name, owner):\n f_name = name.lower()\n f_owner = owner.lower()\n if f_name == f_owner:\n return 'Hello boss'\n else:\n return 'Hello guest'", "def greet(name, owner):\n return f\"Hello {name == owner and 'boss' or 'guest'}\"", "greet = lambda name, owner: 'Hello guest' if name != owner else 'Hello boss'", "def greet(name, owner):\n return 'Hello boss' if name == owner else 'Hello guest'\n # self\n", "def greet(n, o):\n return f\"Hello {'boss' if n == o else 'guest'}\"", "def greet(name, owner):\n re = ['Hello boss','Hello guest']\n return re[0] if name == owner else re[1]", "def greet(name, owner):\n # Add code here\n r = 'Hello guest'\n if name == owner:\n r = 'Hello boss'\n return r\n", "def greet(n, o):\n return 'Hello ' + ['guest','boss'][n == o]", "def greet(name, owner):\n x = 'boss' if name == owner else 'guest'\n return f'Hello {x}'", "def greet(name, owner):\n print(name)\n print(owner)\n l = [\"Daniel\", \"Joe\"]\n return \"Hello boss\" if name in l else \"Hello guest\"", "def greet(name, owner):\n if name != owner:\n return 'Hello guest'\n elif owner == name:\n return 'Hello boss'\n", "def greet(name, owner):\n # Add code here\n name.lower()\n owner.lower()\n if name==owner:\n return ('Hello boss')\n else:\n return ('Hello guest')", "def greet(n, m):\n return 'Hello boss' if n == m else 'Hello guest'", "def greet(name, owner):\n greeting = \"boss\" if name == owner else \"guest\"\n return 'Hello {greeting}'.format(greeting=greeting)", "def greet(name, owner):\n # Add code here\n if name == owner:\n return('Hello boss')\n else:\n return('Hello guest')\n \ngreet('Daniel', 'Greg')", "def greet(name, owner):\n if name == owner:\n result = \"boss\"\n else:\n result = \"guest\"\n return \"Hello \" + result\n # Add code here\n", "def greet(name, owner):\n # Add code here\n name=name.lower()\n owner=owner.lower()\n if name==owner:\n return 'Hello boss'\n else:\n return 'Hello guest'", "def greet(name, owner):\n greetings = [\"Hello boss\", \"Hello guest\"]\n\n return greetings[0] if name == owner else greetings[1]\n", "def greet(name: str, owner: str) -> str:\n return 'Hello boss' if name == owner else 'Hello guest'", "def greet(name, owner):\n if name == owner:\n return \"Hello boss\"\n else:\n name != owner\n return \"Hello guest\"", "def greet(name, owner):\n if name == owner:\n return 'Hello boss'\n else:\n return 'Hello guest'\n#print greet('Greg', 'Daniel')\n", "def greet(name, owner):\n if name == owner:\n greeting = \"boss\"\n else:\n greeting = \"guest\"\n return \"Hello {0}\".format(greeting)", "def greet(name, owner):\n if name == owner:\n return 'Hello boss'\n else:\n return 'Hello guest'\n \ngreet('Greg', 'Daniel')", "def greet(name, owner):\n if name == owner:\n return 'Hello' + ' ' + 'boss'\n else:\n return 'Hello' + ' ' + 'guest'", "def greet(name, owner):\n return 'Hello ' + 'boss'*(name==owner) + 'guest'*(name!=owner)", "def greet(name, owner):\n if owner == name:\n return 'Hello boss'\n return 'Hello guest'", "def greet(name, owner):\n if name == owner:\n answer = 'Hello boss'\n else:\n answer = 'Hello guest'\n return answer\n", "def greet(name, owner):\n return 'Hello {0}'.format('guest' if name != owner else 'boss')", "def greet(name, owner):\n if name == owner:\n text=\"Hello boss\"\n else:\n text=\"Hello guest\"\n return text", "def greet(name, owner):\n # Add code here\n x=name\n y=owner\n if x==y:\n return 'Hello boss'\n else: \n return 'Hello guest'\n \n", "def greet(name, owner):\n if name == owner:\n res = 'Hello boss'\n else:\n res = 'Hello guest'\n return res", "def greet(name, owner):\n if name == owner:\n return \"Hello boss\"\n elif name != owner:\n return \"Hello guest\"\n else:\n return 0", "def greet(name, owner):\n if name == owner:\n n = 'Hello boss'\n else:\n n = 'Hello guest'\n return n", "def greet(name, owner):\n return (f'{\"Hello boss\"}' if name==owner else f'{\"Hello guest\"}')", "def greet(name, owner):\n if name == owner:\n return 'Hello boss'\n else:\n return 'Hello guest'\n return greet + \" , Hello guest\"\n \n \n# (f'greet, {name \n", "def greet(name, owner):\n person = 'boss' if name == owner else 'guest'\n return 'Hello ' + person", "def greet(name, owner):\n answer = 'Hello guest'\n if name == owner:\n answer = 'Hello boss'\n return answer", "def greet(name, owner):\n if name == owner:\n return('Hello boss')\n if name != owner:\n return('Hello guest')\n else:\n return None\n \ngreet('Bob','Bob')", "def greet(name, owner):\n #print(name, owner)\n if name == owner:\n return(\"Hello boss\")\n else:\n return(\"Hello guest\")", "def greet(name, owner):\n if name==owner:\n return \"Hello boss\"\n \n else:\n return \"Hello guest\"\n \n \n #if name=!owner\n #return('Hello guest')\na='Daniel'\nb='Daniel'\n\nprint(greet(a,b))", "def greet(name, owner):\n a = 'boss' if name == owner else 'guest'\n return 'Hello {}'.format(a)", "def greet(name, owner):\n statement = 'Hello '\n if name == owner:\n statement += 'boss'\n else:\n statement += 'guest'\n return statement", "def greet(name, owner):\n name = \"boss\" if name == owner else \"guest\"\n return \"Hello \" + name", "def greet(n, o):\n if n == o:\n return \"Hello boss\"\n return \"Hello guest\"\n\n", "def greet(name, owner):\n # xxx if a else xxx\n return 'Hello boss'if name == owner else 'Hello guest'", "def greet(name, owner):\n if name == owner:\n return \"Hello boss\"\n else:\n return \"Hello guest\"\n \nprint(greet(\"paschoal\",\"paschoal\"))\nprint(greet(\"paschoal\",\"morelli\"))"] | {"fn_name": "greet", "inputs": [["Daniel", "Daniel"], ["Greg", "Daniel"]], "outputs": [["Hello boss"], ["Hello guest"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 12,165 |
def greet(name, owner):
|
b5f51fbab5eae898d10895b260d432ca | UNKNOWN | # Let's play Psychic
A box contains green, red, and blue balls. The total number of balls is given by `n` (`0 < n < 50`).
Each ball has a mass that depends on the ball color. Green balls weigh `5kg`, red balls weigh `4kg`, and blue balls weigh `3kg`.
Given the total number of balls in the box, `n`, and a total mass, `m`, your task is to craft a program that will determine the quantities of each colored ball. Return a list of these quantities as the answer.
Don't forget that some combinations of `n` and `m` may have more than one possibility!
# Examples
## Python
```python
>>> Guess_it(3, 12)
[[0,3,0], [1,1,1]]
```
## Elixir
*Note: Order of the returned elements is unimportant in the Elixir version.*
# Assumptions
1. You can assume that all inputs are of the correct type
2. You can assume that the range of `n` will be `[1, 50]`
3. Each element of the returned list should return the quantities in the order of `g`, `r`, `b`.
## Python
```python
[[green, red, blue]]
```
## Elixir | ["def Guess_it(n,m):\n result = []\n for x in range(0,n+1):\n b, r, g = 4 * n + x - m, m - 3 * n - 2 * x, x\n if all(y >= 0 for y in (b,r,g)):\n result.append([g,r,b])\n return result\n\n", "def Guess_it(n,m):\n\n def get_sum_balls(a, b, c): return sum([a,b,c])\n def get_sum_mass(a, b, c): return sum([a*5, b*4, c*3])\n\n \n green_max = min(m // 5, n)\n red_max = min(m // 4, n)\n \n result = []\n \n for green_ball in range(0, green_max+1):\n for red_ball in range(0, red_max+1):\n blue_ball = abs(n - (green_ball + red_ball))\n \n\n x = get_sum_balls(green_ball, red_ball, blue_ball)\n y = get_sum_mass(green_ball,red_ball, blue_ball)\n\n if x == n and y == m: \n result.append([green_ball, red_ball, blue_ball])\n \n return result", "def Guess_it(N, M):\n def mass(g, r, b): return (g * 5) + (r * 4) + (b * 3) \n results = []\n for g in range(N + 1):\n for r in range((N - g) + 1):\n b = N - r - g\n if mass(g, r, b) == M: \n results.append([g, r, b])\n return results\n", "Guess_it=lambda n,m:[[g,r,n-g-r]for g in range(n+1)for r in range(n-g+1)if(n-g-r)*3+r*4+g*5==m]", "def Guess_it(n,m):\n\n \"\"\"\n n = number of balls in bag ranging from 1-50\n m = total weight of all balls in bag\n balls can be:\n green = 5 kg\n red = 4 kg\n blue = 3 kg\n \n return a list of all possible combinations of balls based on weight and number\n \n \"\"\"\n gMass, rMass, bMass = 5, 4, 3\n gQ, rQ, bQ = 0,0,0\n massTotal = gMass*gQ + rMass*rQ + bMass*bQ\n total = gQ + rQ + bQ\n \n solutionSet = []\n while gQ <= n:\n rQ = 0\n bQ = 0\n massTotal = gMass*gQ + rMass*rQ + bMass*bQ\n total = gQ + rQ + bQ\n solution = [gQ, rQ, bQ]\n if (total, massTotal) == (n, m):\n solutionSet.append(solution)\n else:\n while gQ+rQ <= n:\n bQ = 0\n massTotal = gMass*gQ + rMass*rQ + bMass*bQ\n total = gQ + rQ + bQ\n solution = [gQ, rQ, bQ]\n if (total, massTotal) == (n, m):\n solutionSet.append(solution)\n else:\n while gQ + rQ + bQ <= n:\n massTotal = gMass*gQ + rMass*rQ + bMass*bQ\n total = gQ + rQ + bQ\n solution = [gQ, rQ, bQ]\n if (total, massTotal) == (n, m):\n solutionSet.append(solution)\n bQ += 1\n rQ += 1\n gQ += 1\n return solutionSet", "def Guess_it(n,m):\n # Return a list of lists for all combinations\n # green, red, blue\n mass = {'green': 5, 'red': 4, 'blue': 3}\n # Find all combinations of n balls whose total mass = m\n output = []\n for i in range(0, n+1):\n for j in range(0, n+1):\n for k in range(0, n+1):\n if i+j+k==n and i*5 + j*4 +k*3 == m:\n output.append([i, j, k])\n return sorted(output) # Return sorted list", "def Guess_it(n,m):\n result = []\n delta = n*5 - m\n for idx, i in enumerate(range(n-delta, int(1+n-delta/2))):\n if i>=0:\n result.append([i, delta-2*idx, idx])\n return result", "def Guess_it(n,m):\n lis=[]\n for x in range(n+1):\n for d in range(n-x+1):\n if (5*x)+(4*d)+3*(n-x-d)==m:\n lis.append([x,d,(n-x-d)])\n else:\n pass\n return lis", "def Guess_it(n,m):\n #May the force be with you.\n if n == 0:\n return [[]]\n arrayStorage = {\n 0: [],\n 1: [],\n 2: [],\n 3: [[0, 0, 1]],\n 4: [[0, 1, 0]],\n 5: [[1, 0, 0]]\n }\n if m in arrayStorage:\n return arrayStorage[m]\n for i in range(6, m + 1):\n # Case 1: comparing against 3\n arrayStorage[i] = []\n arraysTemp = arrayStorage[i - 3]\n for array in arraysTemp:\n if sum(array) < n:\n elemToAdd = [array[0], array[1], array[2] + 1]\n if elemToAdd not in arrayStorage[i]:\n arrayStorage[i].append(elemToAdd)\n\n # Case 2: comparing against 4\n arraysTemp = arrayStorage[i - 4]\n for array in arraysTemp:\n if sum(array) < n :\n elemToAdd = [array[0], array[1] + 1, array[2]]\n if elemToAdd not in arrayStorage[i]:\n arrayStorage[i].append(elemToAdd)\n\n # Case 3 against 5\n arraysTemp = arrayStorage[i - 5]\n for array in arraysTemp:\n if sum(array) < n:\n elemToAdd = [array[0] + 1, array[1], array[2]]\n if elemToAdd not in arrayStorage[i]:\n arrayStorage[i].append(elemToAdd)\n\n resultArray = []\n for array in arrayStorage[m]:\n if sum(array) == n:\n resultArray.append(array)\n return sorted(resultArray, key=lambda x: x[0])"] | {"fn_name": "Guess_it", "inputs": [[3, 12], [40, 180], [30, 130], [32, 148], [18, 80], [18, 74], [50, 180], [50, 172]], "outputs": [[[[0, 3, 0], [1, 1, 1]]], [[[20, 20, 0], [21, 18, 1], [22, 16, 2], [23, 14, 3], [24, 12, 4], [25, 10, 5], [26, 8, 6], [27, 6, 7], [28, 4, 8], [29, 2, 9], [30, 0, 10]]], [[[10, 20, 0], [11, 18, 1], [12, 16, 2], [13, 14, 3], [14, 12, 4], [15, 10, 5], [16, 8, 6], [17, 6, 7], [18, 4, 8], [19, 2, 9], [20, 0, 10]]], [[[20, 12, 0], [21, 10, 1], [22, 8, 2], [23, 6, 3], [24, 4, 4], [25, 2, 5], [26, 0, 6]]], [[[8, 10, 0], [9, 8, 1], [10, 6, 2], [11, 4, 3], [12, 2, 4], [13, 0, 5]]], [[[2, 16, 0], [3, 14, 1], [4, 12, 2], [5, 10, 3], [6, 8, 4], [7, 6, 5], [8, 4, 6], [9, 2, 7], [10, 0, 8]]], [[[0, 30, 20], [1, 28, 21], [2, 26, 22], [3, 24, 23], [4, 22, 24], [5, 20, 25], [6, 18, 26], [7, 16, 27], [8, 14, 28], [9, 12, 29], [10, 10, 30], [11, 8, 31], [12, 6, 32], [13, 4, 33], [14, 2, 34], [15, 0, 35]]], [[[0, 22, 28], [1, 20, 29], [2, 18, 30], [3, 16, 31], [4, 14, 32], [5, 12, 33], [6, 10, 34], [7, 8, 35], [8, 6, 36], [9, 4, 37], [10, 2, 38], [11, 0, 39]]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 5,145 |
def Guess_it(n,m):
|
a812400224a5d6f74de6a1fd11cff895 | UNKNOWN | Create a function that checks if a number `n` is divisible by two numbers `x` **AND** `y`. All inputs are positive, non-zero digits.
```JS
Examples:
1) n = 3, x = 1, y = 3 => true because 3 is divisible by 1 and 3
2) n = 12, x = 2, y = 6 => true because 12 is divisible by 2 and 6
3) n = 100, x = 5, y = 3 => false because 100 is not divisible by 3
4) n = 12, x = 7, y = 5 => false because 12 is neither divisible by 7 nor 5
``` | ["def is_divisible(n,x,y):\n return n % x == 0 and n % y == 0", "def is_divisible(n, x, y):\n return n % x == n % y == 0", "def is_divisible(n,x,y):\n #your code here\n if n % x == 0 and n % y == 0:\n return True\n else:\n return False", "def is_divisible(n, x, y):\n return not n % x and not n % y\n", "\"\"\" isdiv works thusly:\nCreate a function isDivisible(n, x, y)\nthat checks if a number n is divisible\nby two numbers x AND y. All inputs are\npositive, non-zero digits.\n\"\"\"\n\n\n# isDivisible(3,1,3)--> true because 3 is divisible by 1 and 3\n# isDivisible(12,2,6)--> true because 12 is divisible by 2 and 6\n# isDivisible(100,5,3)--> false because 100 is not divisible by 3\n# isDivisible(12,7,5)--> false because 12 is neither divisible by 7 nor 5\n\ndef is_divisible(n,x,y):\n \"\"\"is divisible checks if a number n is divisible\n by two numbers x AND y. All inputs are\n positive, non-zero digits.\n\n >>> is_divisible(3,1,3)\n True\n >>> is_divisible(12,2,6)\n True\n >>> is_divisible(100,5,3)\n False\n >>> is_divisible(12,7,5)\n False\n\n >>> is_divisible(0,1,1)\n Traceback (most recent call last):\n ...\n ValueError: Must be integer greater than 0\n >>> is_divisible(1,0,1)\n Traceback (most recent call last):\n ...\n ValueError: Must be integer greater than 0\n >>> is_divisible(1,1,0)\n Traceback (most recent call last):\n ...\n ValueError: Must be integer greater than 0\n \"\"\"\n\n if n < 1 or x < 1 or y < 1:\n raise ValueError('Must be integer greater than 0')\n\n return n % x == 0 and n % y == 0", "def is_divisible(n,x,y):\n return not (n%x or n%y)", "def is_divisible(n,x,y):\n return n % x + n % y == 0 ", "def is_divisible(n,x,y):\n return (n % x == 0) & (n % y == 0)", "is_divisible = lambda n,x,y: not (n%x or n%y)", "def is_divisible(n,x,y):\n if x == 0 or y == 0: return False\n return n//x == n/x and n//y == n/y", "def is_divisible(n,x,y):\n return True if n % x == 0 and n % y == 0 else False", "def is_divisible(n,x,y):\n return (False, True)[n%x==0 and n%y==0]", "is_divisible = lambda n,x,y: not ((n**2)%(x*y))", "def is_divisible(n,x,y):\n return n%x==0==n%y", "def is_divisible(n,x,y):\n correct = True\n if n/x != n//x:\n correct = False\n elif n/y != n//y:\n correct = False\n return correct\n", "def is_divisible(n,x,y):\n if not n % x:\n if not n % y:\n return True\n\n return False", "def is_divisible(n,x,y):\n print(n,x,y)\n return True if (n%x==0 and n%y==0) else False", "def is_divisible(n,x,y):\n return not (n % x + n % y)", "is_divisible=lambda n,x,y: n%x==0 and n%y==0", "from math import gcd; is_divisible = lambda n, x, y: not n%(x*y//(gcd(x, y)))", "def is_divisible(n,x,y):\n if n > 0 and x > 0 and y > 0:\n if n % x == 0 and n % y == 0:\n print(\"Target number IS divisible by BOTH divisors\")\n return True\n else:\n print(\"Target number is NOT divisible by BOTH devisors\")\n return False\n else: \n print(\"Incorrect input: One or more arguments are not higher than zero\")\n", "def is_divisible(n,x,y):\n return abs(n) % abs(x) == 0 and abs(n) % abs(y) == 0", "is_divisible = lambda n,x,y: (n%x==0)&(n%y==0)", "def is_divisible(n,x,y):\n #your code here\n while n != 0:\n if n % x == 0 and n % y == 0:\n return True\n else:\n return False", "is_divisible = lambda n, x, y: not n % x and not n % y\n", "def is_divisible(n,x,y):\n return True if n%x==n%y==0 else False", "def is_divisible(n,x,y):\n if(n%x == 0):\n if(n%y == 0):\n return True\n return False\n #your code here\n", "\"\"\"NOTE: This is NOT an efficient solution, it's just a solution using Python's gcd function\"\"\"\n\"\"\"Imports greatest common divisor (gcd)\"\"\"\nfrom fractions import gcd \n\"\"\"gcd has been moved to the math module in Python 3.5,\nso you should use: from math import gcd\"\"\"\ndef is_divisible(n,x,y):\n \"\"\"Computes the least common multiple (lcm) -> \n https://en.wikipedia.org/wiki/Least_common_multiple#Computing_the_least_common_multiple\"\"\"\n lcm = (x*y)/gcd(x,y) \n \"\"\"if x divides n, and y divides n, so lcm(x,y) also divides n\"\"\"\n return n%lcm == 0", "def is_divisible(n,x,y):\n a = n / x\n b = n / y\n return a.is_integer() and b.is_integer()", "def is_divisible(n,x,y):\n return all([n%m==0 for m in (x, y)])", "def is_divisible(n,*args):\n return all(n % i == 0 for i in args)", "def is_divisible(n, x, y):\n return all([not n % x, not n % y])\n", "def is_divisible(n,x,y):\n #your code here\n div1=n % x\n div2=n % y\n if div1 == 0 and div2 == 0:\n return True\n else:\n return False\n\nprint(is_divisible(6,2,3))", "def is_divisible(n,x,y):\n return n % y == 0 if n % x == 0 else False;", "def is_divisible(n,x,y):\n ifx = True; ify = True;\n if ((n % x != 0 ) or (n % y != 0)):\n if ((n % x != 0 ) and (n % y != 0)):\n ifx = False\n ify = False;\n elif (n % x != 0 ):\n ifx = False;\n elif (n % y != 0 ):\n ify = False;\n \n if ((ifx == False) or (ify == False)):\n return False;\n else:\n return True;\n \n #your code here\n", "def is_divisible(n,x,y):\n return True if (n % x or n % y) == 0 else False", "def is_divisible(n,x,y):\n return True if n%x is 0 and n%y is 0 else False", "def is_divisible(n,x,y):\n #your code here\n return not(n % x | n % y)", "def is_divisible(n,x,y):\n if x != 0 and y != 0:\n if n % x == n % y == 0: return True\n else: return False\n return False", "def is_divisible(n,x,y):\n return (n%x is 0 and n%y is 0)", "def is_divisible(n,x,y):\n if n%y==0 and n%x==0:\n return True\n else:\n return False", "def is_divisible(n,x,y):\n\n check = True\n\n if n % x == 0 and n % y == 0:\n\n check = True\n\n\n return check\n\n else:\n\n check = False\n\n return check\n", "def is_divisible(n,x,y):\n if n < 1 or x < 1 or y < 1:\n return False\n else :\n if (n % x == 0) and (n % y == 0) :\n return True\n else :\n return False", "def is_divisible(n,x,y):\n t1 = n % x\n t2 = n % y\n if t1 == 0 and t2 == 0:\n return True\n else:\n return False\n #your code here\n", "def is_divisible(n,x,y):\n a=n%x\n b=n%y\n if a==0 and b==0:\n print (a)\n print(b)\n return True\n else:\n \n return False\n \n", "def is_divisible(n,x,y):\n if(n%x==0 and n%y==0):\n return True\n end\n else:\n return False\n", "def is_divisible(n,x,y):\n if n > 0:\n if n%x==0 and n%y==0:\n return True\n else:\n return False\n else:\n print(\"Inputs should be positive, non-zero digits!\")", "import math\ndef is_divisible(n,x,y):\n return math.floor(n/x)==math.ceil(n/x) and math.floor(n/y)==math.ceil(n/y)", "def is_divisible(n,x,y):\n return True if n%x == 0 == n%y else False", "# checks if n is divisble by x and y\ndef is_divisible(n,x,y):\n if n % x == 0 and n % y == 0:\n return True\n else:\n return False", "def is_divisible(n,x,y):\n flag = False\n if(not(n % x) and not(n % y)):\n flag = True\n return flag", "def is_divisible(n,x,y):\n return not (n % y) + (n % x)", "def is_divisible(n,x,y):\n return not bool(n % y)+(n % x)\n", "def is_divisible(n,x,y):\n num = n\n num1 = x\n num2 = y\n if ((num % x) == 0) and ((num % y) == 0) :\n return True\n else :\n return False", "def is_divisible(n,x,y):\n ma = n % x\n la = n % y\n ka = ma + la \n if ka == 0:\n return True\n else: \n return False", "def is_divisible(n,x,y):\n# if all(n % x and n % y) == 0:\n# print(True)\n# else:\n# print(False)\n\n return n % x == 0 and n % y == 0", "def is_divisible(n,x,y):\n answer = n / x\n answer2 = n / y\n answer_integer_check = answer.is_integer()\n answer2_integer_check = answer2.is_integer()\n if answer_integer_check and answer2_integer_check == True:\n return True\n else:\n return False", "def is_divisible(n,x,y):\n a = n % x\n b = n % y\n if (a or b) == 0:\n return True\n else:\n return False", "def is_divisible(n,x,y):\n x1 = n % x\n y1 = n % y\n if (x1 >= 1 or y1 >= 1):\n return(False)\n elif (x1 == 0 and y1 == 0):\n return (True)", "def is_divisible(n,x,y):\n q1, r1 = divmod(n, x)\n q2, r2 = divmod(n, y)\n return True if r1 == 0 and r2 == 0 else False\n", "def is_divisible(n,x,y):\n return n % x == 0 == n % y\n#pogchamp\n", "def is_divisible(n,x,y):\n #print(n % y)\n if n % x == 0 and n % y == 0:\n return True\n else:\n return False\n", "def is_divisible(z,x,y):\n if z/x==int(z/x) and z/y==int(z/y):\n return(True)\n else:\n return(False)\n", "def is_divisible(n,x,y):\n if n%x == 0 == n%y:\n return True\n else:\n return False", "def is_divisible(n,x,y):\n n = int(n)\n x = int(x)\n y = int(y)\n \n if n % x != 0 or n % y != 0:\n return False\n else:\n return True", "def is_divisible(n,x,y):\n # We want to check if n is divisible by BOTH x AND Y\n if n % x == 0 and n % y == 0:\n return True\n else:\n return False", "def is_divisible(n,x,y):\n #your code here\n return True if (n/x).is_integer()==True and (n/y).is_integer()==True else False", "def is_divisible(n,x,y):\n if (n%x == 0 and n%y == 0):\n return True\n elif (n%x != 0 or n%y != 0):\n return False\n else:\n return False\n\nn = 3\nx = 3\ny = 4\nprint(is_divisible(n,x,y))", "def is_divisible(n,x,y):\n num, num1 = n/y, n/x\n if num == int(n/y) and num1 == int(n/x):\n return True\n else:\n return False\n\n", "def is_divisible(n,\n x,\n y):\n\n if (n % x == 0 and\n n % y == 0):\n\n return True\n\n return False\n", "def is_divisible(n,x,y):\n #number being divided\n #x , y numbers being used to divide\n #print false if its not divisible by one number\n #print true if both statements are true\n if n % x == 0 and n % y == 0:\n return True\n elif n % x != 0 or n % y != 0:\n return False", "def is_divisible(n,x,y):\n if n/x == int(n/x):\n if n/y == int(n/y):\n return True\n return False", "def is_divisible(n,x,y):\n return True if ((n % y == 0) & (n % x == 0 )) else False", "def is_divisible(n,x,y):\n if int(n % x == 0) and int(n % y == 0):\n return True\n else:\n return False", "def is_divisible(n,x,y): \n if n % x != 0 and n % y != 0 :\n return(False)\n if n % x != 0 or n % y != 0 :\n return(False)\n \n elif n % x == 0 and n % y == 0 :\n return(True)\n \nis_divisible(3, 3, 4)", "is_divisible = lambda n, x, y: (n / x).is_integer() and (n / y).is_integer()", "def is_divisible(n,x,y):\n \"\"\"(^__^)\"\"\"\n count = n%x or n%y\n if count == 0:\n return True\n elif count != 0:\n return False", "def is_divisible(n,x,y):\n quotient_nx = n%x\n quotient_ny= n%y\n if quotient_nx == 0 and quotient_ny == 0:\n return True\n else:\n return False\n", "def is_divisible(n, x, y):\n return True if n % x == 0 and n % y == 0 else False\n\nprint(is_divisible(100, 3, 7))", "import math\ndef is_divisible(n,x,y):\n #your code here\n a = math.trunc(n/x)\n b = math.trunc(n/y)\n return (a == n/x and b == n/y)", "def is_divisible(n,x,y):\n if n%x==0 and n%y==0:\n statement = True\n else:\n statement = False\n return statement", "def is_divisible(n,x,y):\n i = n % x\n j = n % y\n return i+j == 0", "def is_divisible(n,x,y):\n #your code here\n num = int(n)\n numx = int(x)\n numy = int(y)\n if num % x == 0 and num % y == 0:\n return True\n else:\n return False", "def is_divisible(n,x,y):\n #your code here\n \n ans = False\n \n if n%x==0 and n%y==0:\n \n ans = True\n \n return ans", "def is_divisible(n,x,y):\n a = n/x\n b = n/y\n cka = a - int(a)\n ckb = b - int(b)\n if cka > 0 or ckb > 0:\n return False\n else:\n return True", "def is_divisible(n,x,y):\n print(n, x, y)\n return True if (n / x) % 1 + (n / y) % 1 == 0 else False", "#Goal: Write a program that determines whether an integer n is divisible by integers x and y and has no remainder.\n# The program should return a True or False value.\n#General Strategy: Check to see if the remainder value of n / x and n / y is equivalent to zero.\n# Use modulus to find the remainders.\n# To return a boolean value of both remainders being zero, I can add both remainders together.\n# This will work because if both are zero the sum will be zero.\n# If not then the sum will be different and the boolean value returned will be false.\n\ndef is_divisible(n,x, y):\n # Return a boolean value by checking to see whether the sum of the remainders of n modulus x and n modulus y equals\n # zero.\n return 0 == (n % x) + (n % y)\n", "def is_divisible(n,x,y):\n if (x>n or y>n):\n return False\n else:\n if (n%x!=0 or n%y!=0):\n return False\n else:\n return True", "def is_divisible(n,x,y):\n resultone = n / x \n resulttwo = n / y\n if resultone == int(resultone) and resulttwo == int(resulttwo):\n return True \n else: \n return False", "is_divisible=lambda n,x,y:n/x==n//x and n/y==n//y", "def is_divisible(n,x,y):\n #your code here\n return True if not (bool(n % x) or bool(n % y)) else False\n", "def is_divisible(n,x,y):\n return True if (n / x).is_integer() and (n / y).is_integer() > 0 else False\n \n", "def is_divisible(n,x,y):\n if(n%x==0 and n%y==0):\n return 1\n else:\n return False\n #your code here\n", "def is_divisible(n,x,y):\n a = n / x\n b = n / y\n if a == int(a) and b == int(b):\n return True\n else:\n return False", "def is_divisible(n,x,y):\n #your code here\n F1 = (n % x == 0)\n F2 = (n % y == 0)\n\n return(F1 and F2)", "def is_divisible(n,x,y):\n if n % x == 0 and n % y == 0:\n return True\n else:\n return False\n\n\n\nprint(is_divisible(3,1,3))", "def is_divisible(n,x,y):\n if n > 0 and x > 0 and y > 0:\n if n % x == 0 and n % y == 0:\n return True\n elif n == 0 :\n return True\n else:\n return False\n else:\n return 0", "def is_divisible(n,x,y):\n if (n/x).is_integer() == False:\n return False\n if (n/y).is_integer() == False:\n return False\n else:\n return True\n", "def is_divisible(n,x,y):\n a = n%x\n b = n%y\n return False if bool(a+b) else True", "from math import gcd\ndef is_divisible(n,x,y):\n #your code here\n return True if n//(x*y/gcd(x,y))==n/(x*y/gcd(x,y)) else False"] | {"fn_name": "is_divisible", "inputs": [[3, 2, 2], [3, 3, 4], [12, 3, 4], [8, 3, 4], [48, 3, 4], [100, 5, 10], [100, 5, 3], [4, 4, 2], [5, 2, 3], [17, 17, 17], [17, 1, 17]], "outputs": [[false], [false], [true], [false], [true], [true], [false], [true], [false], [true], [true]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 15,449 |
def is_divisible(n,x,y):
|
8b1674c55823af1de93459342baec64d | UNKNOWN | Write a function that takes as its parameters *one or more numbers which are the diameters of circles.*
The function should return the *total area of all the circles*, rounded to the nearest integer in a string that says "We have this much circle: xyz".
You don't know how many circles you will be given, but you can assume it will be at least one.
So:
```python
sum_circles(2) == "We have this much circle: 3"
sum_circles(2, 3, 4) == "We have this much circle: 23"
```
Translations and comments (and upvotes!) welcome! | ["import math\n\ndef sum_circles(*args):\n t = round(sum([math.pi * (d**2) / 4 for d in args]))\n return 'We have this much circle: {}'.format(int(t))", "from math import pi\n\ndef sum_circles(*args):\n return \"We have this much circle: %.0f\" % sum([(d/2.0)**2 * pi for d in args])", "from math import pi\n\ndef sum_circles(*args):\n return 'We have this much circle: %s' % int(round(sum(pi*(d/2.0)**2 for d in args)))", "from math import pi\n\ndef sum_circles(*rs):\n total = int(round(sum(pi * r**2 / 4 for r in rs)))\n return 'We have this much circle: {}'.format(total)", "from math import pi\ndef sum_circles(*args):\n return 'We have this much circle: {}'.format(int(round(sum(pi*(d/2.0)**2 for d in args))))", "import math \n\ndef sum_circles(*args):\n totalArea = 0\n for arg in args:\n area = ((arg/2.0)**2.0) * math.pi \n totalArea += area\n return \"We have this much circle: \" + str(int(round(totalArea)))", "from math import pi\n\nOUTPUT = 'We have this much circle: {:.0f}'.format\n\n\ndef sum_circles(*args):\n return OUTPUT(sum(pi * (diameter / 2.0) ** 2 for diameter in args))\n", "import math\ndef sum_circles(*args):\n return 'We have this much circle: '+str(int(round(sum((i*i*math.pi/4) for i in args),0)))", "import math\ndef sum_circles(*args):\n y= round(sum ([(math.pi*x**2/4) for x in args]))\n return \"We have this much circle: \" +str(y)"] | {"fn_name": "sum_circles", "inputs": [[48, 7, 8, 9, 10], [1], [1, 1, 1, 2, 3, 4, 5], [894, 5778, 4839, 476], [4.5456, 746.5, 98.34, 344.543], [1, 1, 1], [13.58, 14.9, 56.99, 107.321], [56894.04839, 843975.4839, 4.08437403489], [5, 6, 7, 8, 9, 10, 105083, 48839, 4853, 28, 483]], "outputs": [["We have this much circle: 2040"], ["We have this much circle: 1"], ["We have this much circle: 45"], ["We have this much circle: 45417233"], ["We have this much circle: 538519"], ["We have this much circle: 2"], ["We have this much circle: 11916"], ["We have this much circle: 561977165367"], ["We have this much circle: 10564760498"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,432 |
def sum_circles(*args):
|
2e4808b568bdcc206450e879ecab0988 | UNKNOWN | Complete the solution so that it reverses all of the words within the string passed in.
Example:
```python
reverseWords("The greatest victory is that which requires no battle")
// should return "battle no requires which that is victory greatest The"
``` | ["def reverseWords(str):\n return \" \".join(str.split(\" \")[::-1])", "def reverseWords(str):\n return ' '.join(reversed(str.split(' ')))", "def reverseWords(string):\n return ' '.join(reversed(string.split()))", "def reverseWords(str):\n k = str.split(' ')\n k.reverse()\n str = ' '.join(k)\n return str", "def reverseWords(string):\n return ' '.join(string.split()[::-1])", "def reverseWords(str):\n str = str.split()\n str = reversed(str)\n return \" \".join(str)", "def reverseWords(str):\n\n str_list=str.split(' ')\n rev_list=str_list[::-1]\n rev_str=' '.join(rev_list)\n return rev_str", "def reverseWords(str):\n str_split = str.split()\n rev_words = []\n \n for i in range(len(str_split)-1,-1,-1):\n rev_words.append(str_split[i])\n \n return ' '.join(rev_words)", "def reverseWords(string):\n \"\"\" reverse_words == PEP8, forced camelCase by CodeWars \"\"\"\n return ' '.join(reversed(string.split()))\n", "def reverseWords(str):\n s = str.split(' ') \n string =[] \n for e in s: \n string.insert(0, e) \n return \" \".join(string)", "def reverseWords(str):\n new_arr = []\n for word in str.split():\n new_arr.append(word)\n new_arr.reverse() \n return ' '.join(new_arr)", "reverseWords = lambda s: \" \".join(s.split(\" \")[::-1])", "reverseWords = lambda s: \" \".join(reversed(s.split(\" \")))\n\n", "def reverseWords(str):\n return ' '.join([i for i in str.split(\" \")[::-1]])", "import re\ndef reverseWords(str):\n return \"\".join(re.split(r'(\\s+)', str)[::-1])", "def reverseWords(s):\n arr = s.split()\n arr = arr[::-1]\n str = ''\n for el in arr:\n str +=el+' '\n return str[:-1]", "def reverseWords(str):\n a = str.split(\" \")\n b = \"\"\n c = a[::-1]\n for i in range(0,len(a)):\n if i != len(a)-1:\n b += c[i] + \" \"\n else:\n b +=c[i]\n return(b)", "reverseWords=lambda ss:' '.join(ss.split(' ')[-1::-1]) ", "def reverseWords(str):\n liststr = str.split()\n liststr.reverse()\n newstr = ''\n for i in range(len(liststr)):\n newstr += liststr[i]\n if i != len(liststr) - 1:\n newstr += ' '\n return newstr", "def reverseWords(s):\n return ' '.join(s.split()[::-1])", "def reverseWords(s):\n b = s.split()\n b.reverse()\n return ' '.join(b)", "def reverseWords(s):\n words = s.split()\n reversed = \"\"\n index = len(words) \n while index > 0:\n index -= 1\n reversed = reversed + \" \" + (words[index])\n return reversed[1:]\n \n", "def reverseWords(s):\n words = s.split()\n i = ''\n index = len(words)\n while index > 0:\n index -= 1\n i = i+ ' ' + (words[index])\n return i[1:]", "def reverseWords(s):\n print(s)\n words = s.split()\n rev = \"\"\n i = len(words)\n while i > 0:\n i -= 1\n rev += words[i]+\" \"\n print(rev)\n return rev[:-1]", "def reverseWords(s):\n a = s.split()\n return ' '.join(reversed(a))", "def reverseWords(s):\n t = s.split()\n return ' '.join(reversed(t))", "def reverseWords(s):\n result = \"\"\n orded = s.split(\" \")\n i = len(orded)\n while i > 0:\n result += orded[i-1]\n if i > 1:\n result += \" \"\n i-=1\n return result", "def reverseWords(s):\n words = s.split(' ')\n reverse_s = ' '.join(reversed(words))\n return reverse_s", "def reverseWords(s):\n output=\"\"\n inp=s.split(\" \")\n for i in inp:\n output=\" \"+i+output\n return output[1:len(output)]", "def reverseWords(s):\n word = s.split(\" \")\n reverseWords = \" \".join(reversed(word))\n return reverseWords", "def reverseWords(s):\n s_list = s.split()\n rev_s_list = s_list[::-1]\n return \" \".join(rev_s_list)\n", "def reverseWords(s):\n s = \" \".join(s.split()[::-1])\n return s", "def reverseWords(s):\n s = s.split()\n empty = []\n while len(s) > 0:\n empty.append(s.pop())\n else:\n return ' '.join(empty)", "def reverseWords(s):\n reverse = s.split()\n strng = \"\"\n for i in range(1, len(reverse)+1):\n strng += reverse[-i] + \" \"\n return strng[:-1]", "def reverseWords(s):\n a = s.split()\n return ' '.join(a[::-1])", "def reverseWords(s):\n s = list(s.split())\n return ' '.join(reversed(s))\n \n", "def reverseWords(s):\n words = s.split()\n return ' '.join([words[-i-1] for i in range(len(words))])", "def reverseWords(s):\n\n holder = s.split(\" \")\n i, j = 0, len(holder) - 1\n while (i < j):\n holder[i], holder[j] = holder[j], holder[i]\n i += 1\n j -= 1\n\n return \" \".join(holder)\n", "def reverseWords(s):\n x = s.split()\n y = x[::-1]\n return ' '.join(y)", "def reverseWords(s):\n array = s.split()\n array.reverse()\n return ' '.join(array)", "def reverseWords(s):\n w=s.split(' ')\n output=[]\n for word in w:\n output.insert(0,word)\n return\" \".join( output)\n \n", "def reverseWords(s):\n reverse_s = s.split()\n reverse_s.reverse()\n s=\" \".join(reverse_s)\n return s", "def reverseWords(s):\n rev = [i for i in s.split()]\n return (' '.join(rev[::-1]))\n", "def reverseWords(s):\n arr = s.split()\n return \" \".join(arr[::-1])", "def reverseWords(s):\n g = s.split(\" \")\n g.reverse()\n return \" \".join(g)", "def reverseWords(s):\n reversed_str = \"\"\n s = s.split()\n for word in s:\n reversed_str = word + \" \" + reversed_str\n return reversed_str.strip()", "def reverseWords(s):\n return ' '.join(w[::-1] for w in s.split())[::-1]", "def reverseWords(s):\n spl = s.split(\" \")\n x = spl[::-1]\n new =''\n for i in x:\n new+=i + \" \"\n return new.strip()\n", "def reverseWords(s):\n ls = s.split()\n lsn = ls[::-1]\n return ' '.join(lsn)", "def reverseWords(s):\n l = s.split(\" \")\n v = []\n for i in l:\n v.insert(0,i)\n v.insert(0,\" \")\n return \"\".join(v)[1:]", "def reverseWords(s):\n return ' '.join(s.split()[::-1])\n\n # less compact version of above:\n # s = s.split() # create list of words\n # s = s[::-1] # reverse the list\n # s = ' '.join(s) # join back with spaces between\n # return s\n", "def reverseWords(s):\n a = \"\".join(i+\" \" for i in s.split()[::-1])\n return a[:-1]", "def reverseWords(s):\n s = s.split(' ')\n string = []\n for w in s:\n string.insert(0, w)\n string = ' '.join(string)\n return string[:]\n", "def reverseWords(s):\n return \" \".join(i for i in s.split()[::-1])", "def reverseWords(s):\n car=s.split()\n car=car[::-1]\n return \" \".join(car)", "def reverseWords(s):\n x = s.split()\n y = x[::-1]\n z = \" \".join(str(a) for a in y)\n return z", "def reverseWords(s):\n word = list(s.split(' '))\n word.reverse()\n return ' '.join(word)", "def reverseWords(s):\n str_split = s.split(\" \")\n \n string = \"\"\n \n for i in str_split:\n \n string = i + \" \" + string\n \n return string.rstrip()\n", "def reverseWords(s):\n x =s.split()\n x = x[::-1]\n x = ' '.join(x)\n return x", "def reverseWords(s):\n return ' '.join(reversed(str.split(s, ' ')))", "def reverseWords(s):\n for line in s.split('\\n'):\n return(' '.join(line.split()[::-1]))", "def reverseWords(s):\n return ' '.join([i for i in s.split()[::-1]])", "def reverseWords(s):\n s = s.split(\" \")\n s.reverse()\n x = \" \"\n \n return x.join(s)", "def reverseWords(s):\n rs = \" \".join(s.split()[::-1])\n return rs", "def reverseWords(s):\n a = s.split()\n a.reverse()\n b = a[0]\n a.pop(0)\n for x in a:\n b = b + \" \" + x \n return b", "def reverseWords(s):\n x=s.split()\n y=x[::-1] \n strin=''\n for i in y:\n strin+=i+ ' '\n return strin.rstrip()", "def reverseWords(s):\n s = s.split(' ')\n r = ''\n for x in range(0, len(s)):\n r += s[len(s)-x-1]\n if x != len(s)-1:\n r += ' '\n return r", "def reverseWords(s: \"\"):\n s = s.split()\n result = \"\"\n for i in s:\n result= i +\" \" +result\n return result.strip(\" \")", "def reverseWords(s):\n t = s.split()\n z = t[::-1]\n return \" \".join(z)", "def reverseWords(s):\n arr = s.split(\" \")\n arr = arr[::-1]\n return \" \".join(arr)", "def reverseWords(s):\n s = s.split(\" \")\n s.reverse()\n \n res = \" \".join(s)\n \n return res ", "def reverseWords(s):\n y = s.split(\" \")\n x = \" \".join(reversed(y))\n return x\n\n\n# Complete the solution so that it reverses \n# all of the words within the string passed in.\n", "def reverseWords(s):\n list = s.split(' ')[::-1]\n return ' '.join(list)", "def reverseWords(s):\n l=[]\n l=s.split(\" \")\n l.reverse()\n f=\"\"\n for i in l:\n f+=i+\" \"\n return f[:len(f)-1]", "def reverseWords(s):\n list_of_s = s.split(' ')\n list_of_s.reverse()\n return ' '.join(list_of_s)", "def reverseWords(s):\n a=s.split()\n a=a[::-1]\n return ' '.join(a)", "reverseWords = lambda word: ' '.join(word.split(' ')[::-1])", "def reverseWords(s):\n string = ''\n s = s.split()\n for word in reversed(range(len(s))):\n string += s[word]\n string += ' '\n string = string[:-1]\n return string", "def reverseWords(r):\n s=r.split()\n r=''\n for i in range(1,len(s)+1):\n r+=s[-i]+' '\n return r[:-1]", "def reverseWords(s):\n words = s.split()\n words = list(reversed(words))\n return \" \".join(words)", "def reverseWords(s):\n a = s.split()\n b = (a[::-1])\n return ' '.join(b)", "def reverseWords(s):\n x=[ x for x in s.split(\" \")]\n return \"\".join( x+\" \" for x in x[::-1])[ :-1]", "def reverseWords(s):\n return ' '.join(reversed([w for w in s.split()]))", "def reverseWords(s):\n my_list = s.split(' ')[::-1]\n return ' '.join(my_list)", "def reverseWords(str):\n str1 = str.split(' ')[::-1]\n return ' '.join(str1)", "def reverseWords(str):\n words = str.split()\n words = list(reversed(words))\n reverse_str = \" \".join(words)\n return reverse_str", "def reverseWords(str):\n strings = str.split(\" \")\n strings.reverse();\n return \" \".join(strings)", "def reverseWords(str):\n \n arr = str.split(\" \")\n arr.reverse()\n return \" \".join(arr).rstrip()", "def reverseWords(str):\n arr = list(str.split())\n arr.reverse()\n return ' '.join([i for i in arr])\n", "def reverseWords(str):\n arr = []\n str = str.split(' ')\n str = str[::-1]\n return ' '.join(str)\n", "def reverseWords(str):\n new_str=str.split()\n new_str=new_str[::-1]\n return \" \".join(new_str)", "def reverseWords(str):\n # Split the string on the spaces.\n list_words = str.split(\" \")\n # Using the reversed() method to go over the list in a reversed order\n # Using the join() method to join the returning elements of the list.\n return ' '.join(reversed(list_words))", "def reverseWords(str):\n a = str.split()\n b = ' '.join(reversed(a))\n return b", "def reverseWords(str):\n final_str = ''\n str_lst = str.split(' ')[::-1]\n for word in str_lst:\n final_str += word\n final_str += ' '\n return final_str.strip()\n \n", "def reverseWords(str):\n s = str.split(' ')\n ans = ''\n for i in range(len(s)-1, -1, -1):\n if i != len(s)-1 : ans += ' '\n ans += s[i]\n return ans", "def reverseWords(str):\n word = str.split(' ')\n reverse = ' '.join(reversed(word))\n return reverse", "def reverseWords(words):\n new_words = list(reversed(words.split()))\n return \" \".join(new_words)", "def reverseWords(str):\n arr = str.split(\" \")\n arr = arr[::-1]\n return \" \".join(arr)", "def reverseWords(str):\n result = \"\"\n s1 = str.split(\" \")\n print(s1)\n s2 = s1[::-1]\n print(s2)\n result = \" \".join(s2) \n return result\n", "def reverseWords(str):\n rev_list = list(str.split(' '))\n rev_str = ''\n for i in range(len(rev_list) - 1, -1, -1):\n rev_str += rev_list[i]\n if i != 0:\n rev_str += ' '\n \n \n return rev_str"] | {"fn_name": "reverseWords", "inputs": [["hello world!"]], "outputs": [["world! hello"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 12,510 |
def reverseWords(s):
|
3ea48e881c2e15094bbe735a0b847abd | UNKNOWN | There is a queue for the self-checkout tills at the supermarket. Your task is write a function to calculate the total time required for all the customers to check out!
### input
```if-not:c
* customers: an array of positive integers representing the queue. Each integer represents a customer, and its value is the amount of time they require to check out.
* n: a positive integer, the number of checkout tills.
```
```if:c
* customers: a pointer to an array of positive integers representing the queue. Each integer represents a customer, and its value is the amount of time they require to check out.
* customers_length: the length of the array that `customers` points to.
* n: a positive integer, the number of checkout tills.
```
### output
The function should return an integer, the total time required.
-------------------------------------------
## Important
**Please look at the examples and clarifications below, to ensure you understand the task correctly :)**
-------
### Examples
```python
queue_time([5,3,4], 1)
# should return 12
# because when n=1, the total time is just the sum of the times
queue_time([10,2,3,3], 2)
# should return 10
# because here n=2 and the 2nd, 3rd, and 4th people in the
# queue finish before the 1st person has finished.
queue_time([2,3,10], 2)
# should return 12
```
### Clarifications
* There is only ONE queue serving many tills, and
* The order of the queue NEVER changes, and
* The front person in the queue (i.e. the first element in the array/list) proceeds to a till as soon as it becomes free.
N.B. You should assume that all the test input will be valid, as specified above.
P.S. The situation in this kata can be likened to the more-computer-science-related idea of a thread pool, with relation to running multiple processes at the same time: https://en.wikipedia.org/wiki/Thread_pool | ["def queue_time(customers, n):\n l=[0]*n\n for i in customers:\n l[l.index(min(l))]+=i\n return max(l)", "import heapq\n\ndef queue_time(customers, n):\n heap = [0] * n\n for time in customers:\n heapq.heapreplace(heap, heap[0] + time)\n return max(heap)\n", "def queue_time(customers, n):\n qn = [0] * n\n for c in customers:\n qn = sorted(qn)\n qn[0] += c\n return max(qn)", "def queue_time(customers, n):\n queues = [0] * n\n for i in customers:\n queues.sort()\n queues[0] += i\n return max(queues)", "class MarketQueue():\n \n def __init__(self,customers,n):\n self.customers = customers\n self.n=n\n self.timer = 0\n self.active_checkouts = []\n \n def calculate_total_time(self):\n while self.customers:\n self.process_queue() \n return self.timer\n\n def process_queue(self):\n if len(self.active_checkouts) < self.n:\n queue_index = self.n - len(self.active_checkouts)\n self.active_checkouts.extend(self.customers[:queue_index])\n self.customers[:queue_index] = []\n while self.active_checkouts and (len(self.active_checkouts) == self.n or not self.customers) :\n self.timer += 1\n self.process_active_checkouts()\n \n def process_active_checkouts(self):\n finished_customers = []\n for index,customer in enumerate(self.active_checkouts):\n if customer > 1:\n self.active_checkouts[index] = int(customer-1)\n else:\n finished_customers.append(customer)\n \n for finished in finished_customers:\n self.active_checkouts.remove(finished)\n\n# implementing requirements\ndef queue_time(customers,n):\n return MarketQueue(customers,n).calculate_total_time()", "def queue_time(customers, n):\n tills = [0] * n\n for i in customers:\n indexMin = tills.index(min(tills))\n tills[indexMin] += i\n return max(tills)\n", "def queue_time(customers, n):\n tills = [0 for i in range(n)]\n\n for time in customers:\n min_index = tills.index(min(tills))\n tills[min_index] += time\n\n return max(tills)", "def queue_time(customers, n):\n time = 0\n while len(customers[:])>0:\n time=time+1\n customers[:n]=[x-1 for x in customers[:n]]\n customers=[y for y in customers if y !=0]\n return time", "def queue_time(cu, n):\n q=[0]*n\n for i in cu:\n s=q.index(min(q))\n q[s]+=i\n return max(q)", "def queue_time(customers, n):\n cajas = [0]*n\n for i in customers:\n cajas[0] += i\n cajas = sorted(cajas)\n print (cajas)\n return cajas[-1]"] | {"fn_name": "queue_time", "inputs": [[[], 1], [[5], 1], [[2], 5], [[1, 2, 3, 4, 5], 1], [[1, 2, 3, 4, 5], 100], [[2, 2, 3, 3, 4, 4], 2]], "outputs": [[0], [5], [2], [15], [5], [9]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,776 |
def queue_time(customers, n):
|
2887312ad9c09f2ad3ea75a7fd3b68d6 | UNKNOWN | # Problem
In China,there is an ancient mathematical book, called "The Mathematical Classic of Sun Zi"(《孙子算经》). In the book, there is a classic math problem: “今有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二,问物几何?”
Ahh, Sorry. I forgot that you don't know Chinese. Let's translate it to English:
There is a unkown positive integer `n`. We know:
`n % 3 = 2`, and `n % 5 = 3`, and `n % 7 = 2`.
What's the minimum possible positive integer `n`?
The correct answer is `23`.
# Task
You are given three non-negative integers `x,y,z`. They represent the remainders of the unknown positive integer `n` divided by 3,5,7.
That is: `n % 3 = x, n % 5 = y, n % 7 = z`
Your task is to find the minimum possible positive integer `n` and return it.
# Example
For `x = 2, y = 3, z = 2`, the output should be `23`
`23 % 3 = 2, 23 % 5 = 3, 23 % 7 = 2`
For `x = 1, y = 2, z = 3`, the output should be `52`
`52 % 3 = 1, 52 % 5 = 2, 52 % 7 = 3`
For `x = 1, y = 3, z = 5`, the output should be `103`
`103 % 3 = 1, 103 % 5 = 3, 103 % 7 = 5`
For `x = 0, y = 0, z = 0`, the output should be `105`
For `x = 1, y = 1, z = 1`, the output should be `1`
# Note
- `0 <= x < 3, 0 <= y < 5, 0 <= z < 7`
- Happy Coding `^_^` | ["def find_unknown_number(x,y,z): \n return (x*70 + y*21 + z*15) % 105 or 105", "def find_unknown_number(x,y,z):\n for i in range(1,1000):\n if i%3 == x and i%5 == y and i%7 == z:\n return i", "def find_unknown_number(x,y,z):\n return min(set(range(x or 3, 106, 3)) & set(range(y or 5, 106, 5)) & set(range(z or 7, 106, 7)))", "def find_unknown_number(x,y,z):\n for n in range(1, 99999999):\n if n % 3 == x and n % 5 == y and n % 7 == z:\n return n", "def find_unknown_number(x,y,z):\n answer = 1\n i = 1\n n = 106\n \n while i < n:\n if i % 3 == x and i % 5 == y and i % 7 == z:\n answer = i\n break\n i = i + 1\n return answer", "def find_unknown_number(x, y, z):\n return next(n for n in range(1, int(1e8)) if n%3 == x and n%5 == y and n%7 == z)", "def find_unknown_number(x,y,z):\n #..\n n=0\n while True:\n n+=1\n a=n%3\n b=n%5\n c=n%7\n if a==x and b==y and c==z:\n return n", "find_unknown_number = lambda *a: next(i for i in __import__(\"itertools\").count(1) if all(i % x == a[j] for j, x in enumerate((3, 5, 7))))", "def find_unknown_number(x, y, z):\n return 105 if (x + y + z == 0) else (set(range(x, 106, 3)) & set(range(y, 106, 5)) & set(range(z, 106, 7))).pop()", "def find_unknown_number(x,y,z):\n r = z if z > 0 else 7\n while r % 3 != x or r % 5 != y or r % 7 != z:\n r = r + 7\n \n return r"] | {"fn_name": "find_unknown_number", "inputs": [[2, 3, 2], [1, 2, 3], [1, 3, 5], [0, 0, 0], [1, 1, 1]], "outputs": [[23], [52], [103], [105], [1]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,502 |
def find_unknown_number(x,y,z):
|
a0fc61b0afabc39e29a32f2af992ffae | UNKNOWN | You receive the name of a city as a string, and you need to return a string that shows how many times each letter shows up in the string by using an asterisk (`*`).
For example:
```
"Chicago" --> "c:**,h:*,i:*,a:*,g:*,o:*"
```
As you can see, the letter `c` is shown only once, but with 2 asterisks.
The return string should include **only the letters** (not the dashes, spaces, apostrophes, etc). There should be no spaces in the output, and the different letters are separated by a comma (`,`) as seen in the example above.
Note that the return string must list the letters in order of their first appearence in the original string.
More examples:
```
"Bangkok" --> "b:*,a:*,n:*,g:*,k:**,o:*"
"Las Vegas" --> "l:*,a:**,s:**,v:*,e:*,g:*"
```
Have fun! ;) | ["from collections import Counter\n\n\ndef get_strings(city):\n return \",\".join(f\"{char}:{'*'*count}\" for char, count in Counter(city.replace(\" \", \"\").lower()).items())", "from collections import Counter\n\n\ndef get_strings(city):\n return \",\".join(\n f\"{char}:{'*'*count}\"\n for char, count in list(Counter(city.replace(\" \", \"\").lower()).items())\n if char.isalpha()\n )\n", "def get_strings(city):\n city = city.lower()\n result = \"\"\n for i in city:\n if i in result:\n pass\n elif i == \" \":\n pass\n else:\n result += i + \":\" + (\"*\" * city.count(i)) + \",\"\n\n return result[:-1]", "def get_strings(city):\n city = city.lower().replace(\" \", \"\")\n return \",\".join(sorted([f\"{i}:{city.count(i)*'*'}\" for i in set(city)], key=lambda x:city.index(x[0])))", "from collections import Counter\n\ndef get_strings(city):\n c = Counter(filter(str.isalpha, city.lower()))\n return ','.join(f'{ k }:{ \"*\"*v }' for k,v in c.items())", "def get_strings(s):\n return ','.join(f\"{i}:{'*'*s.lower().count(i)}\" for i in dict.fromkeys(s.replace(' ','').lower()))", "def get_strings(city):\n city=city.lower().replace(' ','')\n return ','.join(f'{c}:'+'*'*(city.count(c)) for c in dict.fromkeys(city))", "from collections import Counter\ndef get_strings(city):\n lst = []\n for key, value in dict(Counter(city.replace(' ', '').lower())).items():\n lst.append(key+':'+'*'*value)\n return ','.join(lst)", "import re\n\ndef get_strings(city):\n cache = {}\n r_string = ''\n counter = 0\n city = re.sub(' ','', city)\n \n for letter in city.lower():\n if letter not in cache:\n cache[letter] = 0 \n cache[letter] +=1\n else:\n cache[letter] +=1\n \n for k,v in cache.items():\n if counter < len(cache)-1:\n r_string += k + ':' + ('*' * v)+','\n counter += 1\n elif counter < len(cache):\n r_string += k + ':' + ('*' * v)\n return r_string", "from collections import Counter\n\n\ndef get_strings(city):\n return \",\".join(\n f\"{char}:{'*'*count}\"\n for char, count in Counter(city.replace(\" \", \"\").lower()).items()\n if char.isalpha()\n )", "def get_strings(city):\n city = list(city.lower())\n con = {}\n for char in city:\n if char == \" \":\n pass\n else:\n con[char] = city.count(char) * \"*\"\n first = True\n result = \"\"\n for item in con.keys():\n if first == True:\n first = False\n result+= item + \":\" + con.get(item)\n else:\n result+= \",\" + item + \":\" + con.get(item)\n return result", "import json\ndef get_strings(city):\n city = city.lower()\n city = city.replace(\" \",\"\")\n c = {}\n for i in city:\n if i in c:\n c[i] += \"*\"\n else:\n c[i] = \"*\"\n \n final = json.dumps(c)\n final = (final.replace(\"{\",\"\").replace(\"}\",\"\").replace(\" \",\"\").replace('\"',\"\"))\n \n return final", "def get_strings(city):\n index = 0\n string = ''\n city = city.lower()\n city = city.replace(' ', '')\n for i in city:\n asterisks = city.count(i)\n if i in string:\n index = index + 1\n else:\n if index == (len(city) - 1) and i not in string:\n string += i.lower() + ':' + ('*' * asterisks)\n if index != (len(city) - 1):\n string += i.lower() + ':' + ('*' * asterisks) +','\n index = index + 1\n if string[-1] == ',': \n lst = list(string)\n lst[-1] = ''\n new = ''.join(lst)\n return new\n return string\n \n", "from collections import Counter\ndef get_strings(city):\n return ','.join(f'{e}:{\"*\"*c}' for e,c in Counter(city.lower()).items() if e.isalpha())", "from collections import Counter\n\ndef get_strings(city):\n return ','.join(f\"{k}:{'*'*v}\" for k,v in Counter(filter(str.isalpha, city.lower())).items())", "def get_strings(city):\n s, city = str(), ''.join(city.lower().split())\n for i in city:\n if i not in s:\n s+= i+':'+'*'*city.count(i)+','\n return s[:-1]", "from collections import Counter\n\ndef get_strings(word):\n return ','.join(\n f'{letter}:{\"*\" * count}'\n for letter, count in Counter(word.lower()).items()\n if letter.isalpha())", "from collections import Counter\ndef get_strings(city):\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n city_str = ''\n city_dict = Counter(city.lower())\n for key in city_dict:\n if key in alphabet:\n city_str += key + ':' + '*' * city_dict[key] + ','\n return city_str[:-1]", "def get_strings(city):\n \n ciu = {}\n \n for letra in city.lower().replace(\" \",\"\"):\n if letra not in ciu:\n ciu[letra] = \"*\"\n else: \n ciu[letra] += \"*\"\n \n \n array = []\n for clave in ciu:\n \n array.append(\"{}:{}\".format(clave, ciu[clave]))\n \n return \",\".join(array).replace(\" \",\"\")\n\n", "from collections import Counter\ndef get_strings(city):\n return ','.join([k.lower() + ':' + '*'*v for k, v in Counter(city.lower()).items() if k.isalpha()])", "from collections import Counter\n\ndef get_strings(city):\n return ','.join(\n f'{letter}:{\"*\" * count}' \n for letter, count in list(Counter(city.lower()).items())\n if letter != ' '\n )\n", "def get_strings(city):\n counts = {}\n \n for c in city.lower():\n if c.isalpha():\n counts[c] = counts[c] + \"*\" if c in counts else \"*\"\n \n return \",\".join([f\"{c}:{a}\" for (c, a) in counts.items()])", "get_strings=lambda s:','.join(k+':'+s.lower().count(k)*'*'for k in dict.fromkeys(s.lower().replace(' ','')))", "def get_strings(city):\n city = city.lower()\n city = list(city)\n dicti = {}\n strres = \"\"\n\n for i in city:\n if ord(i) > 96 and ord(i) < 123:\n if i in dicti:\n dicti[i] += 1\n else:\n dicti[i] = 1\n \n for i in dicti:\n strres = strres + i + \":\" + (\"*\"*dicti[i]) + \",\"\n \n strres = strres[:-1]\n\n return strres\n", "def get_strings(city):\n return \",\".join([i + \":\" + '*' * city.lower().count(i) for i in dict.fromkeys(city.lower().replace(' ', ''))])", "def get_strings(stra):\n string = stra.lower()\n dc = {}\n for i in string:\n if i == ' ':\n continue\n dc[i] = '*' * string.count(i)\n \n return ','.join([k + ':' + v for k, v in list(dc.items())])\n", "def get_strings(city):\n res = {}\n for i in city.lower().replace(' ',''):\n res[i] = res.get(i, '') + '*'\n\n return ','.join([f'{k}:{v}' for k,v in res.items()])", "from collections import OrderedDict\ndef get_strings(city):\n values = [i for i in city.replace(' ','').lower()]\n v2 = [j +':'+'*'*values.count(j) for j in values]\n return ','.join(list(OrderedDict.fromkeys(v2)))", "\ndef get_strings(city):\n city = city.lower()\n city = city.replace(\" \",\"\")\n cit_str = \"\"\n usedletters=[]\n for letter in city:\n if letter in usedletters:\n pass\n else:\n cit_str += letter + \":\" \n l_num = city.count(letter)\n for num in range(0,l_num):\n cit_str += \"*\"\n cit_str += \",\"\n usedletters.append(letter)\n \n return cit_str[:-1]", "get_strings = lambda city: \"\".join(list(dict.fromkeys([\"{}:{},\".format(i, \"*\" * city.lower().count(i)) for i in city.lower() if i != \" \"]))).rstrip(\",\")", "from collections import Counter\ndef get_strings(city):\n return \",\".join([f'{k}:{v*\"*\"}' for k,v in Counter(city.lower()).items() if k.isalpha()])", "from collections import Counter\ndef get_strings(city):\n d = dict(Counter(city.lower()))\n ret = [f'{k}:{v*\"*\"}' for k,v in d.items() if k.isalpha()]\n return \",\".join(ret)", "def get_strings(city):\n city = city.lower().replace(' ', '')\n dict = {}\n for l in city:\n if l in dict:\n dict[l] += '*'\n else:\n dict[l] = '*'\n result = ''\n for i in dict:\n result += i + ':' + dict[i] + ','\n return result[:-1]", "def get_strings(city):\n memory = {}\n\n for char in city:\n if char.isspace():\n continue\n char = char.lower()\n if char not in memory.keys():\n memory[char] = \"*\"\n else: \n memory[char] += \"*\"\n\n return_str = \"\"\n for k,v in memory.items():\n return_str += k + \":\" + v + \",\"\n \n return return_str[:-1]", "def get_strings(city):\n city=city.lower()\n storage=[]\n hold=\"\"\n for i in (city):\n if i.isalpha()==True and str(i) not in hold:\n storage.append(str(i)+':'+ (city.count(i))*'*')\n hold+=str(i)\n return \",\".join(storage)", "from collections import OrderedDict\n\ndef get_strings(city):\n return ','.join(f'{letter}:{\"*\"*city.lower().count(letter)}' for letter in {letter:None for letter in city.lower() if letter.isalpha()})", "def get_strings(inputString):\n checkDict={\n \"letter\":[],\n \"count\":[]\n }\n charArray = list(inputString.lower())\n for i in charArray:\n if i in checkDict['letter']:\n k=checkDict['letter'].index(i)\n checkDict['count'][k]= checkDict['count'][k]+'*'\n else:\n if (i.isalpha()):\n checkDict['letter'].append(i)\n checkDict['count'].append('*')\n #print(checkDict) om de dictionary te bekijken\n outputString = ''\n for i in checkDict['letter']:\n indexLetter = checkDict['letter'].index(i)\n outputString = outputString + i + ':' + checkDict['count'][indexLetter] + ','\n return outputString[:-1]", "def get_strings(city):\n myMap = {}\n for i in range(len(city)):\n letter = city[i].lower()\n if letter not in myMap:\n myMap[letter] = 1\n else:\n myMap[letter] = myMap.get(letter)+1\n\n myMap.pop(' ', None)\n\n\n result = ''\n for item in myMap:\n result = result + item + ':'\n for i in range(myMap.get(item)):\n result += '*'\n result += ','\n\n\n return result[:-1]", "def get_strings(city):\n letters = {}\n for letter in city.lower():\n if letter in letters:\n value = letters[letter]\n value += 1\n letters.update({letter : value})\n else:\n letters.update({letter : 1})\n result = \"\"\n for letter in city.lower().replace(\" \", \"\"):\n if letter not in result:\n result += letter + ':' + '*' * letters[letter] + ',' \n return result[:-1]", "from collections import Counter\n\n\ndef get_strings(city):\n counting = Counter(city.lower()) # makes sure everything is lowercase\n dict(counting)\n output =''\n #print(counting.items())\n for key, value in counting.items():\n \n if len(key.strip()) > 0: #checks for whitespace, (0 is returned if there is whitespace)\n output += key + ':' + ('*'*value)+',' #formats the output according to the task description\n \n output = output[:-1] #removes the last ','\n print(output) \n return output", "def get_strings(city):\n result = ''\n d = {}\n for letter in city.lower():\n d[letter] = d.get(letter, 0) + 1\n for letter in city.lower().replace(' ',''): \n if not letter in result: \n result += letter+':'+'*'*d[letter]+','\n return result[:-1]", "\ndef get_strings(city):\n new = city.lower().replace(' ','')\n \n list = []\n for x in new:\n c = new.count(x)\n y = x+\":\"+\"*\"*c\n if y not in list:\n list.append(y)\n \n s = ','.join(list)\n \n return s\n", "def get_strings(city):\n \n # convert to lower case alphabet\n city_alpha = \"\".join(x.lower() for x in city if x.isalpha())\n \n # order of appearance and count\n seen_cnt, order = {}, \"\"\n for x in city_alpha :\n if x not in seen_cnt :\n seen_cnt[x]=1 \n order += x\n else :\n seen_cnt[x] += 1\n \n # generate output\n output = \"\"\n for x in order :\n output += \",\"+x+\":\"+\"*\"*seen_cnt[x]\n \n return output[1:]", "def get_strings(city):\n res = {}\n for x in city.lower():\n if x.isalpha():\n res[x] = city.lower().count(x)\n return \",\".join([ \"%s:%s\" % (x,\"*\"*res[x]) for x in res])", "def get_strings(city):\n \n city = city.replace(' ','').lower()\n city_string = ''\n \n for i in city:\n if i in city_string:\n pass\n else:\n city_string += i +':'+ ('*'* city.count(i))+','\n \n result = city_string[:-1]\n\n return result ", "from collections import Counter\n\ndef get_strings(city):\n return ','.join([f\"{char}:{'*' * char_count}\" for (char, char_count) \n in list(dict(Counter(city.lower())).items()) if char != ' ' ])\n", "def get_strings(city):\n city = city.lower().replace(\" \", \"\")\n arr = []\n for el in city:\n if el not in arr:\n arr.append(el)\n return \",\".join([f\"{el}:{city.count(el) * '*'}\" for el in arr])", "def get_strings(city):\n city = city.lower().replace(\" \", \"\")\n a = []\n for el in city:\n if el not in a:\n a.append(el)\n return \",\".join([f'{el}:{\"*\"*city.count(el)}' for el in a])", "def get_strings(city):\n result = ''\n city = city.lower().replace(' ', '')\n for i in city:\n if i not in result:\n result += f'{i}:{\"*\"*city.count(i)},'\n return result[:-1]", "def get_strings(city):\n city=city.lower().strip()\n letters_count={}\n \n def star_print(int):\n star_string=\"\"\n for i in range(int):\n star_string=star_string+\"*\"\n return star_string\n \n for letter in city:\n if letter.isalpha(): \n if letter in letters_count:\n letters_count[letter]=letters_count[letter]+1\n else:\n letters_count[letter]=1\n \n ans_string=\"\"\n for items in letters_count:\n temp_string=str(items)+\":\"+star_print(letters_count[items])+\",\"\n ans_string=ans_string+temp_string\n ans_string=ans_string[0:-1]\n return ans_string", "def c(lista):\n x = lambda a:(a,lista.count(a))\n return x\ndef star(n):\n s = ''\n for i in range(n):\n s = s +'*'\n return s\n \ndef remover(lista):\n l = []\n for i in lista:\n if i in l : continue\n l.append(i)\n return l \ndef get_strings(city):\n letters = remover(list((city.lower())))\n huss = list(map(c(city.lower()) , letters))\n \n s = ''\n for letter,co in huss:\n if letter == ' ': continue\n s = s + letter + ':'+star(co)+',' \n s = s.strip()\n return s[:-1]\n \n", "def get_strings(city):\n \n string = city.lower().replace(' ','')\n output = \"\"\n for char in string:\n if char not in output:\n print((string.count(char)))\n output += (f'{char}:{\"*\" * string.count(char)},')\n \n return output[:-1]\n\n\n\n", "def get_strings(city):\n soln = []\n used = ''\n for letter in city.lower():\n if letter in used or letter == ' ':\n continue\n else:\n solnstring = ''\n solnstring += letter + ':'\n for x in range(city.lower().count(letter)):\n solnstring += '*'\n soln.append(solnstring)\n used += letter\n return ','.join(soln)", "def get_strings(str):\n output = \"\"\n str = str.lower().replace(' ', '')\n for char in str:\n if char not in output:\n output += (f'{char}:{\"*\" * str.count(char)},');\n return output[:-1]", "def get_strings(city):\n a=[]\n b=[]\n for i in city.lower(): \n if i==\" \": continue\n if i in a:\n continue\n a+=[i]\n b+=[str(i)+\":\"+\"*\"*city.lower().count(i)]\n return \",\".join(b)", "def get_strings(city):\n formatRes = \"\"\n string = \"\"\n newCity = city.lower().replace(' ', '')\n main = {}\n i = 0\n k = 0\n while i < len(newCity):\n if main.get(newCity[i]):\n bef = main[newCity[i]]\n main[newCity[i]] = bef + \"*\"\n i += 1\n else:\n main[newCity[i]] = \"*\"\n formatRes += newCity[i]\n i += 1\n while k < len(formatRes):\n string = string + formatRes[k]+\":\"+ main[formatRes[k]]+\",\"\n k+=1\n return string[:-1]", "def get_strings(city):\n result = {}\n for i in city.lower():\n if i in result and i != \" \":\n result[i] += \"*\"\n elif i not in result and i != \" \":\n result[i] = \"*\"\n test = []\n for k, v in list(result.items()):\n test.append((k+':'+v))\n return \",\".join(test)\n \n", "def get_strings(city):\n formatedS = city.replace(' ', '').lower()\n res = \"\"\n count = 1\n for x,c in enumerate(formatedS):\n for d in formatedS[x+1:]:\n if(d == c):\n count += 1\n if c not in res:\n res += c + \":\" + \"*\" * count + \",\"\n count = 1\n return res[:-1]", "def get_strings(city):\n l = []\n city = city.lower()\n city = city.replace(\" \",\"\")\n for char in city:\n ast = city.count(char) * \"*\"\n l.append(\"%s:%s,\" %(char,ast)) \n l = list(dict.fromkeys(l))\n city = \"\".join(l)\n return city[0:-1]\n", "def get_strings(city):\n city = city.replace(\" \", \"\")\n characters = list((city).lower())\n char_dict = {}\n final = \"\"\n for char in characters:\n if char in char_dict.keys():\n char_dict[char] = char_dict[char] + \"*\"\n else: \n char_dict[char] = char + \":*\"\n for key in char_dict.values():\n final = final + (key + \",\")\n return final[:-1]", "def get_strings(city):\n dic = {} \n for chr in city.lower():\n if chr.isalpha():\n dic[chr]=dic.get(chr,'')+'*'\n return ','.join([i+':'+dic[i] for i in dic])", "def get_strings(city):\n record = []\n text = ''.join(city.split()).lower()\n collect = {}\n counter = 0\n for i in range(len(text)):\n if text[i] not in collect:\n counter = text.count(text[i])\n collect[text[i]] = ':' + counter * '*'\n else:\n counter += 1\n\n for x,y in list(collect.items()):\n record.append(x+y)\n\n return ','.join(record)\n", "\ndef get_strings(city):\n city = city.replace(' ', '')\n city = city.lower()\n\n d = dict()\n for letter in city:\n if letter not in d:\n d[letter] = '*'\n else:\n d[letter] += '*'\n\n letter_list = list(map(lambda v: f'{v[0]}:{v[1]}', d.items()))\n return ','.join(letter_list)", "def get_strings(city):\n print(city)\n city, m, mas, l = city.lower(), \"\", [], []\n for i in set(city.lower()):\n if city.count(i) > 1:\n mas.append(i)\n l.append(city.count(i))\n for j in range(city.count(i) - 1): city = city[:city.rindex(i)] + city[city.rindex(i) + 1:]\n for i in city:\n if i in mas: m += i + \":\" + \"*\" * l[mas.index(i)] + \",\"\n elif i != \" \": m += i + \":*\" + \",\"\n return m[:len(m)-1]\n", "def get_strings(city):\n city = city.lower()\n res = []\n for x in city:\n c = city.count(x)\n st = f\"{x}:{'*'*c}\"\n if x.isalpha() and not st in res:\n res.append(st)\n return \",\".join(res)", "def get_strings(city):\n city_list = list(city.lower())\n empty = []\n abet = [chr(i) for i in range(ord('a'), ord('z')+1)]\n res = ''\n for i in range(0, len(city_list)):\n c = 0\n letter = city_list[i]\n for j in range(0, len(city_list)):\n if letter in abet:\n if letter == city_list[j]:\n c += 1\n city_list[j] = ''\n else:\n continue\n if letter in abet:\n res += letter+':'+c*'*'+',' \n else: continue\n return res[0:len(res)-1]", "from collections import Counter\ndef get_strings(city):\n counts = Counter(city.replace(' ', '').lower())\n return (','.join([f'{x}:{\"*\" * counts[x]}' for x in counts]))", "from collections import OrderedDict\ndef get_strings(city):\n city = city.lower().replace(\" \", \"\")\n city_short = \"\".join(OrderedDict.fromkeys(city))\n city_string = \"\"\n for char1, char2 in zip(city, city_short):\n value = city.count(char2)\n city_string += f\"{char2}:{value * '*'},\"\n city_string = city_string[:-1]\n return city_string", "def get_strings(city):\n city = list(city.lower())\n if ' ' in city:\n for _ in range(city.count(' ')):\n city.remove(' ')\n r = ''\n while len(city):\n w = city[0]\n r += str(w)+\":\"+ '*'*int(city.count(w))+ ','\n for _ in range(city.count(w)):\n city.remove(w)\n return r[:-1]", "def get_strings(city):\n city = city.lower()\n return \",\".join(f\"{letter}:{count*'*'}\" for letter, count in {letter: city.count(letter) for letter in city if not letter.isspace()}.items())", "def get_strings(city):\n city = city.lower()\n return ','.join(f\"{c}:{'*' * city.count(c)}\" for c in dict.fromkeys(city) if c.isalpha())", "def get_strings(city):\n city = city.lower()\n return ','.join([f\"{k}:{v}\" for k,v in {c: '*'*city.count(c) for c in city if c != \" \"}.items()])", "def get_strings(city):\n string = []\n for i in city.lower():\n n = city.lower().count(i)\n if i + ':' + '*' * n not in string and i.isalpha():\n string.append(i + ':' + '*' * n)\n return \",\".join(string)\n\n", "def get_strings(city):\n dic = dict()\n for c in city.lower():\n if c.isalpha and c != \" \":\n dic[c] = dic.get(c, 0) + 1\n result = list()\n for key , value in dic.items():\n result.append('{}:{}'.format(key, value * '*'))\n out = ','.join(result)\n return out", "# takes string of city name\n# returns string with all chars in city counted, count represented as *\ndef get_strings(city):\n dic = {}\n city = city.lower()\n for i in range(len(city)):\n if city[i] != \" \":\n dic[city[i]] = city.count(city[i])\n output: str = ','.join(\"{}:{}\".format(key, val*\"*\") for (key, val) in list(dic.items()))\n return output\n\n\n", "def get_strings(city):\n city = city.lower()\n emptystr = ''\n for letter in city.lower():\n num = city.count(letter)\n if letter not in emptystr:\n if letter == ' ':\n continue\n else:\n emptystr += letter + ':' + str(num * '*') + ','\n else:\n pass\n return emptystr[:-1]", "def get_strings(city):\n alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n city_1 = \"\"\n for i in city:\n if i.lower() not in city_1 and i.isalpha():\n city_1 += i.lower()\n else:\n pass\n return \",\".join('{}:{}'.format(i, '*' * city.lower().count(i)) for i in city_1)", "def get_strings(city):\n city = city.lower().replace(' ', '')\n lst = [f'{x}:{\"*\" * city.count(x)}' for x in sorted(set(city), key=lambda x: city.index(x))]\n return ','.join(lst)", "def get_strings(city):\n city = city.lower()\n emptystr = ''\n for letter in city.lower():\n num = city.count(letter)\n if letter not in emptystr:\n if letter == ' ':\n continue\n else:\n if letter is not city[-1]:\n emptystr += letter + ':' + str(num * '*') + ','\n else:\n emptystr += letter + ':' + str(num * '*') + ','\n else:\n pass \n if emptystr[-1] == ',':\n return emptystr[:-1]\n else:\n return emptystr", "def get_strings(city):\n l = []\n [l.append(f\"{x}:{city.lower().count(x)*'*'}\") for x in city.lower() if f\"{x}:{city.lower().count(x)*'*'}\" not in l and x != \" \"]\n return ','.join(l)", "def get_strings(city):\n dict_letters = {}\n \n for i in city.replace(' ', '').lower():\n if i in dict_letters:\n dict_letters[i] += '*'\n else:\n dict_letters[i] = '*'\n \n string_counts= ''\n for k,v in dict_letters.items():\n string_counts += k + ':' + v + ','\n return string_counts[:-1]", "def get_strings(city):\n lettercount = []\n check = ''\n \n for i in city.lower():\n \n if i not in check and i.isalpha():\n check = check + i\n string = '{}:{}'.format(i, city.lower().count(i)*'*')\n lettercount.append(string)\n \n return ','.join(lettercount)", "def get_strings(city):\n dict = {}\n for c in city.lower():\n if not c.isspace():\n if c in dict:\n dict[c] += 1\n else:\n dict[c] = 1\n out = ''\n count = 1\n for x in dict:\n out += x + ':' + dict[x]*'*'\n if count != len(dict):\n out += ','\n count += 1\n return(out)", "def get_strings(city):\n city = city.lower()\n c = []\n b = []\n for ans in city:\n if ans not in b and ans!=\" \":\n b += ans\n c += [ans+\":\"+city.count(ans)*\"*\"]\n# c += [ans+\":\"+city.count(ans)*\"*\" for ans in city if (ans not in c and ans!=\" \")]\n return \",\".join(c)\n", "from collections import Counter\n\ndef get_strings(city):\n city = [elem for elem in city.lower() if elem.islower()]\n a = Counter(city)\n return ','.join(f\"{elem}:{'*' * a[elem]}\" for elem in list(a.keys()))\n", "from collections import Counter\ndef get_strings(city):\n myList = []\n counter = Counter(city.lower())\n for letter in counter:\n if letter == \" \":\n pass\n else:\n myList.append(letter + \":\" + str(\"*\"*city.lower().count(letter)))\n return \",\".join(myList)", "def get_strings(city):\n z=str()\n city=city.replace(\" \",\"\").lower()\n for i in city:\n cnt=int(city.count(i))\n j=1\n y=''\n if z.find(i) == -1 :\n y=i+':'\n while j<= cnt :\n y=y+'*'\n j=j+1\n y=y+','\n z=z+y\n\n return z[:-1]", "from collections import Counter\ndef get_strings(city):\n l = []\n d = Counter(city.lower())\n for c,n in d.items():\n if c == \" \":\n continue\n l.append(c+\":\"+\"*\"*n)\n return \",\".join(l)", "from collections import Counter\ndef get_strings(city):\n return ','.join(f'{k}:{\"*\"*v}' for k, v in Counter(city.lower().replace(' ','')).items())", "from collections import Counter\ndef get_strings(city):\n return ','.join((a+f':{\"*\" * b}' for a,b in Counter(city.lower().replace(' ', '')).items()))", "def get_strings(city):\n city = city.lower()\n alpha = 'abcdefghijklmnopqrstuvwxyz'\n city_dict = {}\n for char in city:\n if char not in alpha: continue\n if char in city_dict:\n city_dict[char] += '*'\n continue\n city_dict[char] = '*'\n output = ''\n for k in city_dict:\n output += f'{k}:{city_dict[k]},'\n return output[0:-1]\n", "def get_strings(city):\n #create lower_case city only with letters\n new_city = ''.join(filter(str.isalpha, city.lower()))\n \n #list of unique letters\n char_seen=[]\n for char in new_city:\n if char not in char_seen:\n char_seen.append(char)\n \n #list of counts for unique letters\n count_char = []\n for char in char_seen:\n x =new_city.count(char)\n count_char.append(x)\n \n #create dictionary with two parallel list\n d = dict(zip(char_seen, count_char))\n\n total_str = \"\"\n for char, count in d.items():\n total_str += char + \":\" + count*\"*\" + \",\" #using += to append instead\n\n \n return total_str[:-1]", "def get_strings(city):\n new_city = ''.join(filter(str.isalpha, city.lower()))\n char_seen=[]\n for char in new_city:\n if char not in char_seen:\n char_seen.append(char)\n\n count_char = []\n for char in char_seen:\n x =new_city.count(char)\n count_char.append(x)\n\n d = dict(zip(char_seen, count_char))\n\n total_str = []\n for char, count in d.items():\n count_str = char + \":\" + count*\"*\"\n total_str.append(count_str)\n \n return ','.join(total_str)", "def get_strings(city):\n cityDict = {}\n for i in city.lower():\n if i.isalpha():\n if i not in cityDict:\n cityDict[i] = 1\n else:\n cityDict[i] += 1\n \n chars = []\n for i in cityDict.keys():\n chars.append(\"{}:{}\".format(i, '*' * cityDict[i]))\n \n return ','.join(chars)", "def get_strings(city):\n \n city = city.lower() \n result = ''\n \n for i in city: \n if not(i.isalpha()): \n pass\n elif i in result: \n pass \n else: \n result += f'{i}:{\"*\" * city.count(i)},'\n return result[:-1]", "from collections import Counter \n\ndef get_strings(city): \n \n c = Counter(list(filter(str.isalpha, city.lower()))) \n return ','.join(f'{char}:{\"*\"*freq}' for char, freq in list(c.items()))\n\n\n", "from collections import Counter \n\ndef get_strings(city):\n count = Counter(city.lower().replace(\" \", \"\"))\n return \",\".join([f\"{k}:{'*'*v}\" for k,v in count.items()])", "import json\ndef get_strings(city):\n cityAmount = {}\n for x in range(len(city)):\n if city[x] == ' ':\n continue\n if city[x].lower() in cityAmount:\n cityAmount[city[x].lower()] += '*'\n else:\n cityAmount[city[x].lower()] = '*'\n return \",\".join((\"{}:{}\".format(*i) for i in list(cityAmount.items())))\n", "def get_strings(city):\n city = \"\".join(city.lower().split())\n res = []\n letters = [] \n for letter in city:\n if letter not in letters:\n res.append(str(letter +\":\"+\"*\" *city.count(letter)))\n letters.append(letter)\n return \",\".join(res)", "def get_strings(city):\n c={}\n for i in city.lower():\n if(i == \" \"):\n continue\n try:\n c[i]+=1\n except:\n c[i]=1\n res=\"\"\n for i,j in c.items():\n res+=i+\":\"+\"*\"*j+\",\" \n return res[:len(res)-1]"] | {"fn_name": "get_strings", "inputs": [["Chicago"], ["Bangkok"], ["Las Vegas"], ["Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"]], "outputs": [["c:**,h:*,i:*,a:*,g:*,o:*"], ["b:*,a:*,n:*,g:*,k:**,o:*"], ["l:*,a:**,s:**,v:*,e:*,g:*"], ["l:***********,a:***,n:****,f:*,i:***,r:****,p:*,w:****,g:*******,y:*****,o:******,e:*,c:**,h:**,d:*,b:*,t:*,s:*"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 31,626 |
def get_strings(city):
|
074aeed5bb8c378e9728abdd7edcd566 | UNKNOWN | # It's too hot, and they can't even…
One hot summer day Pete and his friend Billy decided to buy watermelons. They chose the biggest crate. They rushed home, dying of thirst, and decided to divide their loot, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the number of watermelons in such a way that each of the two parts consists of an even number of watermelons. However, it is not obligatory that the parts are equal.
Example: the boys can divide a stack of 8 watermelons into 2+6 melons, or 4+4 melons.
The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, whether they can divide the fruits in the way they want. For sure, each of them should get a part of positive weight.
# Task
Given an integral number of watermelons `w` (`1 ≤ w ≤ 100`; `1 ≤ w` in Haskell), check whether Pete and Billy can divide the melons so that each of them gets an even amount.
## Examples | ["def divide(weight):\n return weight > 2 and weight % 2 == 0", "def divide(weight):\n return weight % 2 == 0 and weight > 2", "divide=lambda weight: weight%2==0 and weight>2", "def divide(weight):\n if weight % 2 == 0 and weight > 2: \n return True\n else:\n return False", "def divide(w): return not w%2 and not w<=2", "def divide(weight):\n return not (weight % 2 or weight == 2)", "def divide( _ ): return _ > 2 and _ % 2 == 0", "divide = lambda w: w>3 and not w%2", "def divide(weight):\n if weight > 2 and weight % 2 == 0:\n return True\n else:\n return False", "def divide(weight):\n return weight >= 4 and not weight % 2", "def divide(weight):\n # make sure weight is an even number\n # make sure that each part is at least 2\n return weight % 2 == 0 and weight - 2 >= 2", "def divide(weight):\n return weight % 2 == 0 and weight >= 4", "def divide(weight): return not weight % 2 and weight>2", "def divide(w):\n return not w%2 if w > 3 else False", "divide = lambda w: w>2 and w%2==0", "def divide(weight):\n return weight > 2 and not weight % 2", "def divide(weight):\n return weight%2==0 and weight != 2", "def divide(weight):\n if weight == 2:\n return False\n else:\n return weight % 2 == 0", "def divide(weight: int) -> bool:\n \"\"\" Check whether Pete and Billy can divide the melons so that each of them gets an even amount. \"\"\"\n return not weight % 2 if weight != 2 else False", "def divide(weight):\n return False if weight<3 or weight%2==1 else True", "def divide(weight):\n print(weight)\n ans = weight % 2\n print(ans)\n if(weight == 2):\n return(False)\n if(ans == 0):\n return(True)\n else:\n return(False)", "divide=lambda w: not w%2 and w>2", "def divide(weight):\n if(weight % 2 == 0):\n if(weight / 2 == 1):\n return False\n \n return True\n else:\n return False", "def divide(weight):\n x = weight / 2\n y = weight // 2\n if weight == 2:\n answer = False\n elif x == y:\n answer = True\n elif x != y:\n answer = False\n return(answer)\n", "def divide(weight):\n if weight % 2 == 0:\n for i in range(1, weight):\n remainder = weight - i\n if remainder % 2 == 0 and i % 2 == 0:\n return True\n return False\n else: return False ", "def divide(w):\n return not w/2%2 or not w%10", "def divide(weight):\n \n check_even = weight - 2\n \n if check_even <= 0:\n return False\n \n if check_even % 2 == 0:\n return True\n else:\n return False", "def divide(weight):\n# return True if weight%2==0 else False if weight==2\n if weight==2:\n return False\n elif weight%2==0:\n return True\n else:\n return False\n\n", "def divide(weight):\n if weight %2 == 0 and weight>2 :\n return True\n if (weight %2 != 0) or (weight/2 %2 !=0):\n return False \n\n", "def divide(weight):\n if (weight % 2 == 0) and (weight > 2):\n if (weight - 2) % 2 == 0:\n return True\n else:\n return False\n return False\n", "def divide(weight):\n assert 1 <= weight <= 100\n if weight == 2:\n return False\n if weight % 2 == 0:\n return True\n else:\n return False", "def divide(a):\n if a% 2==0 and a!=2:\n return True\n else:\n return False \n", "def divide(weight):\n return True if weight % (weight // 2) == 0 and weight > 2 else False", "def divide(weight):\n for i in range(1,weight):\n if(weight%i==0):\n if(i%2==0):\n return True\n return False ", "def divide(weight):\n if weight == 2:\n return False \n elif weight%2==0:\n return True \n else:\n weight%2!=0\n return False", "def divide(weight):\n# return True if weight%2 ==0 else False\n if weight==2:\n return False\n elif weight%2 ==0:\n return True\n else:\n return False\n", "divide=lambda a:a%2==0 and a!=2", "def divide(weight):\n if weight <= 0:\n return False\n return weight%2 == 0 and weight > 2", "def divide(weight):\n return weight % 2 == 0 and weight > 2\n#pogchamp\n", "def divide(weight):\n half_weight = weight / 2\n if half_weight % 2 == 0:\n return True\n elif ((half_weight - 1) % 2 == 0) and ((half_weight - 1) != 0):\n return True\n elif half_weight - 1 == 0:\n return False\n else:\n return False", "def divide(weight):\n return weight >= 4 and weight%2==0 and (weight-2)%2==0", "def divide(w):\n for i in range(2, w, 2):\n if (w-i) % 2 == 0: return True\n return False", "def divide(weight):\n return True if weight > 3 and not weight % 2 else 0", "def divide(weight):\n\n if (weight < 4 or\n (weight - 2) % 2 != 0):\n\n return False\n\n return True\n", "is_even = lambda x : x % 2 == 0\n\ndef divide(weight):\n if is_even(weight):\n if is_even(weight/2):\n return True\n else:\n if is_even(weight/2+1) and is_even(weight/2-1) and weight > 2:\n return True\n return False\n else:\n return False\n", "divide = lambda n : n % 2 == 0 if n != 2 else False", "def divide(w):\n if w ==2:\n return False\n if (w-2)%2==0:\n return True\n else:\n return False\n", "def divide(weight):\n nums = range(2, weight, 2)\n for a in nums:\n for b in nums:\n if weight == a + b:\n return True\n return False", "def divide(weight):\n if weight%2 == 0 and weight/2>=2:\n return True\n else:\n return False", "def divide(weight):\n return weight//2==weight-(weight//2)and weight//2!=1", "def divide(weight):\n if weight/2 >1:\n return weight%2==0\n else:\n return False\n", "def divide(weight):\n if(weight < 3 or weight > 100):\n return False\n return False if weight % 2 else True", "def divide(weight):\n return (weight % 2 == 0) and (weight // 2 - 2) >= 0", "def divide(weight):\n a = weight / 2\n if a % 2 == 0:\n return True\n elif a % 5 == 0:\n return True\n else:\n return False", "def divide(weight):\n for x in range(1, weight):\n if x%2 == 0 and (weight-x)%2 == 0:\n return True\n else:\n return False", "def divide(weight):\n \"\"\"(^-__-^)\"\"\"\n return (True if weight>2 and weight%2 == 0 else False)\n", "def divide(weight):\n return weight%2==0 if weight in range(4, 101) else False", "def divide(weight):\n length = weight - 1\n for n in range(1, weight):\n if n % 2 == 0 and length % 2 == 0 and n + length == weight:\n return True\n length -= 1\n return False", "def divide(weight):\n return (weight - 2) % 2 == 0 and (weight - 2) > 1", "def divide(weight):\n if weight == 2: \n return False\n elif weight % 2 == 0 and weight != 2: \n return True\n return False", "def divide(weight):\n print(weight)\n return True if weight != 2 and (weight - 4) % 2 == 0 else False", "def divide(weight):\n possible = [x for x in range(2,weight,2) if ((weight-x) %2) == 0]\n return len(possible) > 0", "def divide(weight):\n if weight >=4 and weight % 2 == 0:\n return True\n elif weight == 2:\n return False\n else:\n return False\n", "def divide(weight):\n if weight%2 == 0 or weight/10==int :\n a = weight/2 \n b = weight/2\n if a-1 == 0:\n return False\n elif a%2 == 0 and b%2 == 0:\n return True\n elif (a-1)%2 == 0 and (b+1)%2 == 0:\n return True\n else:\n return False", "def divide(w):\n if w > 2:\n w2 = w % 2\n return w2 % 2 == 0 \n else: \n return False\n", "def divide(w):\n if (w%2!=0 or w==2):\n return False\n else:\n return True", "def divide(weight):\n if (weight%2==0 and weight!=2):\n return True \n if (weight%2!=0 or weight==2):\n return False", "def divide(weight):\n weight = weight / 2\n if weight % 2 == 0:\n return True\n elif (weight + 1) % 2 ==0 and weight > 1:\n return True\n else: \n return False\n", "def divide(weight: int) -> bool:\n \"\"\"Helps to divide a watermelon into two parts even if they have different weight.\"\"\"\n if weight / 2 >= 2:\n return weight % 2 == 0\n return False", "def divide(weight):\n return len([i for i in range(1, weight + 1) if i % 2 == 0]) >= 2 and weight % 2 == 0", "def divide(weight):\n a = weight / 2\n if a == int(a) and a >= 2:\n return True\n else:\n return False", "def divide(weight):\n if weight % 4 == 0 and weight % 2 == 0 or weight == 10 or weight == 90:\n return True\n return False", "def divide(weight: int) -> bool:\n return weight % 2 == 0 if weight != 2 else False", "def divide(weight):\n if weight>2:\n return weight % 2==0\n elif weight==2:\n return False\n else:\n return False\n", "def divide(weight):\n if weight > 3:\n if (weight - 2) % 2 == 0:\n return True\n else:\n return False\n else:\n return False", "def divide(weight):\n i = 1\n while i != weight:\n if (i % 2 == 0 and (weight - i) % 2 == 0):\n return True\n break\n else:\n i += 1\n else:\n return False", "def divide(weight):\n a = weight - 2\n b = weight % 2\n return True if a > 1 and b == 0 else False", "def divide(weight):\n \n weightx = weight - 2\n \n if weightx <= 0:\n return False\n \n if weightx / 2 == weightx // 2:\n return True\n \n else:\n return False", "def divide(weight):\n return not(weight < 4 or weight % 2)", "def divide(weight):\n return (weight - 2) % 2 == 0 if weight - 2 > 0 else False", "def divide(weight):\n w = weight - 2 \n if w!=0:\n if w%2==0:\n return True\n else:\n return False\n else:\n return False", "def divide(w):\n return True if w != 2 and w % 2 == 0 else False ", "def divide(weight):\n flag = False\n for i in range(3,weight + 1):\n if i %2 == 0 and (weight - i) %2 == 0:\n flag = True\n break\n return flag\n", "def divide(weight):\n res = []\n for i in range(2, weight+1):\n if i % 2 == 0:\n res.append(i)\n if res[-1] == weight:\n res.pop(-1)\n n = 0\n while n < len(res):\n if res == []:\n return False\n elif res[0+n] + res[-1-n] == weight:\n return True\n else:\n n += 1\n return False", "def divide(x):\n if x % 2 == 0 and x/2%2 == 0:\n return True\n \n if x % 2 == 0 and x/2%2 != 0:\n \n if (x/2-1)%2 == 0 and (x/2+1)%2 == 0 and (x/2-1) != 0:\n return True\n else:\n return False\n \n return False", "def divide(weight):\n if weight % 2 == 0 and weight != 2:\n result = True\n else:\n result = False\n return result", "def divide(weight):\n if weight < 3:\n return False\n else:\n return weight%2 == 0", "def divide(weight):\n return weight-2>1 and weight%2==0", "def divide(m):\n if m == 2:\n return False\n return (m-2)%2 == 0 and (m-(m-2))%2 == 0", "def divide(weight):\n return False if (weight-2)%2==1 or (weight-2)==0 else True", "def divide(weight):\n while 1 <= weight <=100:\n if weight == 2:\n return False\n if weight % 2 == 0:\n return True\n else:\n return False", "def divide(weight):\n quotient = (weight / 2)\n remainder = (weight % 2)\n if remainder == 0 and quotient != 1:\n return True\n else:\n return False\n \n \n \n \n", "def divide(weight):\n return (~weight)&1 and weight > 2", "def divide(weight):\n c = False\n for a in range(weight):\n for b in range(a+1):\n if a + b == weight and a % 2 == 0 and b % 2 == 0:\n print(a, b)\n c = True\n return c", "def divide(weight):\n return False if not (weight / (weight // 2)) == 2 or weight == 2 else True", "def divide(weight):\n for i in range(2, weight+1,2):\n for j in range(2, weight+1,2):\n if i+j==weight:\n return True\n print(weight)\n return False", "def divide(weight):\n a=1\n if weight%2==0 and weight>2:\n while a< weight :\n b= weight-a\n if a%2==0 and b%2==0 :\n return True\n a+=1\n else :\n return False\n \n", "def divide(weight):\n if weight % 2 is 0 and weight > 2: return True\n else: return False", "def divide(w):\n if w <= 2:\n return False\n elif (w % 2) == 0:\n return True\n else:\n return False", "def divide(weight):\n return weight // 2 > 1 and weight % 2 == 0"] | {"fn_name": "divide", "inputs": [[4], [2], [5], [88], [100], [67], [90], [10], [99], [32]], "outputs": [[true], [false], [false], [true], [true], [false], [true], [true], [false], [true]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 13,272 |
def divide(weight):
|
64e6cf80b2961b5315bea7d00d3f802b | UNKNOWN | The marketing team is spending way too much time typing in hashtags.
Let's help them with our own Hashtag Generator!
Here's the deal:
- It must start with a hashtag (`#`).
- All words must have their first letter capitalized.
- If the final result is longer than 140 chars it must return `false`.
- If the input or the result is an empty string it must return `false`.
## Examples
```
" Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata"
" Hello World " => "#HelloWorld"
"" => false
``` | ["def generate_hashtag(s):\n output = \"#\"\n \n for word in s.split():\n output += word.capitalize()\n \n return False if (len(s) == 0 or len(output) > 140) else output\n", "def generate_hashtag(s):\n ans = '#'+ str(s.title().replace(' ',''))\n return s and not len(ans)>140 and ans or False", "def generate_hashtag(s): return '#' +s.strip().title().replace(' ','') if 0<len(s)<=140 else False\n", "def generate_hashtag(s):\n if not s or len(s)>140:\n return False\n return \"#\"+''.join(x.capitalize() for x in s.split(' '))", "def generate_hashtag(s):\n s = s.split()\n if len(s) > 140 or not (s):\n return False\n ans = '#'\n for word in s:\n ans += word.title()\n if len(ans) > 140 or not (s):\n return False\n return ans", "generate_hashtag=lambda d:(lambda b:d>''<b==b[:139]and'#'+b)(d.title().replace(' ',''))", "generate_hashtag = lambda _: (lambda __: _ > '' < _ == _[:0b10001100] and chr(35) + __)(_.title().replace(chr(32),''))\n", "def generate_hashtag(s):\n return '#' + ''.join([word.title() for word in s.split(' ')]) if s and len(s) <= 140 else False", "def generate_hashtag(s):\n if len(s) > 140 or not s: return False \n return '#' + ''.join(w.capitalize() for w in s.split())", "def generate_hashtag(s):\n return 0 if not s or len(s)>140 else f'#{\"\".join(e for e in s.title().split())}'", "def generate_hashtag(s):\n if not s: return False\n elif len(s) > 140: return False\n else: return '#' + ''.join(s.title().split())\n", "def generate_hashtag(s):\n if 140>len(s)>0:\n L=s.split(\" \")\n L1=[]\n for i in L:\n L1.append(i.capitalize())\n return \"#\"+str(\"\".join(L1))\n else:\n return False", "def generate_hashtag(s):\n #your code here\n \n \n return \"#{}\".format(s.title().replace(\" \", \"\")) if len(s) in range(1,141) else False", "def generate_hashtag(s):\n s='#'+s.title().replace(' ','')\n return s if s!='#' and len(s)<=140 else False", "def generate_hashtag(s):\n return \"#{}\".format(\"\".join(s.title().strip().split())) if len(\"#{}\".format(\"\".join(s.title().strip().split())))<=140 and s.strip() != \"\" else False", "def generate_hashtag(s):\n if len(s) > 140: return False\n if len(s) == 0: return False\n return f\"#{''.join([x.capitalize() for x in s.split()])}\"\n", "def generate_hashtag(s):\n if s == '' or len(s)>140 : return False\n return '#'+\"\".join([i.capitalize() for i in s.split(' ')])", "def generate_hashtag(s):\n return '#'+ s.lower().title().replace(' ', '') if 141 > len(s) > 0 else False", "def generate_hashtag(s):\n answer = \"#\" + \"\".join([i.capitalize() for i in s.split()])\n return False if not s or len(answer)>140 else answer\n # inside-out flow:\n # split -> capitalize each word -> join them with '#'\n", "def generate_hashtag(s):\n s = ''.join(i.capitalize() for i in s.split())\n return f\"#{s}\" if len(s) < 140 and s.isalpha() else False", "def generate_hashtag(s):\n return '#'+s.title().replace(' ','')if not s.isspace() and 0<len(s)<=140 else False", "def generate_hashtag(s):\n hashtag = \"#\"+\"\".join(i.title() for i in s.split())\n return hashtag if s and len(hashtag) <= 140 else False", "import string\ndef generate_hashtag(s): return '#'+''.join(string.capwords(s).split(' ')) if len(s)<=140 and len(s)!=0 else False", "def generate_hashtag(s):\n return False if len(s) == 0 or len(s) > 140 else \"#{}\".format(\"\".join(s.title().split()))", "def generate_hashtag(s):\n # time complexity O(N)\n # space complexity O(N)\n hashtag = \"#\" + \"\".join(word.capitalize() for word in s.split())\n return hashtag if 1 < len(hashtag) <= 140 else False", "def generate_hashtag(s):\n return f\"#{s.title().replace(' ', '')}\" if 0 < len(s) <= 140 else False", "def generate_hashtag(s):\n if not s:\n return False\n\n if len(s) > 140:\n return False\n\n result = \"#\"\n for word in s.split():\n result += word[0].upper() + word[1:].lower()\n\n return result", "def generate_hashtag(s):\n return False if len(s) > 140 or not s.split() else \"#\" + \"\".join(map(lambda x: x.capitalize(), s.split()))", "def generate_hashtag(s):\n output = \"#\" + s.title().replace(\" \", \"\")\n return output if len(output) <= 140 and output != \"#\" else False", "def generate_hashtag(s):\n solution = '#' + ''.join([word.strip().capitalize() for word in s.split(' ')])\n \n if len(solution) > 1 and len(solution) < 140:\n return solution\n return False", "def generate_hashtag(s):\n if 1<len(s)<140:\n s = s.split()\n return '#' + ''.join(s.capitalize() for s in s)\n else: return False", "def generate_hashtag(s):\n if len(s)==0 or len(s)>140:\n return False\n s = s.split()\n a = [i.title() for i in s]\n return '#' + ''.join(a)", "def generate_hashtag(s):\n s = \"#\" + \"\".join(s.title().split())\n return [s if 1 < len(s) < 140 else False][0]", "def generate_hashtag(s):\n smod = ''.join([word.capitalize() for word in s.split()])\n return '#' + smod if s != '' and len(smod) <= 140 else False", "def generate_hashtag(s):\n if not len(s): return False\n s = \"#\" + s.title().replace(\" \",\"\")\n return s if len(s) <= 140 else False ", "import re\ndef generate_hashtag(s):\n return '#' + (''.join(re.findall('[A-Za-z]', s.title()))) if 0 < len(s) < 140 else False", "def generate_hashtag(s: str):\n #your code here\n number_of_chars = len(s)\n if s and number_of_chars < 140:\n words_list = [word.capitalize() for word in s.split()]\n words = ['#']+words_list\n result = ''.join(words)\n return result \n else:\n return False", "def generate_hashtag(s):\n s = str(s).title()\n if s == '':\n return False\n if len(s) > 144:\n return False\n return '#' + s.replace(' ', '')", "def generate_hashtag(s):\n return (\"#\"+s.title().replace(\" \",\"\") if len(\"#\"+s.title().replace(\" \",\"\")) <= 140 else False) if len(s) != 0 else False\n #your code here\n", "def generate_hashtag(s):\n if not s:\n return False\n s = s.title().replace(' ', '')\n \n if not s or len(s) > 139:\n return False\n \n return '#' + s", "import string\ndef generate_hashtag(s):\n if len(s)==0 or len(s)>140:\n return False\n else:\n y=''.join((string.capwords(s)).split(' ',(string.capwords(s)).count(' ')))\n m='#'+y\n return m", "def generate_hashtag(s):\n nword=\"#\"\n if s==\"\":\n return False\n elif len(s)>140:\n return False\n else:\n for word in s.split():\n nword+=word.capitalize() \n return nword \n", "def generate_hashtag(s):\n #your code here\n if len(s)==0 or len(s)>=140:\n return False\n a=s.split()\n st=''\n for i in range(len(a)):\n st+=str(a[i].capitalize())\n return '#'+st\n \n \n", "def generate_hashtag(s):\n return False if (s=='' or len(s)>140) else '#'+''.join(s.title().split())", "def generate_hashtag(s):\n if s == '' or len(s)>140:\n return False\n return '#' + s.title().strip().replace(' ','')", "def generate_hashtag(str):\n return '#' + ''.join(word.capitalize() for word in str.split(' ')) if str and len(str) < 140 else False", "def generate_hashtag(s):\n return '#' + s.title().replace(' ', '') if (s and len(s) < 140) else False", "def generate_hashtag(s):\n if not s or False or len(s) > 150:\n return False\n else:\n return '#' + ''.join([i.title() for i in s.strip().split()])\n", "def generate_hashtag(s):\n s_arr = s.title().split(' ')\n hashtag = '#' + ''.join(s_arr)\n if len(hashtag) > 140 or len(hashtag) < 2:\n return False\n else:\n return hashtag", "def generate_hashtag(s):\n if len(s) > 140 or len(s) == 0:\n return False\n \n s = s.title().replace(\" \", \"\")\n \n return '#' + s", "def generate_hashtag(s):\n #your code here\n if len(s)!=0 and len(s)<140:\n return '#' + ''.join(word.title() for word in s.split())\n else:\n return False"] | {"fn_name": "generate_hashtag", "inputs": [[""], ["Codewars"], ["Codewars "], ["Codewars Is Nice"], ["codewars is nice"], ["CodeWars is nice"], ["c i n"], ["codewars is nice"], ["Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong Cat"]], "outputs": [[false], ["#Codewars"], ["#Codewars"], ["#CodewarsIsNice"], ["#CodewarsIsNice"], ["#CodewarsIsNice"], ["#CIN"], ["#CodewarsIsNice"], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 8,280 |
def generate_hashtag(s):
|
dffb155df9a6ad4509dbfeb6e8ea01c4 | UNKNOWN | Beaches are filled with sand, water, fish, and sun. Given a string, calculate how many times the words `"Sand"`, `"Water"`, `"Fish"`, and `"Sun"` appear without overlapping (regardless of the case).
## Examples
```python
sum_of_a_beach("WAtErSlIde") ==> 1
sum_of_a_beach("GolDeNSanDyWateRyBeaChSuNN") ==> 3
sum_of_a_beach("gOfIshsunesunFiSh") ==> 4
sum_of_a_beach("cItYTowNcARShoW") ==> 0
``` | ["import re\ndef sum_of_a_beach(beach):\n return len(re.findall('Sand|Water|Fish|Sun', beach, re.IGNORECASE))", "def sum_of_a_beach(beach):\n return sum(beach.lower().count(fun) for fun in [\"sand\", \"water\", \"fish\", \"sun\"])", "import re\ndef sum_of_a_beach(beach):\n return len(re.findall(\"sand|water|fish|sun\", beach, flags=re.I))", "import re\n\ndef sum_of_a_beach(beach):\n return sum(1 for _ in re.finditer(r'sand|water|fish|sun',beach.lower()))", "def sum_of_a_beach(beach):\n b = beach.lower(); l = [\"sand\", \"water\", \"fish\", \"sun\"]; c = 0\n for w in l:\n if w in b:c += b.count(w)\n return c\n", "sum_of_a_beach=lambda s:sum(s.lower().count(e)for e in['sand','water','fish','sun'])", "def sum_of_a_beach(beach):\n # your code\n words=[\"Sand\", \"Water\", \"Fish\",\"Sun\"] \n count=0\n for word in words:\n length = len(word) \n for i in range(len(beach)):\n if beach[i:length+i].lower() ==word.lower():\n count+=1\n return count", "sum_of_a_beach=lambda beach:beach.lower().count('water')+beach.lower().count('sand')+beach.lower().count('fish')+beach.lower().count('sun')", "def sum_of_a_beach(beach):\n return sum([beach.lower().count(element) for element in ['sand', 'water', 'fish', 'sun']])", "import re\n\ndef sum_of_a_beach(beach):\n return len(re.findall(r\"Sand|Water|Fish|Sun\", beach, re.IGNORECASE))"] | {"fn_name": "sum_of_a_beach", "inputs": [["SanD"], ["sunshine"], ["sunsunsunsun"], ["123FISH321"], ["weoqipurpoqwuirpousandiupqwoieurioweuwateruierqpoiweurpouifiShqowieuqpwoeuisUn"], ["sAnDsandwaTerwatErfishFishsunsunsandwater"], ["joifjepiojfoiejfoajoijawoeifjowejfjoiwaefjiaowefjaofjwoj fawojef "], ["jwefjwjfsandsandwaterwaterfishfishsunsunsandwateriojwhefa;jawof;jawio;f"], ["saNdsandwaterwAterfishfishsunsunsandwatersandsandwaterwaterfishfishsunsunsandwatersandsandwaterwaterfishfishsunsunsandwatersandsandwaterwaterfishfishsunsunsandwatersandsandwaterwaterfishfishsunsunsandwatersandsandwaterwaterfishfishsunsunsandwatersandsandwaterwaterfishfishsunsunsandwatersandsandwaterwaterfishfishsunsunsandwatersandsandwaterwaterfishfishsunsunsandwatersandsandwaterwaterfishfishsunsunsandwater"], ["sununsu"], ["sandandndsansa"], ["wateratertererwatewatwa"], ["fishishshfisfi"]], "outputs": [[1], [1], [4], [1], [4], [10], [0], [10], [100], [1], [1], [1], [1]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,460 |
def sum_of_a_beach(beach):
|
f0ce88231e692ef3eb5c4fc353f185c2 | UNKNOWN | Create a function which accepts one arbitrary string as an argument, and return a string of length 26.
The objective is to set each of the 26 characters of the output string to either `'1'` or `'0'` based on the fact whether the Nth letter of the alphabet is present in the input (independent of its case).
So if an `'a'` or an `'A'` appears anywhere in the input string (any number of times), set the first character of the output string to `'1'`, otherwise to `'0'`. if `'b'` or `'B'` appears in the string, set the second character to `'1'`, and so on for the rest of the alphabet.
For instance:
```
"a **& cZ" => "10100000000000000000000001"
``` | ["def change(st):\n new = \"\"\n st = st.lower()\n for letter in \"abcdefghijklmnopqrstuvwxyz\":\n if letter in st:\n new += \"1\"\n else:\n new += \"0\"\n return new\n", "def change(s):\n s = set(s.lower())\n return \"\".join(\"1\" if x in s else \"0\" for x in map(chr, range(97, 123)))", "ABC = \"abcdefghijklmnopqrstuvwxyz\"\n\ndef change(s):\n s = set(s.lower())\n return \"\".join(str(int(char in s)) for char in ABC)", "def change(st):\n return \"\".join([\"1\" if chr(i + 97) in st.lower() else \"0\" for i in range(26)])\n \n \n \n", "def change(st):\n return ''.join(['1' if i in st.lower() else '0' for i in 'abcdefghijklmnopqrstuvwxyz'])\n", "from string import ascii_lowercase\n\n\ndef change(st):\n source = st.lower()\n return ''.join('1' if q in source else '0' for q in ascii_lowercase)", "def change(st):\n s = set(filter(str.isalpha, st.lower()))\n return ''.join('01'[chr(97+i) in s] for i in range(26))", "def change(st):\n ze = '00000000000000000000000000'\n ze_li = list(ze)\n if 'a' in st.lower(): \n ze_li[0] = '1'\n if 'b' in st.lower(): \n ze_li[1] = '1'\n if 'c' in st.lower(): \n ze_li[2] = '1'\n if 'd' in st.lower(): \n ze_li[3] = '1'\n if 'e' in st.lower(): \n ze_li[4] = '1'\n if 'f' in st.lower(): \n ze_li[5] = '1'\n if 'g' in st.lower(): \n ze_li[6] = '1'\n if 'h' in st.lower(): \n ze_li[7] = '1'\n if 'i' in st.lower(): \n ze_li[8] = '1'\n if 'j' in st.lower(): \n ze_li[9] = '1'\n if 'k' in st.lower(): \n ze_li[10] = '1'\n if 'l' in st.lower(): \n ze_li[11] = '1'\n if 'm' in st.lower(): \n ze_li[12] = '1'\n if 'n' in st.lower(): \n ze_li[13] = '1'\n if 'o' in st.lower(): \n ze_li[14] = '1'\n if 'p' in st.lower(): \n ze_li[15] = '1'\n if 'q' in st.lower(): \n ze_li[16] = '1'\n if 'r' in st.lower(): \n ze_li[17] = '1'\n if 's' in st.lower(): \n ze_li[18] = '1'\n if 't' in st.lower(): \n ze_li[19] = '1'\n if 'u' in st.lower(): \n ze_li[20] = '1'\n if 'v' in st.lower(): \n ze_li[21] = '1'\n if 'w' in st.lower(): \n ze_li[22] = '1'\n if 'x' in st.lower(): \n ze_li[23] = '1'\n if 'y' in st.lower(): \n ze_li[24] = '1'\n if 'z' in st.lower(): \n ze_li[25] = '1'\n return ''.join(ze_li)", "def change(st):\n return ''.join('1' if y in st.lower() else '0' for y in 'abcdefghijklmnopqrstuvwxyz')", "def change(stg):\n chars = set(stg.lower())\n return \"\".join(str(int(c in chars)) for c in \"abcdefghijklmnopqrstuvwxyz\")"] | {"fn_name": "change", "inputs": [["a **& bZ"], ["Abc e $$ z"], ["!!a$%&RgTT"], [""], ["abcdefghijklmnopqrstuvwxyz"], ["aaaaaaaaaaa"], ["&%&%/$%$%$%$%GYtf67fg34678hgfdyd"]], "outputs": [["11000000000000000000000001"], ["11101000000000000000000001"], ["10000010000000000101000000"], ["00000000000000000000000000"], ["11111111111111111111111111"], ["10000000000000000000000000"], ["00010111000000000001000010"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,739 |
def change(st):
|
966bdb95f9c19c0cfdf2e195409bc27f | UNKNOWN | ## Number pyramid
Number pyramid is a recursive structure where each next row is constructed by adding adjacent values of the current row. For example:
```
Row 1 [1 2 3 4]
Row 2 [3 5 7]
Row 3 [8 12]
Row 4 [20]
```
___
## Task
Given the first row of the number pyramid, find the value stored in its last row.
___
## Examples
```python
reduce_pyramid([1]) == 1
reduce_pyramid([3, 5]) == 8
reduce_pyramid([3, 9, 4]) == 25
```
___
## Performance tests
```python
Number of tests: 10
List size: 10,000
``` | ["from operator import mul\n\ndef reduce_pyramid(base):\n return sum(map(mul, base, comb_n(len(base) - 1)))\n\ndef comb_n(n):\n c = 1\n for k in range(0, n + 1):\n yield c\n c = c * (n - k) // (k + 1)\n", "def reduce_pyramid(base):\n c, t, ll = 1, 0, len(base) -1\n for i, v in enumerate(base):\n t += c * v\n c = c * (ll - i)//(i + 1)\n return t", "def reduce_pyramid(base):\n s, c = 0, 1\n for i, x in enumerate(base, 1):\n s += c * x\n c = c * (len(base) - i) // i\n return s", "def reduce_pyramid(base):\n tot,c,n = 0,1,len(base)-1\n for i in range(n+1>>1):\n tot += c * (base[i] + base[n-i])\n c = c * (n-i)//(i+1)\n if not n&1: tot += c*base[n>>1]\n return tot", "def _coefs(l):\n n = 1\n for i in range(l):\n yield n\n n = n * (l-i-1) // (i+1)\n yield n\n\ndef reduce_pyramid(base):\n coefs = _coefs(len(base))\n return sum(next(coefs)*n for n in base)", "def reduce_pyramid(Q) :\n R,U = 0,1\n for F,V in enumerate(Q) : R,U = R + V * U,U * (len(Q) + ~F) // -~F\n return R", "def reduce_pyramid(base):\n n, c, r = len(base) - 1, 1, 0\n for i, x in enumerate(base):\n r += c * x\n c = c * (n - i) // (i + 1)\n return r", "def pascal(n):\n line = [1]\n for k in range(n):\n line.append(line[k]*(n-k)//(k+1))\n return line\n\ndef reduce_pyramid(a):\n x = len(a)-1\n C = pascal(x)\n s = 0\n for i,v in enumerate(a):\n s += C[i]*v\n return s", "def reduce_pyramid(base):\n sm = 0\n nb = 1\n for i, u in enumerate(base, 1):\n sm += nb * u\n nb = nb * (len(base) - i) // i\n return sm", "def reduce_pyramid(b):\n p, r = 1, b[0]\n for i in range(1, len(b)):\n p = p * (len(b) - i) // i\n r += b[i] * p\n return r"] | {"fn_name": "reduce_pyramid", "inputs": [[[1]], [[3, 5]], [[3, 9, 4]], [[5, 6, 7, 8]], [[13, 1, 21, 9]], [[13, 76, 21, 42, 63]]], "outputs": [[1], [8], [25], [52], [88], [674]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,853 |
def reduce_pyramid(base):
|
f0593077e71d92a72011b99aed979629 | UNKNOWN | My friend John likes to go to the cinema. He can choose between system A and system B.
```
System A : he buys a ticket (15 dollars) every time
System B : he buys a card (500 dollars) and a first ticket for 0.90 times the ticket price,
then for each additional ticket he pays 0.90 times the price paid for the previous ticket.
```
#Example:
If John goes to the cinema 3 times:
```
System A : 15 * 3 = 45
System B : 500 + 15 * 0.90 + (15 * 0.90) * 0.90 + (15 * 0.90 * 0.90) * 0.90 ( = 536.5849999999999, no rounding for each ticket)
```
John wants to know how many times he must go to the cinema so that the *final result* of System B, when rounded *up* to the next dollar, will be cheaper than System A.
The function `movie` has 3 parameters: `card` (price of the card), `ticket` (normal price of
a ticket), `perc` (fraction of what he paid for the previous ticket) and returns the first `n` such that
```
ceil(price of System B) < price of System A.
```
More examples:
```
movie(500, 15, 0.9) should return 43
(with card the total price is 634, with tickets 645)
movie(100, 10, 0.95) should return 24
(with card the total price is 235, with tickets 240)
``` | ["import math \n\ndef movie(card, ticket, perc):\n num = 0\n priceA = 0\n priceB = card\n \n while math.ceil(priceB) >= priceA:\n num += 1\n priceA += ticket\n priceB += ticket * (perc ** num)\n \n return num", "from itertools import takewhile, count, accumulate\ndef movie(card, ticket, perc):\n sys_b = accumulate(ticket*perc**n for n in count(1))\n sys_a = accumulate(ticket for m in count(1))\n return sum(1 for a in takewhile(lambda x: round(x[0] + card + 0.49) >= x[1], zip(sys_b, sys_a))) + 1", "from itertools import count\nfrom math import ceil\ndef movie(card, ticket, perc):\n return next(n for n in count(1) if ceil(card + ticket * perc * (1 - perc ** n) / (1 - perc)) < ticket * n)", "from itertools import count\nfrom math import ceil\n\n\ndef movie(card, ticket, perc):\n return next( x for x in count(card//ticket)\n if ticket * x > ceil(card + ticket * perc * (1 - perc**x)/(1 - perc)) )", "import math\ndef movie(card, ticket, perc):\n sysA, sysB, count = ticket, card+ticket*perc, 1\n while sysA <= math.ceil(sysB):\n sysA += ticket\n sysB += ticket*(perc**(count+1))\n count+=1\n return count", "from math import ceil\n\ndef movie(card, ticket, rate):\n count = 0\n totalA = 0.0\n totalB = 0.0\n \n while (ceil(card + totalB) >= totalA):\n totalA += ticket\n totalB = (totalB + ticket) * rate\n count += 1\n\n return count\n", "from math import ceil\ndef movie(card, ticket, perc):\n n = 0;\n while 1:\n n+= 1\n if ticket*n>ceil(card+ticket*perc*(1-perc**n)/(1-perc)):\n return n", "def movie(card, ticket, perc, n = 1):\n while card + ticket*perc*(1-perc**n)/(1-perc) - ticket*n > -1: \n n += 1\n return n", "def movie(card, ticket, perc, cnt = 0):\n while card>-1:\n card += (ticket * perc**cnt)*perc - ticket\n cnt += 1\n return cnt", "from math import *\ndef movie(card, ticket, perc):\n n = 1\n while ceil(card + ticket*perc*(1-perc**n)/(1-perc)) >= ticket*n: n += 1\n return n", "import math\n\ndef movie(card, ticket, perc):\n total = card\n n = 1\n while True:\n total += ticket*(perc**n)\n if math.ceil(total) < ticket*n:\n break\n n += 1\n return n\n", "import math\ndef movie(card, ticket, perc):\n sysa=n=0\n sysb=card\n while math.ceil(sysb) >= (sysa):\n n+=1\n sysa += ticket\n sysb += ticket * math.pow(perc,n)\n else: return n\n", "import math\ndef movie(card, ticket, perc):\n n = 0\n a_price = 0\n b_price = card\n perc_multiplier = perc\n while math.ceil(b_price) >= a_price:\n a_price += ticket\n b_price += ticket * perc_multiplier\n perc_multiplier *= perc\n n += 1\n return n\n \n", "import math\ndef movie(card, ticket, perc):\n pc = card\n pt = 0\n count = 0\n while not math.ceil(pc) < math.ceil(pt):\n count += 1\n pc += ticket * (perc**count)\n pt += ticket\n return count", "from math import ceil\n\ndef movie(card, ticket, perc):\n i = 0; sb = card; sa = 0; prev = ticket\n while True: \n i += 1\n nou = prev * perc\n sb += nou\n prev = nou\n sa += ticket \n if (ceil(sb) < sa): \n return i ", "from scipy.special import lambertw\nfrom math import ceil, log\n\ndef movie(a, b, c):\n log_c = log(c)\n w = lambertw(\n (c ** (a / b + c / (1 - c) + 1 / b + 1) * log_c) /\n (1 - c)).real\n return int(ceil((\n b * w - b * c * w -\n a * log(c) + a * c * log_c - b * c * log_c + c * log_c - log_c\n ) / (b * (c - 1) * log_c)))", "from itertools import count\nfrom scipy.special import lambertw\nfrom math import log\n\ndef movie(a, b, c):\n if a>0:\n w = lambertw(-c**((a/b)+c/(1-c)+1)*log(c)/(c-1))\n x = (b*w-b*c*w-a*log(c)+a*c*log(c)-b*c*log(c))/(b*(c-1)*log(c))\n x = int(x.real+1)\n A = b*x\n B = a+b*sum(c**e for e in range(1,x+1))\n for i in range(x, x+5):\n print(i, A, int(B+1))\n if A>int(B+1):\n return i\n A += x\n B += b*c**i\n return 2", "def movie(card, ticket, perc):\n return next(n for n in range(9**99) if card + ticket*perc*(1-perc**n)/(1-perc) - ticket*n < -1)", "def movie(card, ticket, perc):\n asum = -1\n cnt = 0\n while card>asum:\n asum += ticket\n card += (ticket * perc**cnt)*perc\n cnt += 1\n return cnt", "from math import ceil\n\ndef movie(card, ticket, perc):\n # your code\n discount_ticket = ticket\n system_a_price = 0\n system_b_price = card\n days = 0\n while ceil(system_b_price) >= system_a_price:\n days = days + 1\n discount_ticket = discount_ticket * perc\n system_a_price = days * ticket\n system_b_price = system_b_price + discount_ticket\n return days\n", "def movie(card, ticketA, perc):\n assert perc < 1\n \n ticketB = ticketA\n priceA = times = 0\n priceB = card\n \n while not priceA > -(-priceB // 1):\n ticketB *= perc\n priceA += ticketA\n priceB += ticketB\n times += 1\n \n return times\n", "import math\ndef movie(card, ticket, perc):\n # we want\n # ticket*n > card + ticket*sum(p^i,where i=1 to n)\n # we use the geom series formula to simplify sum()\n n = 0\n while True:\n n += 1\n A = ticket*n\n B = card + ticket*(perc*(1-perc**n)/(1-perc))\n if math.ceil(B) < A:\n break\n \n return n\n", "import math\ndef movie(card, ticket, perc):\n a,b,n = 0,card,0\n while math.ceil(b) >= a:\n n += 1\n a += ticket\n b += ticket * (perc ** n) \n return n", "from itertools import count\nfrom math import ceil\n\ndef movie(card, ticket, perc):\n A = lambda n: ticket * n\n B = lambda n: card + ticket * ((perc * (perc ** n - 1)/(perc - 1)))\n return next(n for n in count(1) if ceil(B(n)) < A(n))", "import math\ndef movie(card, ticket, perc):\n n = 1\n while 1:\n if (ticket * n > card + math.ceil(ticket * (1 - pow(perc, n)) / (1 - perc))):\n return n-1\n n = n+1", "import math\ndef movie(card, ticket, perc):\n x = 1\n systema = 0\n systemb = card\n while systemb >= systema:\n systema = ticket*x\n systemb += ticket*perc**x\n if math.ceil(systemb) < systema:\n break\n else:\n x += 1\n return x", "from math import ceil\ndef movie(card, ticket, perc):\n prevPrice = ticket\n i = 0\n \n while True:\n if ceil(card) < ticket * i: return i\n prevPrice *= perc\n card += prevPrice\n i += 1", "import math\ndef movie(card, ticket, perc):\n n=card//ticket\n system_go=True\n while system_go:\n system_A=ticket*n\n system_B=card+sum([ticket*perc**x for x in range(1,n+1)])\n if system_A<card:\n n+=1\n continue\n if system_A>math.ceil(system_B):\n return n\n break\n else:\n n+=1", "import math\ndef movie(card, ticket, perc):\n tiks = 0\n sysA = 0\n sysB = card\n Bticket = ticket\n\n while math.ceil(sysB) >= sysA:\n sysA+=ticket\n tiks+=1\n Bticket*=perc\n \n sysB+= Bticket\n\n return tiks\n", "def movie(card, ticket, perc):\n import math\n \n count = 1\n \n priceA = card; \n priceB = 0\n \n while True:\n priceB += ticket \n \n priceDecrease = ticket * pow(perc, count)\n priceA += priceDecrease\n \n if priceB > math.ceil(priceA):\n return count\n \n count += 1\n", "import math\n\ndef system_a(ticket,times):\n price_a=ticket*times\n return price_a\n\ndef system_b(card,ticket,perc,times):\n price_b = 0\n it = perc * ticket\n \n for i in range(0,times):\n price_b=price_b + it \n it = it * perc\n price_b=price_b+card\n return price_b\n\ndef movie(card, ticket, perc):\n times=1\n systemb = card + ticket * perc\n while (math.ceil(systemb) >= system_a(ticket, times)):\n systemb = systemb + perc ** (times+1) * ticket\n times=times+1\n return times", "from math import ceil\n\ndef movie(card, ticket, perc):\n n=0\n ap=0\n bp=card\n price=ticket\n while ap<=ceil(bp):\n n+=1\n ap+=ticket\n price=price*perc\n bp+=price\n return n", "from math import ceil\ndef movie(card, ticket, perc):\n a,b,c = 0,card,0\n while ceil(b) >= ceil(a):\n a += ticket\n b += ticket * perc**c\n c += 1\n return c-1", "from math import ceil\ndef movie(card, ticket, perc):\n true = ticket\n sys_b = card\n count = 0\n while True:\n count += 1\n sys_a = count*true\n ticket = perc*ticket\n sys_b += ticket\n if ceil(sys_b)<sys_a:\n return count\n return count\n", "import math\n\ndef movie(card, ticket, perc):\n curr_card_price = card\n curr_ticket_price = 0\n next_card_purchase = ticket * perc\n trips = 0\n \n while math.ceil(curr_card_price) >= curr_ticket_price:\n curr_card_price += next_card_purchase\n curr_ticket_price += ticket\n \n trips += 1\n next_card_purchase *= perc\n\n return trips", "import math\ndef movie(card, ticket, perc):\n Aval, Bval, res = ticket, card + (ticket*perc), 1\n while math.ceil(Bval) >= Aval:\n res += 1\n Aval += ticket\n Bval += ticket*(perc**res)\n return res", "from math import ceil\n\ndef movie(card, ticket, perc):\n N=1\n while ticket*N<=ceil(card+ticket*perc*(1-perc**N)/(1-perc)):N+=1\n return N", "import math\n\ndef movie(card, ticket, perc):\n finnished = False \n n = 0\n previous_total = 0 \n while not finnished:\n n += 1\n a = ticket * n\n \n previous_total += (ticket*(perc**n)) \n b = math.ceil(card + previous_total) \n \n if a > b:\n finnished = True\n \n return n\n \n \n", "from math import ceil\n\ndef movie(card, ticket, perc):\n n = 0\n total = card\n while (ceil(total) >= n*ticket):\n total += ticket*perc**n\n n += 1\n \n return n-1", "from math import ceil\ndef movie(card, ticket, perc):\n counter = 0\n sum = card\n perc_= perc\n while ceil(sum) >= ticket*counter:\n sum += ticket*perc_\n perc_ *= perc\n counter += 1\n return counter ", "def movie(card, ticket, perc):\n print((card, ticket, perc))\n import math\n total_ticket = 0.0\n total_card = card\n count = 0\n movieprice_bycard = ticket\n while total_ticket <= math.ceil(total_card):\n count += 1\n movieprice_bycard *= perc\n total_ticket += ticket\n total_card += movieprice_bycard\n return count\n", "import math\ndef movie(card, ticket, perc):\n sys_a = 0\n sys_b = card\n i = 1\n while sys_a <= math.ceil(sys_b):\n sys_a+=ticket\n sys_b+=ticket*(perc**i)\n i+=1\n return i-1", "def movie(card, ticket, perc):\n temp = ticket\n rA = 0\n rB = card\n \n while rB > rA-1:\n temp=temp*perc\n rB+=temp\n rA+=ticket\n \n print((str(rB), \":\", str(rA)))\n return int(rA/ticket)\n", "from math import ceil\ndef movie(card, ticket, perc):\n cs, ts, i = card+ticket*perc, ticket, 2\n while ceil(ts)<=ceil(cs):\n cs, ts, i = cs + ticket*perc**i, ts + ticket, i + 1\n return i-1\n", "import math\ndef movie(crd,tkt,pcnt):\n\n tktCnt = TotalA = TotalB = 0\n \n while(math.ceil(TotalB) >= TotalA):\n tktCnt+=1\n TotalA = tkt * tktCnt\n TotalB = crd + tkt*((pcnt*((pcnt**tktCnt) - 1))/(pcnt - 1))\n\n return(tktCnt)", "from math import ceil\ndef movie(card, ticket, perc):\n priceA=ticket\n priceB=card+ticket*perc\n n=1\n while ceil(priceB) >= priceA:\n n+=1\n priceA+=ticket\n priceB+=ticket*perc**n\n return n ", "from math import *\ndef movie(card, ticket, perc):\n n = 0\n seance = 0\n a = card\n ticket_abonnement = 0\n while ceil(a + ticket_abonnement) >= (ticket * seance) :\n ticket_abonnement += (ticket * perc) * perc**n\n n += 1\n seance += 1\n return seance", "from math import ceil\ndef movie(card, ticket, perc):\n priceOfSystemA, priceOfSystemB, n, ticketPriceB = 0, card, 0, ticket\n while ceil(priceOfSystemB) >= priceOfSystemA:\n n += 1\n priceOfSystemA += ticket\n ticketPriceB *= perc\n priceOfSystemB += ticketPriceB\n return n", "import math\n\ndef movie(card, ticket, perc):\n num_trips = 0\n card_cost = card\n ticket_cost = 0\n while math.ceil(card_cost) >= ticket_cost:\n num_trips += 1\n card_cost += ticket * (perc ** num_trips)\n ticket_cost += ticket\n return num_trips", "import math\ndef movie(card, ticket, perc):\n reduced = ticket*perc\n total = card + reduced\n n=1\n while math.ceil(total) >= ticket * n:\n reduced *= perc\n total += reduced\n n += 1\n return n", "def movie(card, ticket, perc):\n import math\n n=1\n s1=ticket\n s2=card+ticket*perc\n while s1<=math.ceil(s2):\n n+=1\n s1=ticket*n\n s2+=ticket*perc**n\n return n", "import math\n\ndef movie(card, ticket, perc):\n n = 1\n ticket_b = ticket\n ticket_total = 0\n sys_a = ticket\n sys_b = card+ticket \n c = ((sys_b))/((sys_a))\n if (c < 1) :\n return 1\n exit \n else: \n while True:\n sys_a = (n) * ticket\n ticket_b = ticket_b * perc\n ticket_total = ticket_total + ticket_b\n sys_b = card + ticket_total \n if (math.ceil(sys_b) < sys_a ):\n return n\n else : \n n +=1\n return n", "import math\ndef movie(card, ticket, perc):\n i = 1\n lhs = lambda: ticket * i\n rhs = lambda: math.ceil(card + ticket*(1-perc**i)/(1-perc))\n \n while lhs() <= rhs():\n i *= 2\n \n low = i/2-1\n high = i+1\n \n while low+1 != high :\n i = (low + high)//2\n if lhs() <= rhs():\n low = i\n else :\n high = i\n \n p_lhs = lhs()\n i += 1\n if p_lhs > rhs():\n return i-2\n return i-1", "import math\ndef movie(card, ticket, perc):\n i = 1\n lhs = lambda: ticket * i\n rhs = lambda: math.ceil(card + ticket*(1-perc**i)/(1-perc))\n \n while lhs() <= rhs():\n i += 1\n \n return i-1", "import math\n\ndef movie(card, ticket, perc):\n number_of_tickets = 0\n scenario_a = 0\n scenario_b = 1\n \n while scenario_a <= scenario_b:\n number_of_tickets += 1\n scenario_a = number_of_tickets * ticket\n scenario_b = math.ceil(card + ticket * (1 - perc ** number_of_tickets) / (1 - perc)) \n return number_of_tickets-1\n \n", "from math import ceil\n\ndef movie(card, ticket, perc):\n num = 0\n priceA = 0\n priceB = card\n while ceil(priceB) >= priceA:\n num += 1\n priceA += ticket\n priceB += ticket * (perc ** num)\n return num", "import math\ndef movie(card, ticket, perc):\n n = 0\n A = 0.0\n B = card\n while math.ceil(B) >= A:\n n += 1\n A += ticket\n B += ticket * (perc ** n)\n return n", "def movie(card, ticket, perc):\n from math import ceil\n \n b = card\n n = 1\n while True:\n a = ticket * n\n b = b + ticket * perc**n\n if b + 1 < a:\n return n\n else:\n n = n + 1", "import math\ndef movie(card, ticket, perc):\n sys_A, sys_B, count = ticket, card+ticket*perc, 1\n while sys_A <= math.ceil(sys_B):\n sys_A += ticket\n sys_B += ticket*(perc**(count+1))\n count+=1\n return count", "import math\ndef movie(card, ticket, perc):\n # your code\n times = 0\n price_A = 0\n price_B = card \n \n while(math.ceil(price_B)>=price_A):\n times+=1\n price_A+=ticket\n price_B += ticket*(perc ** times)\n \n return times \n \n \n\n", "import math\ndef movie(card, ticket, perc):\n # your code\n times = 0\n price_A = 0\n price_B = card \n \n while(math.ceil(price_B)>=price_A):\n times+=1\n price_A+=ticket\n price_B = price_B+ticket*(perc ** times)\n \n return times \n \n \n\n", "from math import *\ndef movie(card, ticket, perc):\n n=0\n priceA=0\n priceB=card\n while ceil(priceB)>=priceA:\n n+=1\n priceA+=ticket\n priceB+=ticket*(perc**n)\n return n", "import math\n\ndef movie(card, ticket, perc):\n sys_a = 0\n sys_b = card\n time = 0\n while sys_a <= math.ceil(sys_b):\n time += 1\n sys_a = ticket * time\n sys_b += ticket * (perc ** time)\n return time", "import math\n\ndef movie(card, ticket, perc):\n \n x = 0\n price1 = 0\n price2 = card\n \n while math.ceil(price2) >= price1:\n \n x +=1\n price1 += ticket\n price2 += ticket * perc ** x\n \n return x", "import math\n\ndef movie(card, ticket, perc):\n temp, spend_a, spend_b = 1, 0, 0\n \n while spend_a <= math.ceil(spend_b):\n \n spend_a += ticket\n \n if temp == 1:\n spend_b += card + ticket * perc\n else:\n spend_b += ticket * math.pow(perc,temp)\n \n temp += 1\n \n return temp-1", "from math import ceil\n\ndef movie(card, ticket, perc):\n answer = 1\n systemA = 0\n systemB = card\n while answer > 0:\n systemA += ticket\n systemB += ticket*(perc**answer)\n if ceil(systemA) > ceil(systemB):\n return answer\n answer += 1", "def movie(card, ticket, perc):\n result = 1\n B = card+ticket*perc\n while ticket*result < B+1:\n result += 1\n B += ticket*perc**result\n return result", "import math\n\ndef movie(card, ticket, perc):\n PriceA = 0\n PriceB = card\n n = 0\n while PriceA <= math.ceil(PriceB):\n n += 1\n PriceA += ticket\n PriceB += ticket * (perc ** n)\n return n", "def movie(card, ticket, perc):\n B = card\n A = 0\n n = 0\n t = ticket\n while A <= int(B)+ 1:\n A += ticket\n t *= perc\n B += t\n n += 1\n return n ", "import numpy as np\ndef movie(card, ticket, perc):\n # system A - buying tickets\n # system B - buying card and then tickets\n # wartosci, ktore wchodza do petli while:\n licznik = 0\n sysA = 0\n sysB = card # * ticket * perc\n tic_B = ticket\n while np.ceil(sysA) <= np.ceil(sysB): # rozpoczyna sie nowy obieg\n licznik += 1 # wiec go uwzgledniam\n sysA += ticket\n tic_B *= perc\n sysB += tic_B\n return licznik", "from math import ceil\n\ndef movie(card, ticket, perc):\n i=1\n card=card+ticket*perc\n while True:\n if ceil(card) < i*ticket:\n return i\n else:\n i+=1\n card += ticket*(perc**i)\n", "from math import ceil\n\ndef movie(card, ticket, perc):\n sysa = 0\n sysb = card\n ratio = ticket * perc\n times = 0\n \n while sysa <= ceil(sysb):\n sysa += ticket\n sysb += ratio\n ratio *= perc\n times += 1\n\n return times", "import math\n\ndef movie(card, ticket, perc):\n a, tc = 0, 0\n tc2 = ticket\n while math.ceil(card) >= tc:\n a += 1\n ticket = ticket * perc\n tc += tc2\n card += ticket\n return a", "def movie(card, ticket, perc):\n ticketsBought = 0\n\n a = 0\n b = card\n while (round(b,0) >= a):\n discount = pow(perc, ticketsBought)\n b += ticket * discount\n ticketsBought += 1\n\n a += ticket\n \n if (b > round(b, 0)):\n b += 1\n \n if (a > b):\n return ticketsBought - 1\n else:\n ticketsBought += 1\n return ticketsBought -1\n \n print(f\"a:{a}, b:{b}\")\n print(f\"ticketsBought:{ticketsBought - 1}\")\n return ticketsBought - 1", "import math\n\ndef movie(card, ticket, perc):\n A = 0\n B = card\n i = 0\n \n while math.ceil(B) >= A:\n i = i+1\n A = A + ticket\n B = B + ticket*perc**i\n \n return i\n\n # your code\n", "def movie(card, ticket, perc):\n import math\n i = 0\n sys_A = 0\n sys_B = card\n while True:\n i += 1\n sys_B += ticket*(perc**i)\n sys_A += ticket\n if math.ceil(sys_B) < sys_A:\n return i", "import math \ndef movie(card, ticket, perc):\n n = 0\n c = 0\n x = ticket\n while c <= math.ceil(card):\n n += 1\n c += ticket\n x *= perc\n card += x\n return n", "from math import ceil\n\ndef movie(c, t, p):\n n = 1\n while ceil(c + p * t * ((p ** n - 1) / (p - 1))) >= n * t:\n n += 1\n return n", "import math\ndef movie(card, ticket, perc):\n sysA = ticket\n sysB = ticket*perc\n count = 1\n while card+math.ceil(sysB) >= sysA:\n sysA+=ticket\n sysB = (sysB) + (ticket)*(perc**(count+1))\n count+=1\n \n return count", "def movie(c, t, p):\n s = c\n n = 1 \n while True:\n summation = (1 - p**(n+1))/(1-p) - 1\n if int(s + t*summation)+1 < n*t:\n break\n n += 1\n return n\n", "import math\ndef movie(card, ticket, perc):\n #System B\n price_A = 0\n visits = 0\n while math.ceil(card) >= price_A:\n price_A += ticket\n card += ticket * (perc ** visits)\n visits += 1\n return visits -1", "def movie(card, ticket, perc):\n import math \n n = 1\n while n * ticket -card <= math.ceil(ticket* (perc**n - 1)/(perc -1)):\n n +=1\n return n-1", "def movie(card, ticket, perc):\n numero_de_tickets = 0\n novo_valor_do_ticket = ticket * perc\n valor_inteiro_do_ticket = 0\n while valor_inteiro_do_ticket <= int(card) + 1:\n card += novo_valor_do_ticket\n valor_inteiro_do_ticket += ticket\n novo_valor_do_ticket *= perc\n numero_de_tickets += 1\n return numero_de_tickets", "import math\ndef movie(card, ticket, perc):\n a = 0\n b = card\n n = 0\n while math.ceil(b) >= a:\n n += 1\n a += ticket\n b += ticket * (perc ** n)\n return n", "import math\ndef movie(card, ticket, perc):\n tickets = 1\n system_a = ticket\n system_b = card + (ticket * perc)\n while True:\n if math.ceil(system_b) < system_a:\n return tickets\n tickets += 1\n system_a += ticket\n system_b += ticket * perc ** tickets", "def movie(card, ticket, perc):\n import math\n \n sysa = 0\n sysb = card\n tickets = 0\n while True:\n tickets += 1\n sysa += ticket\n sysb += ticket * (perc ** tickets)\n \n if math.ceil(sysb) < sysa:\n return tickets", "import math\ndef movie(card, ticket, perc):\n tickets = 1\n ticket_a = ticket\n ticket_b = card+ticket*perc\n while True:\n if math.ceil(ticket_b) < ticket_a:\n return tickets\n ticket_a += ticket\n ticket_b += ticket*(perc**(tickets+1))\n tickets += 1", "from math import ceil\n\ndef movie(card, ticket, perc):\n n = 1\n p = card + ticket*perc\n while ceil(p)>=n*ticket:\n n += 1\n p += ticket*(pow(perc,n))\n return n", "import math\n\ndef movie(card, ticket, perc):\n v=0\n i=0\n while 1:\n i=i+1\n if i==1:\n v=ticket*perc\n \n elif i>1:\n v=(v*perc)\n \n card += v\n \n if math.ceil(card) < (ticket*i):\n return i\n\n \n \n\n \n", "def movie(card, ticket, perc):\n import math\n SystemB = card\n for num in range(1,500_000):\n SystemB += ticket * perc ** num\n if num * ticket > math.ceil(SystemB):\n break\n return num", "def movie(card, ticket, perc):\n A,B = ticket,card+(ticket*perc)\n prev,count = ticket*perc, 1\n while A <= int(B)+1:\n count +=1\n prev = prev*perc\n A += ticket\n B += prev\n return count\n", "from math import ceil\ndef movie(card, ticket, perc):\n n=1\n while True:\n card = card+ticket*perc**n\n ticket_price = ticket*n\n if ticket_price > ceil(card):\n return n\n n+=1\n", "from math import ceil\ndef movie(card, ticket, perc):\n n=0\n while True:\n n+=1\n sysA=ticket*n\n sysB=ceil(card + ticket*perc*(1-perc**n)/(1-perc))\n if sysA>sysB:\n return n\n", "import math\ndef movie(card, ticket, perc):\n system_a: int = 0\n n: int = 0\n\n system_b = card\n ticket_b = ticket * perc\n\n while system_a <= math.ceil(system_b):\n n += 1\n system_a = ticket * n\n system_b += ticket_b\n ticket_b = ticket_b * perc\n\n system_b = math.ceil(system_b)\n print(f'system A price is {system_a}')\n print(f'system B price is {system_b}')\n return n", "def movie(a, b, c):\n import math\n for n in range(500000):\n if n*b> math.ceil(a+b*(1-c**n)/(1-c)):\n return n-1", "import math\ndef movie(card, ticket, perc):\n priceA = 0\n priceB = card\n visits = 0\n while priceA <= math.ceil(priceB):\n visits += 1\n priceB += ticket * perc**visits\n priceA += ticket\n return visits\n", "from math import ceil\n\n\n\ndef movie(card, ticket, rate):\n count = 0\n totala = 0.0\n totalb = 0.0\n\n while (ceil(card + totalb) >= totala):\n totala += ticket\n totalb = (totalb + ticket) * rate\n count += 1\n\n return count\n", "import math\ndef movie(card, ticket, perc):\n count=0\n system_A=0\n system_B=card\n while math.ceil(system_B) >= system_A:\n count+=1\n system_A+=ticket\n system_B+=ticket*(perc**count)\n #count+=1\n return count", "import math\ndef movie(card, ticket, perc):\n a, count = ticket, 1\n ticket_p = perc*ticket\n b = card + ticket_p\n while a <= math.ceil(b):\n a += ticket\n ticket_p *= perc\n b += ticket_p\n count += 1\n return count "] | {"fn_name": "movie", "inputs": [[500, 15, 0.9], [100, 10, 0.95], [0, 10, 0.95], [250, 20, 0.9], [500, 20, 0.9], [2500, 20, 0.9]], "outputs": [[43], [24], [2], [21], [34], [135]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 26,901 |
def movie(card, ticket, perc):
|
768f0d93ba5e5a27c55b7af41a64ffc6 | UNKNOWN | You will have a list of rationals in the form
```
lst = [ [numer_1, denom_1] , ... , [numer_n, denom_n] ]
```
or
```
lst = [ (numer_1, denom_1) , ... , (numer_n, denom_n) ]
```
where all numbers are positive integers. You have to produce their sum `N / D` in an irreducible form: this means that `N` and `D` have only `1` as a common divisor.
Return the result in the form:
- `[N, D]` in Ruby, Crystal, Python, Clojure, JS, CS, PHP, Julia
- `Just "N D"` in Haskell, PureScript
- `"[N, D]"` in Java, CSharp, TS, Scala, PowerShell, Kotlin
- `"N/D"` in Go, Nim
- `{N, D}` in C++, Elixir
- `{N, D}` in C
- `Some((N, D))` in Rust
- `Some "N D"` in F#, Ocaml
- `c(N, D)` in R
- `(N, D)` in Swift
- `'(N D)` in Racket
If the result is an integer (`D` evenly divides `N`) return:
- an integer in Ruby, Crystal, Elixir, Clojure, Python, JS, CS, PHP, R, Julia
- `Just "n"` (Haskell, PureScript)
- `"n"` Java, CSharp, TS, Scala, PowerShell, Go, Nim, Kotlin
- `{n, 1}` in C++
- `{n, 1}` in C
- `Some((n, 1))` in Rust
- `Some "n"` in F#, Ocaml,
- `(n, 1)` in Swift
- `n` in Racket
If the input list is empty, return
- `nil/None/null/Nothing`
- `{0, 1}` in C++
- `{0, 1}` in C
- `"0"` in Scala, PowerShell, Go, Nim
- `O` in Racket
- `""` in Kotlin
### Example:
```
[ [1, 2], [1, 3], [1, 4] ] --> [13, 12]
1/2 + 1/3 + 1/4 = 13/12
```
### Note
See sample tests for more examples and the form of results. | ["from fractions import Fraction\n\ndef sum_fracts(lst):\n if lst:\n ret = sum(Fraction(a, b) for (a, b) in lst)\n return ret.numerator if ret.denominator == 1 else [ret.numerator, ret.denominator]\n", "from fractions import Fraction\ndef sum_fracts(lst):\n s = sum(Fraction(*f) for f in lst)\n if s: return s.numerator if s.denominator == 1 else [s.numerator, s.denominator]\n", "from fractions import Fraction\n\ndef sum_fracts(lst):\n if lst:\n ret = sum(map(lambda l: Fraction(*l), lst))\n return [ret.numerator, ret.denominator] if ret.denominator != 1 else ret.numerator", "from fractions import Fraction\ndef sum_fracts(lst):\n if not lst: return None\n r = sum([Fraction(f[0], f[1]) for f in lst])\n return r.numerator if r.denominator == 1 else [r.numerator, r.denominator]", "from fractions import Fraction\ndef sum_fracts(lst):\n out = Fraction(0, 1)\n for x in lst: out = out + Fraction(x[0], x[1]) \n return None if out.numerator == 0 else out.numerator if out.denominator == 1 else [out.numerator, out.denominator]\n", "from fractions import Fraction\nfrom itertools import starmap\n\ndef sum_fracts (fractions):\n if not fractions:\n return None\n \n total = sum(starmap(Fraction, fractions))\n if total.denominator == 1:\n return total.numerator\n return [total.numerator, total.denominator]\n", "def sum_fracts(lst):\n print(lst)\n if lst == []: return None\n ll = len(lst)\n n, cd, md = 2, 1, min( lst[i][1] for i in range(ll) )\n while n <= md:\n if all( lst[i][1] % n == 0 for i in range(ll) ): cd = n\n n += 1\n print(('max common divider: {}'.format(cd)))\n \n dd = cd\n for i in range(ll):\n dd = dd * (lst[i][1]//cd)\n \n nn = sum( lst[i][0]*(dd//lst[i][1]) for i in range(ll) )\n \n i, primes = 0, [2, 3, 5, 7, 11, 13, 17] # it's too expensive to strip down nn and dd, so cheat with small primes\n while i < len(primes):\n n = primes[i]\n if nn % n == 0 and dd % n == 0:\n nn = nn//n\n dd = dd//n\n else:\n i += 1\n if dd == 1: return nn\n else: return [nn, dd]\n", "from fractions import Fraction\n\ndef sum_fracts(lst):\n f = sum(Fraction(n, d) for n, d in lst)\n return f.numerator or None if f.denominator == 1 else [f.numerator, f.denominator]", "from fractions import Fraction\nfrom itertools import starmap\ndef sum_fracts(lst):\n if lst:\n f = sum(starmap(Fraction, lst))\n return [f.numerator, f.denominator] if f.denominator > 1 else f.numerator"] | {"fn_name": "sum_fracts", "inputs": [[[[1, 2], [1, 3], [1, 4]]], [[[1, 3], [5, 3]]], [[[12, 3], [15, 3]]], [[[2, 7], [1, 3], [1, 12]]], [[[69, 130], [87, 1310], [3, 4]]], [[[77, 130], [84, 131], [60, 80]]], [[[6, 13], [187, 1310], [31, 41]]], [[[8, 15], [7, 111], [4, 25]]], [[]], [[[81345, 15786], [87546, 11111111], [43216, 255689]]], [[[1, 8], [1, 9]]], [[[2, 8], [1, 9]]]], "outputs": [[[13, 12]], [2], [9], [[59, 84]], [[9177, 6812]], [[67559, 34060]], [[949861, 698230]], [[2099, 2775]], [null], [[79677895891146625, 14949283383840498]], [[17, 72]], [[13, 36]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,621 |
def sum_fracts(lst):
|
117d6bbf8bccadb6d1529fa0b3a8ea80 | UNKNOWN | Scheduling is how the processor decides which jobs(processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One solution is Shortest Job First(SJF), which today you will be implementing.
SJF works by, well, letting the shortest jobs take the CPU first. If the jobs are the same size then it is First In First Out (FIFO). The idea is that the shorter jobs will finish quicker, so theoretically jobs won't get frozen because of large jobs. (In practice they're frozen because of small jobs).
You will be implementing:
```python
def SJF(jobs, index)
```
It takes in:
1. "jobs" a non-empty array of positive integers. They represent the clock-cycles(cc) needed to finish the job.
2. "index" a positive integer. That represents the job we're interested in.
SJF returns:
1. A positive integer representing the cc it takes to complete the job at index.
Here's an example:
```
SJF([3, 10, 20, 1, 2], 0)
at 0cc [3, 10, 20, 1, 2] jobs[3] starts
at 1cc [3, 10, 20, 0, 2] jobs[3] finishes, jobs[4] starts
at 3cc [3, 10, 20, 0, 0] jobs[4] finishes, jobs[0] starts
at 6cc [0, 10, 20, 0, 0] jobs[0] finishes
```
so:
```
SJF([3,10,20,1,2], 0) == 6
``` | ["def SJF(jobs, index):\n return sum(j for i, j in enumerate(jobs)\n if j < jobs[index] or (j == jobs[index] and i <= index))\n", "SJF = lambda jobs, index: sum(j for i, j in enumerate(jobs) if j <= jobs[index] and (jobs[i] != jobs[index] or i <= index))", "def SJF(jobs, index):\n return sum(n for i, n in enumerate(jobs) if n < jobs[index] or (n == jobs[index] and i <= index))\n\n\n\n \n\n\n #jobs = jobs.copy()\n #cycles = 0\n #for n in sorted(jobs):\n # cycles += n\n # i = jobs.index(n)\n # jobs[i] = 0\n # if i == index:\n # break\n #return cycles\n", "def SJF(jobs, index):\n return sum(c for i, c in enumerate(jobs) if c < jobs[index] or (c == jobs[index] and i <= index))", "def SJF(jobs, index):\n return sum(n for i, n in enumerate(jobs) if n < jobs[index] + (i <= index))", "def SJF(jobs, index):\n return sum(list(filter(lambda x: x<jobs[index],jobs)))+sum(list(filter(lambda x: x==jobs[index], jobs[0:index+1])))", "def SJF(jobs, index):\n job = jobs[index]\n return sum(sorted(jobs)[:sorted(jobs).index(job)+1]) + (job * jobs[:index].count(job))", "SJF = lambda arr, j: sum(k for k in arr if k<arr[j]) + (arr[:j+1].count(arr[j]))*arr[j]", "SJF = lambda jobs, index: sum(j for i, j in enumerate(jobs) if j < jobs[index] or (j == jobs[index] and i < index)) + jobs[index]", "from operator import itemgetter\n\ndef SJF(jobs, index):\n total = 0\n for i, duration in sorted(enumerate(jobs), key=itemgetter(1)):\n total += duration\n if i == index:\n return total"] | {"fn_name": "SJF", "inputs": [[[100], 0], [[3, 10, 20, 1, 2], 0], [[3, 10, 20, 1, 2], 1], [[3, 10, 10, 20, 1, 2], 1], [[3, 10, 10, 20, 1, 2], 2], [[3, 10, 20, 1, 2, 3], 5], [[3, 10, 20, 1, 2, 10, 10], 5]], "outputs": [[100], [6], [16], [16], [26], [9], [26]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,593 |
def SJF(jobs, index):
|
853a9dfb3806d341e5ba7abc343c5ec6 | UNKNOWN | We are interested in collecting the sets of six prime numbers, that having a starting prime p, the following values are also primes forming the sextuplet ```[p, p + 4, p + 6, p + 10, p + 12, p + 16]```
The first sextuplet that we find is ```[7, 11, 13, 17, 19, 23]```
The second one is ```[97, 101, 103, 107, 109, 113]```
Given a number ```sum_limit```, you should give the first sextuplet which sum (of its six primes) surpasses the sum_limit value.
```python
find_primes_sextuplet(70) == [7, 11, 13, 17, 19, 23]
find_primes_sextuplet(600) == [97, 101, 103, 107, 109, 113]
```
Features of the tests:
```
Number Of Tests = 18
10000 < sum_limit < 29700000
```
If you have solved this kata perhaps you will find easy to solve this one:
https://www.codewars.com/kata/primes-with-two-even-and-double-even-jumps/
Enjoy it!! | ["def find_primes_sextuplet(limit):\n for p in [7, 97, 16057, 19417, 43777, 1091257, 1615837, 1954357, 2822707, 2839927, 3243337, 3400207, 6005887]:\n if p * 6 + 48 > limit:\n return [p, p + 4, p + 6, p + 10, p + 12, p + 16]", "n = 6005904\nsieve = [True] * (n // 2)\nfor i in range(3, int(n**0.5) + 1, 2):\n if sieve[i // 2]:\n sieve[i * i // 2::i] = [False] * ((n - i * i - 1) // (2 * i) + 1)\nprimes = {2} | {(2 * i + 1) for i in range(1, n // 2) if sieve[i]}\n\ndef find_primes_sextuplet(limit):\n i = limit // 6 - 8\n p = next(n for n in range(i, i+10) if n % 10 == 7)\n while not {p, p+4, p+6, p+10, p+12, p+16}.issubset(primes):\n p += 10\n return [p, p+4, p+6, p+10, p+12, p+16]", "# Reference: https://oeis.org/A022008\n# I hope this isn't considered as cheating :)\n\n\nA022008 = [\n 7, 97, 16057, 19417, 43777, 1091257,\n 1615837, 1954357, 2822707, 2839927,\n 3243337, 3400207, 6005887, 6503587,\n 7187767, 7641367, 8061997, 8741137,\n 10526557, 11086837, 11664547, 14520547,\n 14812867, 14834707, 14856757, 16025827,\n 16094707, 18916477, 19197247\n]\n\n\ndef find_primes_sextuplet(n):\n t = (n - 48) // 6\n r = next(x for x in A022008 if x > t)\n return [i + r for i in [0, 4, 6, 10, 12, 16]]", "li = [7,97,16057,19417,43777,1091257,1615837,1954357,\n 2822707,2839927,3243337,3400207,6005887,6503587,\n 7187767,7641367,8061997,8741137,10526557,11086837,\n 11664547,14520547,14812867,14834707,14856757,\n 16025827,16094707,18916477,19197247]\nsequences = [[i+j for j in [0,4,6,10,12,16]] for i in li]\nfind_primes_sextuplet=lambda s:next(i for i in sequences if sum(i)>s)", "from bisect import bisect\n\nsums = [90, 630, 96390, 116550, 262710, 6547590, 9695070, 11726190, 16936290, 17039610, 19460070, 20401290, 36035370]\nresult = [[7, 11, 13, 17, 19, 23],\n [97, 101, 103, 107, 109, 113],\n [16057, 16061, 16063, 16067, 16069, 16073],\n [19417, 19421, 19423, 19427, 19429, 19433],\n [43777, 43781, 43783, 43787, 43789, 43793],\n [1091257, 1091261, 1091263, 1091267, 1091269, 1091273],\n [1615837, 1615841, 1615843, 1615847, 1615849, 1615853],\n [1954357, 1954361, 1954363, 1954367, 1954369, 1954373],\n [2822707, 2822711, 2822713, 2822717, 2822719, 2822723],\n [2839927, 2839931, 2839933, 2839937, 2839939, 2839943],\n [3243337, 3243341, 3243343, 3243347, 3243349, 3243353],\n [3400207, 3400211, 3400213, 3400217, 3400219, 3400223],\n [6005887, 6005891, 6005893, 6005897, 6005899, 6005903]]\n\ndef find_primes_sextuplet(sum_limit):\n return result[bisect(sums, sum_limit)]", "doge = [\n [7, 11, 13, 17, 19, 23], \n [97, 101, 103, 107, 109, 113], \n [16057, 16061, 16063, 16067, 16069, 16073], \n [19417, 19421, 19423, 19427, 19429, 19433], \n [43777, 43781, 43783, 43787, 43789, 43793], \n [1091257, 1091261, 1091263, 1091267, 1091269, 1091273], \n [1615837, 1615841, 1615843, 1615847, 1615849, 1615853], \n [1954357, 1954361, 1954363, 1954367, 1954369, 1954373], \n [2822707, 2822711, 2822713, 2822717, 2822719, 2822723], \n [2839927, 2839931, 2839933, 2839937, 2839939, 2839943], \n [3243337, 3243341, 3243343, 3243347, 3243349, 3243353], \n [3400207, 3400211, 3400213, 3400217, 3400219, 3400223],\n [6005887, 6005891, 6005893, 6005897, 6005899, 6005903]\n]\n\ndef find_primes_sextuplet(sum_limit):\n for d in doge:\n if sum(d) > sum_limit:\n return d", "sextuplets=[\n [7, 11, 13, 17, 19, 23],\n [97, 101, 103, 107, 109, 113],\n [16057, 16061, 16063, 16067, 16069, 16073],\n [19417, 19421, 19423, 19427, 19429, 19433],\n [43777, 43781, 43783, 43787, 43789, 43793],\n [1091257, 1091261, 1091263, 1091267, 1091269, 1091273],\n [1615837, 1615841, 1615843, 1615847, 1615849, 1615853],\n [1954357, 1954361, 1954363, 1954367, 1954369, 1954373],\n [2822707, 2822711, 2822713, 2822717, 2822719, 2822723],\n [2839927, 2839931, 2839933, 2839937, 2839939, 2839943],\n [3243337, 3243341, 3243343, 3243347, 3243349, 3243353],\n [3400207, 3400211, 3400213, 3400217, 3400219, 3400223],\n [6005887, 6005891, 6005893, 6005897, 6005899, 6005903]]\ndef find_primes_sextuplet(sum_limit):\n for t in sextuplets:\n if sum(t)>sum_limit:\n return t"] | {"fn_name": "find_primes_sextuplet", "inputs": [[70], [600], [2000000]], "outputs": [[[7, 11, 13, 17, 19, 23]], [[97, 101, 103, 107, 109, 113]], [[1091257, 1091261, 1091263, 1091267, 1091269, 1091273]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,370 |
def find_primes_sextuplet(sum_limit):
|
ea5a2400430576325b6b4c126e9e6da0 | UNKNOWN | The sum of divisors of `6` is `12` and the sum of divisors of `28` is `56`. You will notice that `12/6 = 2` and `56/28 = 2`. We shall say that `(6,28)` is a pair with a ratio of `2`. Similarly, `(30,140)` is also a pair but with a ratio of `2.4`. These ratios are simply decimal representations of fractions.
`(6,28)` and `(30,140)` are the only pairs in which `every member of a pair is 0 <= n < 200`. The sum of the lowest members of each pair is `6 + 30 = 36`.
You will be given a `range(a,b)`, and your task is to group the numbers into pairs with the same ratios. You will return the sum of the lowest member of each pair in the range. If there are no pairs. return `nil` in Ruby, `0` in python. Upper limit is `2000`.
```Haskell
solve(0,200) = 36
```
Good luck!
if you like this Kata, please try:
[Simple division](https://www.codewars.com/kata/59ec2d112332430ce9000005)
[Sub-array division](https://www.codewars.com/kata/59eb64cba954273cd4000099) | ["from collections import defaultdict\nfrom fractions import Fraction\nfrom bisect import bisect_left as bisect\n\nharmonic = [0] + [Fraction(sum({y for x in range(1,int(n**.5)+1) for y in [x, n//x] if not n%x}), n) for n in range(1,7001)]\n\nharmonicity = defaultdict(set)\nfor n,h in enumerate(harmonic): harmonicity[h].add(n)\n\nHARMO_GROUPS = {h: sorted(s) for h,s in harmonicity.items() if len(s) > 1}\nHARMO_RATIOS = {n: h for h,lst in HARMO_GROUPS.items() for n in lst}\nHARMO_NUM = sorted(HARMO_RATIOS.keys())\n\ndef solve(a,b):\n seens, s = set(), 0\n n1, n2 = bisect(HARMO_NUM, a), bisect(HARMO_NUM, b)\n for n in HARMO_NUM[n1:n2]:\n if n not in seens:\n grp = [x for x in HARMO_GROUPS[HARMO_RATIOS[n]] if a <= x < b]\n if len(grp) > 1:\n seens |= set(grp)\n s += grp[0]\n return s", "import collections\n\ndef solve(a,b):\n d = collections.defaultdict(list)\n for n in range(a, b):\n d[(sum(k + n//k for k in range(1, int(n**0.5)+1) if n%k==0) - (int(n**0.5) if int(n**0.5) == n**0.5 else 0))/n].append(n)\n return sum(v[0] for v in list(d.values()) if len(v) > 1)\n", "from collections import defaultdict\n\nD = defaultdict(list)\nfor x in range(1, 2000):\n D[sum(y for y in range(1, x+1) if x%y == 0) / x].append(x)\nresult = [v for v in D.values() if len(v) >= 2]\n\n# Fuck [6, 28, 496] and [84, 270, 1488, 1638], description was unclear\ndef solve(a,b):\n def check(p):\n for x in range(len(p)-1):\n if a <= p[x] and p[x+1] < b:\n return p[x]\n return 0\n return sum(map(check, result))", "from collections import defaultdict\nfrom fractions import Fraction\n\ndef divisorsum(n):\n s = 0\n for i in range(1, int(n ** 0.5)+1):\n if n % i == 0:\n s += i\n s += n // i\n if i * i == n:\n s -= i\n return s\n\nd = defaultdict(list)\nfor i in range(1, 2000+1):\n d[Fraction(divisorsum(i), i)].append(i)\n\nxs = [value for key, value in d.items() if len(value) > 1]\n\ndef solve(a,b):\n ys = [[y for y in x if a <= y < b] for x in xs]\n return sum(y[0] for y in ys if len(y) > 1)", "from itertools import groupby\nfrom operator import itemgetter\ndef solve(a,b):\n def factors(n):\n seen = set([1, n])\n for a in range(2, 1 + int(n ** 0.5)):\n b, m = divmod(n, a)\n if m == 0:\n if a in seen: break\n seen.add(a)\n seen.add(b)\n return seen\n\n s = 0\n for k, g in groupby(sorted(((sum(factors(a)) / a, a) for a in range(a, b)), key = itemgetter(0)), key = itemgetter(0)):\n gl = list(g)\n if len(gl) > 1:\n s += min(map(itemgetter(1), gl))\n return s", "from collections import defaultdict\nfrom fractions import Fraction\n\nharmonic = [0] + [Fraction(sum({y for x in range(1,int(n**.5)+1) for y in [x, n//x] if not n%x}), n) for n in range(1,7001)]\n\nharmonicity = defaultdict(set)\nfor n,h in enumerate(harmonic): harmonicity[h].add(n)\n\nHARMO_GROUPS = {h: sorted(s) for h,s in harmonicity.items() if len(s) > 1}\nHARMO_RATIOS = {n: h for h,lst in HARMO_GROUPS.items() for n in lst}\n\ndef solve(a,b):\n seens, s = set(), 0\n for n,h in HARMO_RATIOS.items():\n if n not in seens and a <= n < b:\n grp = [x for x in HARMO_GROUPS[HARMO_RATIOS[n]] if a <= x < b]\n if len(grp) > 1:\n seens |= set(grp)\n s += grp[0]\n return s", "def solve(a,b):\n H = {}\n for n in range(a, b):\n r = {1, n}\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0: r.update([i, n//i])\n d = sum(r) / n\n H[d] = H.get(d, []) + [n]\n return sum(H[k][0] for k in H if len(H[k]) > 1) ", "def divisor_sum(n):\n s = 0; i = 1\n while i*i<=n:\n if n%i==0: s+=i+n//i\n i+=1\n if (i-1)**2 == n: s -= (i-1)\n return s\n\nratios = {}\nfor i in range(2,7001):\n d = divisor_sum(i); ratio = d/i\n if ratio in ratios: ratios[ratio] += [i]\n else: ratios[ratio] = [i]\nratios = [v for k, v in ratios.items() if len(v)>1]\n\ndef solve(a,b):\n d = [[r for r in v if r>=a and r<b] for v in ratios]\n return sum(min(v) for v in d if len(v)>1)", "from fractions import Fraction as F\n\ncache = {}\ndef divisors(n):\n result = cache.get(n)\n if result is not None:\n return result\n if n < 2:\n return [1] if n == 1 else []\n result = set([1, n])\n for i in range(2, n // 2):\n if n % i == 0:\n result.add(i)\n result.add(n // i)\n cache[n] = result\n return result\n\n\ndef solve(a, b):\n print(f'a: {a}, b: {b}')\n vals = {}\n for n in range(max(a, 1), b):\n r = F(sum(divisors(n)), n)\n vals.setdefault(r, []).append(n)\n \n result = 0\n for k, v in vals.items():\n if len(v) >= 2:\n result += v[0]\n return result", "import math\nfrom fractions import Fraction\n\ndef divisorGenerator(n): #\u6c42\u6240\u6709\u9664\u6570\n large_divisors = []\n for i in range(1, int(math.sqrt(n) + 1)):\n if n % i == 0:\n yield i\n if i*i != n:\n large_divisors.append(n / i)\n for divisor in reversed(large_divisors):\n yield divisor\n\ndef solve(m,n):\n div_ratios = []\n input_list = [x for x in range(m,n+1)]\n #print(input_list)\n for i in range(m,n):\n div_sum = 0\n for j in list(divisorGenerator(i)):\n div_sum += int(j)\n #div_ratios.append(div_sum/i)\n div_ratios.append(str(Fraction(div_sum,i)))\n #print('number=',i,'\u9664\u6570\u548c=',div_sum,'ratio=',div_sum/i,Fraction(div_sum,i),type(Fraction(div_sum,i)))\n #print(div_ratios,div_ratios)\n\n array = []\n for i in range(len(div_ratios)):\n for j in range(i+1,len(div_ratios)):\n if div_ratios[i] == div_ratios[j]:\n array.append([input_list[i],input_list[j]])\n #array.append(div_ratios[j])\n print(array)\n ret_sums = 0\n for k in range(len(array)):\n ret_sums += int(array[k][0])\n if m <=6 and n >=496:\n ret_sums = ret_sums - 34\n return ret_sums"] | {"fn_name": "solve", "inputs": [[1, 100], [1, 200], [1, 300], [200, 1000], [1, 1000], [100, 1000], [800, 2000]], "outputs": [[6], [36], [252], [1104], [2619], [2223], [2352]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 6,291 |
def solve(a,b):
|
58f7c6d3dd6fa2bf962f27d6124664a9 | UNKNOWN | Given two integers `a` and `b`, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return `a` or `b`.
**Note:** `a` and `b` are not ordered!
## Examples
```python
get_sum(1, 0) == 1 // 1 + 0 = 1
get_sum(1, 2) == 3 // 1 + 2 = 3
get_sum(0, 1) == 1 // 0 + 1 = 1
get_sum(1, 1) == 1 // 1 Since both are same
get_sum(-1, 0) == -1 // -1 + 0 = -1
get_sum(-1, 2) == 2 // -1 + 0 + 1 + 2 = 2
```
```C
get_sum(1, 0) == 1 // 1 + 0 = 1
get_sum(1, 2) == 3 // 1 + 2 = 3
get_sum(0, 1) == 1 // 0 + 1 = 1
get_sum(1, 1) == 1 // 1 Since both are same
get_sum(-1, 0) == -1 // -1 + 0 = -1
get_sum(-1, 2) == 2 // -1 + 0 + 1 + 2 = 2
``` | ["def get_sum(a,b):\n return sum(range(min(a, b), max(a, b) + 1))", "def get_sum(a, b):\n return (a + b) * (abs(a - b) + 1) // 2", "def get_sum(a,b):\n soma=0\n if a==b:\n return a\n elif a > b:\n for i in range(b,a+1):\n soma += i\n return soma\n else:\n for i in range(a,b+1):\n soma += i\n return soma", "def get_sum(a,b):\n if a>b : a,b = b,a\n return sum(range(a,b+1))", "# Beginner Sum of Numbers by Dr. Professor, Esq.\n# \n# input: any two numbers, positive or negative, as a and b\n# output: print the sum all numbers between a and b; including a and b\n#\n# pseudo-code:\n# test for equality\n# if equal print a\n#\n# if a greater than b\n# loop through the value of each number between b and a\n# accumulate each value in x\n#\n# if b greater than a\n# loop through the value of each number between a and b\n# accumulate each value in x\n#\n# return x\n\ndef get_sum(a,b):\n x=0 \n if a == b: \n return a \n \n elif a > b: \n for i in range(b, a+1):\n x+=i\n elif b > a:\n for i in range(a, b+1):\n x+=i\n return x", "def get_sum(a,b):\n sum = 0\n if a==b:\n return a\n if b<a:\n a, b = b, a\n for i in range(a,b+1):\n sum += i\n return sum", "def get_sum(a, b):\n return (a + b) * (abs(a - b) + 1) / 2", "def get_sum(a,b):\n return sum([x for x in range(min(a,b),max(a,b)+1)])"] | {"fn_name": "get_sum", "inputs": [[0, 1], [1, 2], [5, -1], [505, 4], [321, 123], [0, -1], [-50, 0], [-1, -5], [-5, -5], [-505, 4], [-321, 123], [0, 0], [-5, -1], [5, 1], [-17, -17], [17, 17]], "outputs": [[1], [3], [14], [127759], [44178], [-1], [-1275], [-15], [-5], [-127755], [-44055], [0], [-15], [15], [-17], [17]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,576 |
def get_sum(a,b):
|
1f1341d0f92502311ec9b0eb4ec99c84 | UNKNOWN | The first positive integer, `n`, with its value `4n² + 1`, being divisible by `5` and `13` is `4`. (condition 1)
It can be demonstrated that we have infinite numbers that may satisfy the above condition.
If we name **ai**, the different terms of the sequence of numbers with this property, we define `S(n)` as:
We are interested in working with numbers of this sequence from 10 to 15 digits. Could you elaborate a solution for these results?
You will be given an integer value `m`(always valid an positive) and you should output the closest value of the sequence to `m`.
If the given value `m` is in the sequence, your solution should return the same value.
In the case that there are two possible solutions: `s1` and `s2`, (`s1 < s2`), because `|m - s1| = |m - s2|`, output the highest solution `s2`
No hardcoded solutions are allowed.
No misterious formulae are required, just good observation to discover hidden patterns.
See the example tests to see output format and useful examples, edge cases are included.
Features of the random tests
`1000 <= m <= 5.2 e14`
**Note** Sierpinsky presented the numbers that satisfy condition (1) | ["def sierpinski():\n x = s = 0\n while 1:\n for a in 4, 9, 56, 61:\n s += x + a\n yield s\n x += 65\n\ns = sierpinski()\nS = [next(s)]\n\nfrom bisect import bisect_left\ndef find_closest_value(m):\n while S[-1] < m: S.append(next(s))\n i = bisect_left(S, m)\n return min(S[i:i-2:-1], key=lambda n: abs(m - n))", "import math\ndef find_closest_value(Q) :\n B = math.ceil((math.ceil(Q / 65) / 2) ** .5)\n S,B = 130 * B * B,65 * B\n return S - min((0,B - 4,B + B - 13,3 * B - 69,4 * B - 130),key = lambda V : abs(Q - S + V)) or 4", "def find_closest_value(m):\n x = int((m/130)**0.5)\n y, z = 130 * x**2, 65*x\n res = [y + v + i*z for i,v in enumerate((0, 4, 13, 69, 130))]\n return min(res, key=lambda k: (abs(m-k), m-k)) or 4", "class SierpinskiSumFunc():\n def __init__(self):\n sierpinski_number = 4\n sierpinski_numbers_add = (5, 47, 5, 8) # (47, 5, 8, 5)\n sierpinski_sum = [4, ]\n n = 0\n while sierpinski_sum[-1] < 520000000000000:\n sierpinski_number += sierpinski_numbers_add[n]\n sierpinski_sum.append(sierpinski_sum[-1] + sierpinski_number)\n n = 0 if n == 3 else n + 1\n self.sierpinski_sum = tuple(sierpinski_sum)\n\n\nsierpinski_sum_obj = SierpinskiSumFunc()\n\ndef find_closest_value(m):\n if m <= 4:\n return 4\n if m <= 100000:\n sierpinski_sum = sierpinski_sum_obj.sierpinski_sum\n nn = 0\n while True:\n if m == sierpinski_sum[nn]:\n return m\n elif m < sierpinski_sum[nn + 1] and m > sierpinski_sum[nn]:\n return sierpinski_sum[nn + 1] if m - sierpinski_sum[nn + 1] >= sierpinski_sum[nn] - m else sierpinski_sum[nn]\n nn += 1\n elif m > 100000:\n sierpinski_sum = sierpinski_sum_obj.sierpinski_sum\n nn = -1\n while True:\n if m == sierpinski_sum[nn]:\n return m\n elif m > sierpinski_sum[nn - 1] and m < sierpinski_sum[nn]:\n return sierpinski_sum[nn - 1] if m - sierpinski_sum[nn - 1] < sierpinski_sum[nn] - m else sierpinski_sum[nn]\n if m < sierpinski_sum[nn - 20]:\n nn -= 20\n else:\n nn -= 1", "# Helpful math trivias: \n# ---------------------\n# 1. if \"x\" is in the sequence of the 'a's, then \n# 5*13*y+x is also in the sequence of 'a's\n# 2. the base solutions are 4, 9, 56, 61\n# 3. if the sequence is terminated at the right point,\n# then it is the mix of 4 independent arithmetic\n# sequences (x=130*n**2 is the total sum of the four)\n\nimport math\n\ndef find_closest_value(x):\n if x < 4:\n return 4\n\n n = math.sqrt(x/130)\n n_low = math.floor(n)\n seed = 130*n_low**2\n n_inc = n_low*65\n candidates = [seed,\n seed+4 +1*n_inc,\n seed+13 +2*n_inc,\n seed+69 +3*n_inc,\n seed+130+4*n_inc]\n candidates=sorted(candidates,reverse=True)\n candidates=sorted(candidates,key=lambda a:abs(a-x))\n return candidates[0]", "# https://oeis.org/A203464\ns = [0]\nfor m in range(0,10**9):\n for p in (4,9,56,61):\n s.append(s[-1]+m*65+p)\n if s[-1]>52*10**13: break\n\nfrom bisect import bisect\n\ndef find_closest_value(m):\n if m<4: return 4\n i = bisect(s,m)\n return s[min([i,i-1], key=lambda i:abs(s[i]-m))]", "def find_closest_value(m):\n if m < 4:\n return 4\n l = [130 * k ** 2 + k * i * 65 + a for i, a in enumerate([4, 13, 69, 130], 1) for k in [int((m // 130) ** 0.5) - 1, int((m // 130) ** 0.5)]]\n return min(l, key = lambda x: (abs(m - x), -x))", "def find_closest_value(m):\n a = lambda i: ((i - 1) // 4) * 65 + [4, 9, 56, 61][(i - 1) % 4]\n s = lambda n: a(-~((n * n - 1) // 2)) + (4 if n % 2 == 0 else 0)\n n = int((m // 65 * 8) ** 0.5)\n while s(n) <= m:\n n += 1\n if n == 1: return 4\n d1 = s(n) - m\n d2 = m - s(n - 1)\n return s(n) if d1 <= d2 else s(n - 1)"] | {"fn_name": "find_closest_value", "inputs": [[1], [5000], [7500], [8300], [14313], [20005], [18331], [18332]], "outputs": [[4], [5074], [7293], [8320], [14313], [20293], [17944], [18720]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,051 |
def find_closest_value(m):
|
1575f45ddfebdc2d36afd49e4466a4b5 | UNKNOWN | Given two numbers (m and n) :
- convert all numbers from m to n to binary
- sum them as if they were in base 10
- convert the result to binary
- return as string
Eg: with the numbers 1 and 4
1 // 1 to binary is 1
+ 10 // 2 to binary is 10
+ 11 // 3 to binary is 11
+100 // 4 to binary is 100
----
122 // 122 in Base 10 to Binary is 1111010
So BinaryPyramid ( 1 , 4 ) should return "1111010"
range should be ascending in order | ["def binary_pyramid(m,n):\n return bin(sum(int(bin(i)[2:]) for i in range(m, n+1)))[2:]", "def binary_pyramid(m,n):\n return '{:b}'.format(sum(map(int, map('{:b}'.format, range(m,n+1)))))", "def binary_pyramid(m,n):\n return bin(int(sum(int(bin(i)[2:]) for i in range(m,n+1))))[2:]", "binary_pyramid=lambda m,n:bin(sum(int(bin(e)[2:]) for e in range(m,n+1)))[2:]", "def binary_pyramid(m,n):\n return format(sum(int(format(i, 'b')) for i in range(m, n+1)), 'b')", "def binary_pyramid(m,n):\n return bin(sum(eval(bin(i)[2:]) for i in range(m, n+1)))[2:]", "def binary_pyramid(m,n):\n sm = 0\n for i in range(m, n+1):\n sm += int(\"{0:b}\".format(i))\n return \"{0:b}\".format(sm)", "def binary_pyramid(m,n):\n suma = []\n for i in range(m,n+1):\n suma.append(int(bin(i)[2:]))\n return bin(sum(suma))[2:]", "def binary_pyramid(m,n):\n return f\"{sum(int(f'{x:b}') for x in range(m, n+1)):b}\"", "binary_pyramid = lambda a, b: bin(sum(int(bin(n)[2:]) for n in range(a, b + 1)))[2:]"] | {"fn_name": "binary_pyramid", "inputs": [[1, 4], [1, 6], [6, 20], [21, 60], [100, 100], [1, 1], [0, 1], [0, 0], [1, 100], [100, 1000]], "outputs": [["1111010"], ["101001101"], ["1110010110100011"], ["1100000100010001010100"], ["100001100100101000100"], ["1"], ["1"], ["0"], ["10011101010010110000101010"], ["111111001111110110011011000101110101110"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,030 |
def binary_pyramid(m,n):
|
8eeec589649318d91e1c604fa0f3632e | UNKNOWN | Given an array (a list in Python) of integers and an integer `n`, find all occurrences of `n` in the given array and return another array containing all the index positions of `n` in the given array.
If `n` is not in the given array, return an empty array `[]`.
Assume that `n` and all values in the given array will always be integers.
Example:
```python
find_all([6, 9, 3, 4, 3, 82, 11], 3)
> [2, 4]
``` | ["def find_all(array, n):\n return [index for index, item in enumerate(array) if item == n]", "def find_all(array, n):\n res = []\n for i in range(len(array)):\n if array[i] == n:\n res.append(i)\n return res", "def find_all(array, n):\n return [ i for i,v in enumerate(array) if v==n ]", "def find_all(array, n):\n return [i for i,x in enumerate(array) if x == n]", "def find_all(array, n):\n return [i for i in range(len(array)) if array[i] == n]", "def find_all(array, n):\n return [i[0] for i in enumerate(array) if i[1]==n]", "def find_all(array, n):\n l = []\n for i,v in enumerate(array):\n if v == n:\n l.append(i)\n return l ", "import numpy as np\n\ndef find_all(array, n):\n return list(np.where(np.array(array) == n)[0])", "def find_all(array, n):\n return [pos for pos, number in enumerate(array) if number == n]", "def find_all(array, n):\n return [i for i, number in enumerate(array) if number == n]"] | {"fn_name": "find_all", "inputs": [[[6, 9, 3, 4, 3, 82, 11], 3], [[6, 9, 3, 4, 3, 82, 11], 99], [[10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16], [[20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20]], "outputs": [[[2, 4]], [[]], [[1, 9]], [[0, 1, 8]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 999 |
def find_all(array, n):
|
4fee539b2f8a176d4ff8d8349efa682b | UNKNOWN | Task:
Given an array arr of strings complete the function landPerimeter by calculating the total perimeter of all the islands. Each piece of land will be marked with 'X' while the water fields are represented as 'O'. Consider each tile being a perfect 1 x 1piece of land. Some examples for better visualization:
['XOOXO',
'XOOXO',
'OOOXO',
'XXOXO',
'OXOOO']
or
should return:
"Total land perimeter: 24",
while
['XOOO',
'XOXO',
'XOXO',
'OOXX',
'OOOO']
should return: "Total land perimeter: 18"
Good luck! | ["def land_perimeter(arr):\n \n I,J = len(arr),len(arr[0])\n \n P = 0\n for i in range(I):\n for j in range(J):\n if arr[i][j] == 'X':\n if i == 0 or arr[i-1][j] == 'O': P += 1\n if i == I-1 or arr[i+1][j] == 'O': P += 1\n if j == 0 or arr[i][j-1] == 'O': P += 1\n if j == J-1 or arr[i][j+1] == 'O': P += 1\n \n \n return 'Total land perimeter: ' + str(P)\n", "land = lambda a: sum(t == ('X', 'X') for r in a for t in zip(r, r[1:])) * 2\n\ndef land_perimeter(a):\n return 'Total land perimeter: ' + str(''.join(a).count('X') * 4 - land(a) - land(zip(*a)))", "def land_perimeter(arr):\n result = 0\n for row in arr + list(zip(*arr)):\n current = list(row)\n result += sum(a != b for a, b in zip(['O'] + current, current + ['O']))\n return 'Total land perimeter: {}'.format(result)\n", "def land_perimeter(arr):\n perimetr=0\n height=len(arr)\n for y in range(height):\n width=len(arr[y])\n for x in range(width):\n if arr[y][x]=='X':\n if x==0 or arr[y][x-1]=='O':perimetr+=1\n if x==width-1 or arr[y][x+1]=='O':perimetr+=1\n if y==0 or arr[y-1][x]=='O':perimetr+=1\n if y==height-1 or arr[y+1][x]=='O':perimetr+=1\n return 'Total land perimeter: '+str(perimetr)", "def land_perimeter(arr):\n a, b = ' '.join(arr), ' '.join(''.join(x) for x in zip(*arr))\n p = 4 * a.count('X') - 2 * 'O{}O{}O'.format(a, b).split('X').count('')\n return 'Total land perimeter: {}'.format(p)", "def land_perimeter(arr):\n total=0\n for x in range(len(arr)):\n for y in range(len(arr[0])):\n if arr[x][y]=='X':\n total+=4\n if (x!=len(arr)-1) and (arr[x+1][y]=='X'): total-=1\n if (x!=0) and (arr[x-1][y]=='X'): total-=1\n if (y!=len(arr[0])-1) and (arr[x][y+1]=='X'): total-=1\n if (y!=0) and (arr[x][y-1]=='X'): total-=1\n return 'Total land perimeter: %i' % total", "def land_perimeter(grid):\n s, m = len(grid), len(grid[0])\n ans = 0\n for x in range(s):\n for y in range(m):\n if grid[x][y] == 'X':\n ans += 4\n if x < s - 1 and grid[x+1][y] == 'X':\n ans -= 2\n if y < m - 1 and grid[x][y+1] == 'X':\n ans -= 2\n \n return ('Total land perimeter: {}'.format(ans))", "def land_perimeter(arr):\n n = len(arr)\n m = len(arr[0])\n dr = [1, 0, -1, 0]\n dc = [0, 1, 0, -1]\n ans = 0\n for i in range(len(arr)):\n for j in range(len(arr[i])):\n if arr[i][j] == 'O': continue\n cur = 0\n for k in range(4):\n nx = i + dr[k]\n ny = j + dc[k]\n inside = (nx >= 0 and ny >= 0 and nx < n and ny < m)\n ans += (inside and arr[nx][ny] == 'O') + (not inside)\n ampogiko = \"Total land perimeter: \" + str(ans)\n return ampogiko", "def land_perimeter(arr):\n per = 0\n for _ in range(4):\n arr.insert(0, ['0']*(len(arr[0])+(_+1)))\n arr = list(zip(*arr[::-1]))\n for i in range(1,len(arr)):\n for y in range(1,len(arr[i])):\n if arr[i][y] == 'X':\n per += 4 - sum([arr[i-1][y]=='X', arr[i+1][y]=='X', arr[i][y+1]=='X', arr[i][y-1]=='X'])\n return f'Total land perimeter: {per}'"] | {"fn_name": "land_perimeter", "inputs": [[["OXOOOX", "OXOXOO", "XXOOOX", "OXXXOO", "OOXOOX", "OXOOOO", "OOXOOX", "OOXOOO", "OXOOOO", "OXOOXX"]], [["OXOOO", "OOXXX", "OXXOO", "XOOOO", "XOOOO", "XXXOO", "XOXOO", "OOOXO", "OXOOX", "XOOOO", "OOOXO"]], [["XXXXXOOO", "OOXOOOOO", "OOOOOOXO", "XXXOOOXO", "OXOXXOOX"]], [["XOOOXOO", "OXOOOOO", "XOXOXOO", "OXOXXOO", "OOOOOXX", "OOOXOXX", "XXXXOXO"]], [["OOOOXO", "XOXOOX", "XXOXOX", "XOXOOO", "OOOOOO", "OOOXOO", "OOXXOO"]], [["X"]]], "outputs": [["Total land perimeter: 60"], ["Total land perimeter: 52"], ["Total land perimeter: 40"], ["Total land perimeter: 54"], ["Total land perimeter: 40"], ["Total land perimeter: 4"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 3,424 |
def land_perimeter(arr):
|
8ab7ca5ad3881f35a6eb05884d7d3e27 | UNKNOWN | Write
```python
word_pattern(pattern, string)
```
that given a ```pattern``` and a string ```str```, find if ```str``` follows the same sequence as ```pattern```.
For example:
```python
word_pattern('abab', 'truck car truck car') == True
word_pattern('aaaa', 'dog dog dog dog') == True
word_pattern('abab', 'apple banana banana apple') == False
word_pattern('aaaa', 'cat cat dog cat') == False
``` | ["def word_pattern(pattern, string):\n x = list(pattern)\n y = string.split(\" \")\n return (len(x) == len(y) and \n len(set(x)) == len(set(y)) == len(set(zip(x, y)))\n )", "def word_pattern(pattern, string):\n return [pattern.index(any) for any in pattern] == [string.split().index(any) for any in string.split()]", "def word_pattern(pattern, string):\n match = {}\n \n if len(pattern) != len(string.split()): return False\n \n for c, word in zip(pattern, string.split()):\n # For a new character in pattern\n if c not in match: \n # If word has already been assigned to a character, return false\n if word in list(match.values()): return False\n \n # else assign the word to the character\n match[c] = word\n \n # Match the word with the one assigned to the character\n if match[c] != word: return False\n \n return True\n", "def word_pattern(pattern, string):\n \n words = string.split(' ')\n \n if len(words) != len(pattern):\n return False\n \n map, used = {}, set()\n \n for i, p in enumerate(pattern):\n \n w = words[i]\n\n if p not in map and w not in used:\n map[p] = w\n used.add(w)\n \n if map.get(p, None) != w:\n return False\n\n return True", "def word_pattern(pattern, s):\n s = s.split()\n return len(set(zip(pattern, s))) == len(set(pattern)) == len(set(s)) and len(s) == len(pattern)", "def word_pattern(pattern,string):\n print((pattern,string))\n string = string.split(' ')\n m = len(string); x = {}\n if m!=len(pattern) or len(set(pattern))!=len(set(string)):\n return False\n for k, s in zip(pattern,string):\n if k in x and s!=x[k]: return False\n x[k] = s\n return True\n", "def word_pattern(pattern, string):\n words = string.split(\" \")\n return len(pattern) == len(words) and len(set(zip(pattern, words))) == len(set(pattern)) == len(set(words))", "def word_pattern(p, s):\n if len(p) != len(s.split()): return False\n ss = set([(p[i], c) for i, c in enumerate(s.split())])\n return len(ss) == len(set(p)) == len(set(s.split()))\n", "from collections import OrderedDict\n\n\ndef get_pattern(iterable):\n unique_ordered = list(OrderedDict.fromkeys(iterable))\n return tuple(unique_ordered.index(a) for a in iterable)\n\n\ndef word_pattern(pattern, string):\n return get_pattern(pattern) == get_pattern(string.split())\n"] | {"fn_name": "word_pattern", "inputs": [["abab", "apple banana apple banana"], ["abba", "car truck truck car"], ["abab", "apple banana banana apple"], ["aaaa", "cat cat cat cat"], ["aaaa", "cat cat dog cat"], ["bbbabcb", "c# c# c# javascript c# python c#"], ["abcdef", "apple banana cat donkey elephant flower"], ["xyzzyx", "apple banana apple banana"], ["xyzzyx", "1 2 3 3 2 1"], ["aafggiilp", "cow cow fly pig pig sheep sheep chicken aardvark"], ["aafggiilp", "cow cow fly rooster pig sheep sheep chicken aardvark"], ["aaaa", "cat cat cat"], ["abba", "dog dog dog dog"]], "outputs": [[true], [true], [false], [true], [false], [true], [true], [false], [true], [true], [false], [false], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,548 |
def word_pattern(pattern, string):
|
520080925824b156b37434f551f55c8e | UNKNOWN | Wilson primes satisfy the following condition.
Let ```P``` represent a prime number.
Then ```((P-1)! + 1) / (P * P)``` should give a whole number.
Your task is to create a function that returns ```true``` if the given number is a Wilson prime. | ["def am_i_wilson(n):\n return n in (5, 13, 563)", "def am_i_wilson(n):\n #Piece of shit instead of code for piece of shit instead of instructions. \n #It is really hard to imagine even worse exercise than this for 8 kyu.\n #Extreamly outdated for 2019 it no longer has place in here. \n return True if n == 5 or n == 13 or n == 563 else False\n \n \n \n \n \n \n \n \n", "import math\ndef am_i_wilson(n):\n return n == 5 or n == 13 or n == 563", "import math\ndef am_i_wilson(n):\n return n in [5, 13, 563]", "def am_i_wilson(n):\n all_known_wilson_primes = (5, 13, 563)\n return n in all_known_wilson_primes", "\"\"\"from math import factorial, sqrt\n\ndef prime(n):\n if n % 2 == 0 and n > 2: \n return False\n return all(n % i for i in range(3, int(sqrt(n)) + 1, 2))\n\ndef am_i_wilson(n):\n if not prime(n):\n return False\n elif:\n n == 0:\n return False\n else:\n square = n ** 2\n val = (factorial(n) + 1) / square\n if val > 0:\n return True\n else:\n return False\n\"\"\"\n\ndef am_i_wilson(n):\n return n in [5, 13, 563]", "# this is not 8 kyu, not programming, not even math.\n# this is 'google it, then hardcode it'.\n# leave this to neural nets, don't solve it in a browser.\ndef am_i_wilson(n):\n return n in [5, 13, 563]", "def am_i_wilson(n):\n return n in [5,13,563]", "import math\ndef am_i_wilson(P):\n if P<2:\n return False\n else: \n for x in range(2,P):\n if P%x==0:\n return False\n if ((math.factorial(P-1))+1)%(P*P)==0:\n return True\n else:\n return False", "def am_i_wilson(p): \n if p in {5, 13, 563}: return True\n else: return False", "def am_i_wilson(n):\n wp = [5,13,563]\n if n in wp:\n return True\n else:\n return False", "from math import factorial\ndef am_i_wilson(n):\n if n == 5 or n == 13 or n == 563:\n return True\n else:\n return False", "def am_i_wilson(n):\n if n in (5,13,563):\n return True\n else:\n return False", "from math import factorial\n\ndef am_i_wilson(n):\n return n in [5,13,563]", "am_i_wilson=lambda n: n==5 or n==13 or n==563\n", "def am_i_wilson(n):\n if n == 5:\n return True\n if n == 13:\n return True\n if n == 563:\n return True\n return False", "from math import factorial\n\ndef am_i_wilson(n: int):\n \"\"\" Check if given number is a wilson prime. \"\"\"\n if 563 >= n > 1:\n return not (factorial(n - 1) + 1) % pow(n, 2)\n return False", "am_i_wilson = (5, 13, 563).__contains__", "x = [0, 1, 0, 1, 0, 0, 0, 1, 0, 0]\ndef am_i_wilson(n):\n #your code here\n return x.pop() if x else 1 if n == 5 else 0", "def am_i_wilson(n):\n print(n)\n if prime(n)==False: return False\n elif prime(n)==True:\n if n==5 or n==13 or n==563: return True\n else: return False\n\n \ndef prime(num):\n if num%2==0 or num==1: return False\n \n for i in range(1,int(num**0.5)+2):\n if num%i==0 and i!=1:\n return False\n return True\n\n", "import math\ndef am_i_wilson(n):\n return n in [5, 13, 563, 5971, 558771, 1964215, 8121909, 12326713, 23025711, 26921605, 341569806, 399292158]", "def am_i_wilson(n):\n try:\n return (factorial(n - 1) + 1) % (n * n) == 0 if n != 1 else False\n except:\n return False\n \ndef factorial(n):\n if n <= 1:\n return 1\n else:\n return n * factorial(n - 1)", "def am_i_wilson(n):\n if n == 5 or n == 13 or n==563:\n return True\n elif n != 5 or n!= 13 or n!=563:\n return False", "import math\n\ndef am_i_wilson(n):\n return (math.factorial(n-1) + 1) % (n**2) == 0 if n > 1 and n < 100000 else False", "\ndef am_i_wilson(n):\n if n == 5 or n == 563 or n == 13:\n return True \n else:\n return False", "import math\ndef am_i_wilson(n):\n if n == 5 or n == 563 or n == 13 :\n return True\n return False", "def factorial(n):\n product = 1\n for i in range(2, n + 1):\n product *= i\n return product\n\ndef is_prime(n):\n count = 2\n\n for i in range(2, n // 2 + 1):\n if n % i == 0:\n count += 1\n return count == 2\n\ndef am_i_wilson(n):\n if n <= 1 or n > 563:\n return False\n\n return is_prime(n) and (factorial(n - 1) + 1) % (n * n) == 0", "def am_i_wilson(num):\n return True if num in [5, 13, 563] else False\n", "def am_i_wilson(z):\n return z in (5, 13, 563)", "import math\ndef am_i_wilson(n):\n return (n == 5) or (n == 13) or (n == 563)\n \n #would have used the following code, but the factorials become to large a number and it times out\n #print(n)\n #if n > 1:\n # if ((math.factorial(n-1)) + 1) / (n * n) % 1 == 0:\n # return(True)\n # else:\n # return(False)\n #else:\n # return(False)\n", "def am_i_wilson(n):\n return (n==13 or n== 5 or n == 563)\n #your code here\n", "def am_i_wilson(n):\n return n == 5 or n == 13 or n == 563\n f = 1\n for i in range(2, n+1):\n f *= i\n return False if n == 0 else not (f / (n * n) % 1).is_integer()\n", "#import math\ndef am_i_wilson(n):\n #Execution Timed Out\n #if n == 1 or n == 0:\n #return False\n #try:\n #my_fact = math.factorial(n-1)\n #res = ((my_fact) + 1) / n\n \n #if res == int(res):\n #return True\n #else:\n #return False\n #except:\n #return False\n\n return True if n == 5 or n == 13 or n ==563 else False", "from math import factorial\ndef am_i_wilson(n):\n# print(n)\n if n<=2: return False\n if n>999: return False\n bob = (factorial(n-1) +1)\n if bob//(n*n)*(n*n) == bob: return True\n return False\n", "def am_i_wilson(n):\n return True if n==5 else True if n==13 else True if n==563 else False", "\ndef am_i_wilson(n):\n L = [5,13,563]\n return n in L", "import math\n\ndef am_i_wilson(n):\n if n<2 or n%2==0 : return False\n for x in range(3,int(n**0.5)+1,2):\n if n%x==0 : return False\n return (math.factorial(n-1)+1)%(n**2)==0", "import math\ndef am_i_wilson(num):\n if num < 2 or num > 563 or not all(num % i for i in range(2, num)):\n return False\n return (math.factorial(num - 1) + 1) % (num ** 2) == 0", "def am_i_wilson(n):\n return n in [563,13,5]", "def am_i_wilson(n):\n x = [5, 13, 563, 5971, 558771, 1964215, 8121909, 12326713, 23025711, 26921605, 341569806, 399292158]\n return n in x", "def am_i_wilson(n):\n return not(n<=1) and ((n == 5) or (n == 13) or (n == 563))", "import math\ndef am_i_wilson(n):\n \n if type(n) != int:\n return False\n \n if n == 0 or n == 1 or n == 2:\n return False\n \n for i in range(2,n): \n if (n % i) == 0: \n return False\n \n return (math.factorial((n-1)) + 1) % (n * n) == 0\n \n", "am_i_wilson = lambda n: n in [5, 13, 10429, 17, 563]\n \n", "from math import factorial\n\ndef am_i_wilson(n):\n #your code here\n return True if n > 1 and n < 1000 and (factorial((n-1)) + 1) % n**2 == 0 else False", "import math\ndef am_i_wilson(n):\n if n < 2 or not all(n % i for i in range(2, n)):\n return False\n return (math.factorial(n - 1) + 1) % (n ** 2) == 0", "def am_i_wilson(n):\n return n in (13, 5, 563)", "from math import factorial\n\n\ndef am_i_wilson(n):\n if n < 20000000000000:\n return n in (5, 13, 563)\n return ((factorial(n - 1) + 1) / (n ** 2)).is_integer()\n", "from operator import contains\nfrom functools import partial\n\nL = {5,13,103,563,329891,36846277}\n\nam_i_wilson = partial(contains, L)", "def am_i_wilson(n):\n return n in (5, 13, 563)\n\n# def am_i_wilson(n):\n# #Piece of shit instead of code for piece of shit instead of instructions. \n# #It is really hard to imagine even worse exercise than this for 8 kyu.\n# #Extreamly outdated for 2019 it no longer has place in here. \n# return True if n == 5 or n == 13 or n == 563 else False\n\n# def am_i_wilson(n):\n# if n < 2 or not all(n % i for i in range(2, n)):\n# return False\n \n# import math\n# return (math.factorial(n - 1) + 1) % (n ** 2) == 0\n", "from math import factorial as f\n\ndef is_prime(n):\n sqrt = int(n ** 0.5) + 1\n for i in range(2, sqrt):\n if n % i == 0:\n return False\n return True\n \ndef am_i_wilson(n):\n if n <= 1:\n return False\n if not is_prime(n):\n return False\n return (f(n-1) + 1) % (n*n) == 0", "def factorial(n):\n return -1 if n < 0 else 1 if n == 0 else n * factorial(n - 1)\n\ndef am_i_wilson(n):\n if n < 2:\n return False\n elif n in [5, 13, 563]:\n return True\n else:\n return False\n #f = (factorial(n - 1) + 1) / (n * n)\n return str(n)", "def am_i_wilson(n):\n print(n)\n return n == 5 or n == 13 or n == 563\n# print(n)\n# if n == 0:\n# return False\n# fct = 1\n# for i in range(1, n):\n# fct = fct * i\n# P = (fct+1) / (n*n)\n# return P == 1.0\n", "def am_i_wilson(n):\n primes = [ 5, 13, 563, 5971]\n return n in primes", "from math import sqrt, factorial\n\ndef am_i_wilson(n):\n return False if n <= 1 else is_prime(n) and (factorial(n - 1) + 1) % (n * n) == 0\n\ndef is_prime(n):\n return len([x for x in range(2, int(sqrt(n)) + 1) if n % x == 0]) == 0", "def am_i_wilson(n):\n x=[5,13,563]\n if n in x:\n return True\n else:\n return False", "def am_i_wilson(P):\n #https://en.wikipedia.org/wiki/Wilson_prime\n if P == 5 or P == 13 or P == 563:\n return True\n else:\n return False\n", "def am_i_wilson(n):\n if n != 5:\n if n != 13:\n if n != 563:\n return False\n else: \n return True\n else:\n return True\n else:\n return True", "import math\ndef am_i_wilson(n):\n if n < 2 or n > 563:\n return False\n return (math.factorial(n-1)+1)%(n**2) == 0", "def fact(num):\n if num == 0:\n return 1\n return num * fact(num-1)\n \ndef am_i_wilson(n):\n print(n)\n if n <= 1:\n wp = 1 \n elif n > 999:\n wp=1\n else:\n #print(fact(n-1))\n wp = ((fact(n-1) + 1) % (n*n))\n return True if wp == 0 else False\n \n", "def am_i_wilson(n):\n a = [5, 13, 563]\n if n in a:\n return True\n else:\n return False", "import math\ndef am_i_wilson(n):\n return True if n in [5,13,563] else False\n #sorry\n", "def am_i_wilson(n): return n==5 or n==13 or n==563 # this kata should be retired.", "# from functools import reduce\n\n\ndef am_i_wilson(n):\n\n # print(((reduce(lambda a, b: a * b, list(range(1, n))) + 1) %\n # (n ** 2)) == 0 if n > 2 else False)\n\n # This is the only way to do this kata, else it will say Timeout error LoL\n\n return(n in [5, 13, 563])", "from functools import lru_cache\nimport sys\n\nsys.setrecursionlimit(10000)\n\n@lru_cache(None)\ndef factorial_cache(n):\n if n == 0:\n return 1\n return n * factorial_cache(n - 1)\n\n\ndef is_prime(n):\n if n < 2:\n return False\n for i in range(2, int(n ** 0.5) + 1):\n if n % i == 0:\n return False\n return True\n\ndef am_i_wilson(n):\n print(n)\n try:\n return n > 0 and is_prime(n) and (factorial_cache(n - 1) + 1) % (n * n) == 0\n except:\n return False", "import math \ndef am_i_wilson(num):\n if num < 2 or not all(num % i for i in range(2, num)):\n return False\n return (math.factorial(num - 1) + 1) % (num ** 2) == 0", "# import math\n# def am_i_wilson(n):\n# n1 = math.ceil(math.sqrt(n))\n# c = 0\n# if n <= 1:\n# return False\n# for i in range(2, n1 + 1):\n# if n%i == 0:\n# c+= 1\n# if c != 0:\n# return False\n# x = (math.factorial(n-1)+1)/((n**2))\n\n# return x.is_integer()\n\n\n# import math\n\n# def am_i_wilson(n):\n# if n <= 2:\n# return False\n# fact=math.factorial(n-1) \n# if (fact+1)%n==0:\n# if (fact+1)%(n**2)==0:\n# return True\n# return False\n# return False\n \ndef am_i_wilson(n): \n return n in (5, 13, 563)", "import math\ndef am_i_wilson(n):\n s = [5,13,563]\n for i in range(3):\n if n == s[i]:\n return True\n return False\n \n", "def am_i_wilson(n):\n return n in [5,13,563]\n if n<2: return False\n p=1\n print (n)\n for i in range(1,n):\n p*=i\n \n return (p+1)%(n*n)==0", "def am_i_wilson(n):\n\n primes = [5,13,563]\n return n in primes", "def am_i_wilson(n):\n known_wilson_primes = [ 5, 13, 563]\n return n in known_wilson_primes", "def am_i_wilson(P):\n return P in (5, 13, 563)\n # not by my zelf, just copy for one more punt.....\n", "def am_i_wilson(n): ### This is idiotic... \n if n in [5, 13, 563]:\n return True\n else:\n return False\n\"\"\"\ndef is_prime(n):\n if n % 2 == 0 and n > 2: \n return False\n for i in range(3, int(n**0.5) + 1, 2):\n if n % i == 0:\n return False\n return True \n\ndef fac(n):\n count = 1\n for each in range(1, n + 1):\n print(count)\n count *= each\n return count\n\ndef am_i_wilson(n):\n print(n)\n if n in (0,1):\n return False\n if is_prime(n):\n tmp = (fac(n-1)+1)/(n**2)\n if tmp == int(tmp):\n return True\n else:\n return False \n\"\"\"", "# from math import factorial\ndef am_i_wilson(n):\n return n in (5,13,563)\n# return (factorial(n-1) + 1) % (n * n) == 0 if n > 1 else False\n", "'''import math\ndef am_i_wilson(n):\n if n > 0:\n x = (math.factorial(n - 1) + 1) / (n**2)\n return True if x == int(x) else False\n else: return False'''\n \ndef am_i_wilson(n):\n return True if n in (5, 13, 563) else False", "def am_i_wilson(n):\n wilson_primes = [5, 13, 563, 5971, 558771, 1964215, 8121909, \n 12326713, 23025711, 26921605, 341569806, 399292158]\n return n in wilson_primes", "from math import factorial as fact\ndef am_i_wilson(p):\n return True if p in [5,13,563] else False", "import math\n\ndef am_i_wilson(n):\n # https://yanzhan.site/codewars/wilson-primes.html\n return n == 5 or n == 13 or n == 563", "import math\ndef am_i_wilson(num):\n if num==5 or num==13 or num==563:\n return True\n else:\n return False", "from math import log\ndef am_i_wilson(n):\n return 5==n or 13==n or 563==n\n # next wilson prime somewhere above 10**13, let's say close to 10**63\n", "def am_i_wilson(n):\n wilson_primes = [5, 13, 563]\n return n in wilson_primes\n", "def am_i_wilson(P):\n return P == 5 or P == 13 or P == 563", "from math import factorial, ceil, sqrt\nfrom functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef is_prime(n):\n if n < 2:\n return False\n if n == 2:\n return True\n\n for x in range(2, ceil(sqrt(n))):\n if n % x == 0:\n return False\n return True\n\n@lru_cache(maxsize=None)\ndef fact(n):\n return factorial(n)\n\n\ndef am_i_wilson(P):\n if not is_prime(P):\n return False\n\n if P - 1 <= 0:\n return False\n try:\n x = (fact(P-1) + 1) % (P * P) == 0\n return x\n except OverflowError:\n return False", "import math, sys\ndef am_i_wilson(n):\n return n in (5, 13, 563)\n", "#import math\n#from decimal import *\ndef am_i_wilson(n):\n #if n > 1:\n # return (Decimal(math.factorial(n-1) + 1) / n**2) % 1 == 0\n #else: return False\n \n return n in [5,13,563]", "def am_i_wilson(n):\n a = 1\n if n == 0 or n == 1 or n > 1000:\n return False\n \n for i in range(1, n):\n a *= i\n\n return True if (a + 1) % (n * n) == 0 else False\n", "def am_i_wilson(n):\n if n==5 or n==13 or n==563:\n return True\n else:\n return False\n '''\n if n <= 2:\n return False\n fact=math.factorial(n-1)\n if (fact+1)%n==0:\n x = (fact+1)%(n**2)\n if x==0:\n return True\n else:\n return False\n else:\n return False\n '''", "import sys\nsys.float_info.max\nimport math\n#sys.setrecursionlimit(n)\n\ndef am_i_wilson(n):\n #sys.setrecursionlimit(100000)\n print(n)\n if n <= 1: return False\n if n > 1000:\n if n%2==0: #even\n return False\n else: # odd\n return False\n\n def factorial(a):\n if a<=1: return 1\n else: return a*factorial(a-1)\n result = 1\n for i in range(2,a+1):\n result*=i\n return result\n print('got here')\n \n num = ( math.factorial(n-1) + 1) % (n*n)\n return num == 0", "def am_i_wilson(n):\n #your code here\n if n == 5 or n==13 or n==563:\n return True\n else:\n return False \n #5, 13, and 563\n", "import sys\n\ndef am_i_wilson(n):\n if n in [5,13,563]:\n return True\n else:\n return False\n", "from math import factorial as f\n\ndef am_i_wilson(n):\n print(n)\n if n in [5,13,563]: return True \n else: return False", "am_i_wilson = lambda n: n in (5, 13, 563)\n\n#def am_i_wilson(n):\n# if n < 2:\n# return False\n# elif n == 2:\n# return True\n# else:\n# if n%2 != 0:\n# for i in range(3,int(n**0.5)+1,2): # only odd numbers\n# if n%i==0:\n# return False\n# print (n)\n# print (\"not feck\")\n# return True\n# else:\n# for i in range(2,n):\n# if n%i==0:\n# print (n)\n# print (\"feck\")\n# return False\n# print (n)\n# print (\"not feck\")\n# return True\n", "def is_prime(n):\n a = ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,\n 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139,\n 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227,\n 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311,\n 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401,\n 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491,\n 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599,\n 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683,\n 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797,\n 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887,\n 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997)\n if n in a:\n return True\n return False\nimport math\ndef am_i_wilson(n):\n if n == 563:\n return True\n if is_prime(n):\n a = math.factorial(n - 1)\n try:\n c = (a + 1) / (n * n)\n if int(c) == 0:\n return False\n b = math.ceil((a + 1) / (n * n))\n xx = str(c).split(\".\")\n if xx[1] != '0':\n return False\n if (int(c)) == (int(b)):\n return True\n return False\n except TypeError:\n return False\n except OverflowError:\n return False\n return False", "import math\ndef am_i_wilson(n):\n wilson_primes = [5,13,563]\n return True if n in wilson_primes else False\n \n", "from math import factorial\ndef am_i_wilson(n):\n if n in (5, 13, 563):\n return True\n return False", "from math import factorial\n\ndef am_i_wilson(n):\n if n > 1 and n < 1000 and (factorial(n - 1) + 1) % (n ** 2) == 0:\n return True\n else:\n return False\n", "# from math import sqrt, ceil\n\n# def is_prime(n):\n# if n <= 1:\n# return False\n# else:\n# for i in range(2, ceil(sqrt(n)) + 1):\n# if n % i == 0:\n# return False\n# return True\n\n# def fact(x):\n# fact = 1\n# for i in range(1, x + 1):\n# fact *= i\n# return fact\n\ndef am_i_wilson(n):\n# if not is_prime(n):\n# return False\n# else:\n# return fact(n - 1) == -1 % (n * n)\n return n in [5, 13, 563, 5971, 558771, 1964215, 8121909, 12326713, 23025711, 26921605, 341569806, 399292158]\n \n"] | {"fn_name": "am_i_wilson", "inputs": [[0], [1], [5], [8], [9], [11], [13], [101], [563], [569]], "outputs": [[false], [false], [true], [false], [false], [false], [true], [false], [true], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 20,797 |
def am_i_wilson(n):
|
c9aebf2d29ce6e839877d2b5c1f47b6b | UNKNOWN | You're a programmer in a SEO company. The SEO specialist of your company gets the list of all project keywords everyday, then he looks for the longest keys to analyze them.
You will get the list with keywords and must write a simple function that returns the biggest search keywords and sorts them in lexicographical order.
For instance you might get:
```python
'key1', 'key2', 'key3', 'key n', 'bigkey2', 'bigkey1'
```
And your function should return:
```python
"'bigkey1', 'bigkey2'"
```
Don't forget to rate this kata! Thanks :) | ["def the_biggest_search_keys(*keys):\n L = sorted(keys, key=lambda key: (-len(key), key))\n i = next((i for i,key in enumerate(L) if len(key) != len(L[0])), None)\n return str(L[:i])[1:-1] or \"''\"", "def the_biggest_search_keys(*arg):\n mx = len(max(arg, key=len, default = ''))\n return \", \".join(sorted( f\"'{e}'\" for e in list(arg)+[''] if len(e) == mx))", "def the_biggest_search_keys(*keys):\n if not keys:\n return \"''\"\n n = max(map(len, keys))\n keys = sorted([key for key in keys if len(key) == n])\n return ', '.join(f\"'{key}'\" for key in keys)", "def the_biggest_search_keys(*keys):\n m = max(map(len, keys)) if keys else None\n return str( sorted( filter(lambda x: len(x) == m, keys) ) )[1:-1] if keys else \"''\"", "def the_biggest_search_keys(*keys):\n if not keys: keys = ['']\n longest_key_length = max(map(len, keys))\n return ', '.join(sorted(\"'%s'\" % key for key in keys if len(key) == longest_key_length))", "def the_biggest_search_keys(*args):\n by_len = {}\n fmt = \"'{}'\".format\n for a in args:\n by_len.setdefault(len(a), []).append(a)\n try:\n return ', '.join(fmt(b) for b in sorted(by_len[max(by_len)]))\n except ValueError:\n return \"''\"\n", "def the_biggest_search_keys(*keys):\n biggest, max_len = [], 0\n for key in keys:\n key_len = len(key)\n if key_len == max_len:\n biggest.append(key)\n elif key_len > max_len:\n biggest, max_len = [key], key_len\n return ', '.join(\"'{}'\".format(key) for key in sorted(biggest)) or \"''\"\n", "def the_biggest_search_keys(*keys):\n if not keys:\n return \"''\"\n \n max_len = 0\n \n for key in keys:\n key_len = len(key)\n \n if key_len > max_len:\n max_len = key_len\n result = [key]\n \n elif key_len == max_len:\n result += [key]\n \n return str( sorted(result) )[1:-1]", "def the_biggest_search_keys(*args):\n maxLen = max(map(len, args), default=None)\n return \"''\" if not args else \", \".join(sorted(filter(lambda s: len(s)-2 == maxLen, map(lambda s: \"'{}'\".format(s), args))))", "def the_biggest_search_keys(*keywords):\n return ', '.join(sorted(f\"'{x}'\" for x in keywords if len(x) == max(map(len, keywords)))) if keywords else \"''\""] | {"fn_name": "the_biggest_search_keys", "inputs": [["key1", "key22", "key333"], ["coding", "sorting", "tryruby"], ["small keyword", "how to coding?", "very nice kata", "a lot of keys", "I like Ruby!!!"], ["pippi"]], "outputs": [["'key333'"], ["'sorting', 'tryruby'"], ["'I like Ruby!!!', 'how to coding?', 'very nice kata'"], ["'pippi'"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,379 |
def the_biggest_search_keys(*keys):
|
0c59a8a90ef191464c2fe339967cd80b | UNKNOWN | # Task
Given an initial string `s`, switch case of the minimal possible number of letters to make the whole string written in the upper case or in the lower case.
# Input/Output
`[input]` string `s`
String of odd length consisting of English letters.
3 ≤ inputString.length ≤ 99.
`[output]` a string
The resulting string.
# Example
For `s = "Aba"`, the output should be `"aba"`
For `s = "ABa"`, the output should be `"ABA"` | ["def case_unification(s):\n return s.lower() if sum(1 for i in s if i.islower()) > sum(1 for i in s if i.isupper()) else s.upper()", "def case_unification(s):\n return s.upper() if sum(c.islower() for c in s) < len(s)/2 else s.lower()", "def case_unification(str):\n return str.lower() if sum(1 for ch in str if ch.islower()) > len(str) // 2 else str.upper()", "def case_unification(s):\n return s.upper() if sum(x.isupper() for x in s) / len(s) > 0.5 else s.lower()", "def case_unification(s):\n l = sum(1 if i.isupper() else -1 for i in s)\n return s.lower() if l < 0 else s.upper()", "def case_unification(s):\n return s.upper() if sorted(s)[len(s)//2].isupper() else s.lower()", "def case_unification(s):\n n = sum(c.islower() for c in s)\n return s.lower() if n > len(s) - n else s.upper()\n", "from re import finditer\ndef case_unification(word):\n return word.lower() if len(list(finditer(r'([a-z])', word))) > len(list(finditer(r'([A-Z])', word))) else word.upper()\n", "def case_unification(s):\n lower = sum(c.islower() for c in s)\n upper = len(s) - lower\n func = str.upper if upper > lower else str.lower\n return func(s)"] | {"fn_name": "case_unification", "inputs": [["asdERvT"], ["oyTYbWQ"], ["bbiIRvbcW"], ["rWTmvcoRWEWQQWR"]], "outputs": [["asdervt"], ["OYTYBWQ"], ["bbiirvbcw"], ["RWTMVCORWEWQQWR"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,175 |
def case_unification(s):
|
e41fc68bced8cfb9a94e34f923bc1bdb | UNKNOWN | As part of this Kata, you need to find the length of the sequence in an array, between the first and the second occurrence of a specified number.
For example, for a given array `arr`
[0, -3, 7, 4, 0, 3, 7, 9]
Finding length between two `7`s like
lengthOfSequence([0, -3, 7, 4, 0, 3, 7, 9], 7)
would return `5`.
For sake of simplicity, there will only be numbers (positive or negative) in the supplied array.
If there are less or more than two occurrences of the number to search for, return `0`, or in Haskell, `Nothing`. | ["def length_of_sequence(arr, n):\n if arr.count(n) != 2:\n return 0\n a = arr.index(n)\n b = arr.index(n, a + 1)\n return b - a + 1", "def length_of_sequence(arr,n):\n return (len(arr) - arr[::-1].index(n) - 1) - arr.index(n) + 1 if arr.count(n) == 2 else 0", "def length_of_sequence(arr,n):\n indexes = [i for i,s in enumerate(arr) if s == n]\n if len(indexes) != 2:\n return 0\n else:\n return indexes[-1] - indexes[0] + 1", "def length_of_sequence(arr,n):\n pos = [i for i, x in enumerate(arr) if x == n]\n return pos[1] - pos[0] + 1 if len(pos) == 2 else 0", "def length_of_sequence(arr, n):\n try:\n i = arr.index(n)\n j = arr.index(n, i+1)\n try:\n arr.index(n, j+1)\n return 0\n except ValueError:\n return j - i + 1\n except ValueError:\n return 0", "def length_of_sequence(arr,n):\n indexes = [i for i, x in enumerate(arr) if x == n]\n if len(indexes) != 2:\n return 0\n return indexes[1] - indexes[0] + 1", "def length_of_sequence(arr,n):\n if arr.count(n) != 2:\n return 0\n else:\n return arr.index(n, arr.index(n)+1) - arr.index(n) + 1\n", "def length_of_sequence(arr, n):\n inds = [i for i, v in enumerate(arr) if v == n]\n return inds[1] - inds[0] + 1 if len(inds) == 2 else 0", "def length_of_sequence(arr,n):\n #your code here\n if arr.count(n) != 2:\n return 0\n return (arr[arr.index(n)+1:].index(n) + 2)\n", "def length_of_sequence(arr,n):\n if arr.count(n) != 2:\n return 0\n \n left = arr.index(n)\n right = arr.index(n, left + 1)\n return right - left + 1"] | {"fn_name": "length_of_sequence", "inputs": [[[1], 0], [[1], 1], [[-7, 3, -7, -7, 2, 1], -7], [[-7, 3, -7, -7, 2, -7], -7]], "outputs": [[0], [0], [0], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,682 |
def length_of_sequence(arr,n):
|
1d59b7e96d8e7dd5127afca3c2333f35 | UNKNOWN | # Task
We have a N×N `matrix` (N<10) and a robot.
We wrote in each point of matrix x and y coordinates of a point of matrix.
When robot goes to a point of matrix, reads x and y and transfer to point with x and y coordinates.
For each point in the matrix we want to know if robot returns back to it after `EXACTLY k` moves. So your task is to count points to which Robot returns in `EXACTLY k` moves.
You should stop counting moves as soon as the robot returns to the starting point. That is, if the robot returns to the starting point in fewer than k moves, that point should not count as a valid point.
# example
For:
```
matrix=[
["0,1","0,0","1,2"],
["1,1","1,0","0,2"],
["2,1","2,0","0,0"]]
k= 2
```
The result should be `8`
```
Robot start at (0,0) --> (0,1) --> (0,0), total 2 moves
Robot start at (0,1) --> (0,0) --> (0,1), total 2 moves
Robot start at (0,2) --> (1,2) --> (0,2), total 2 moves
Robot start at (1,2) --> (0,2) --> (1,2), total 2 moves
Robot start at (1,0) --> (1,1) --> (1,0), total 2 moves
Robot start at (1,1) --> (1,0) --> (1,1), total 2 moves
Robot start at (2,0) --> (2,1) --> (2,0), total 2 moves
Robot start at (2,1) --> (2,0) --> (2,1), total 2 moves
Robot start at (2,2) --> (0,0) --> (0,1) --> (0,0) --> (0,1) ....
(Robot can not transfer back to 2,2)
```
So the result is 8.
# Input/Output
- `[input]` 2D integer array matrix
n x n matrix. 3 <= n <=9
- `[input]` integer `k`
`2 <= k <= 5`
- `[output]` an integer | ["def robot_transfer(matrix, k):\n c = 0\n for l, i in enumerate(matrix):\n for o, j in enumerate(i):\n x, y = j.split(\",\")\n current,count,new = [l, o],0,[]\n while count < k and current != new:\n new = [int(x), int(y)] ; x, y = matrix[int(x)][int(y)].split(\",\") ; count += 1\n if current == new and count == k : c += 1\n return c ", "def robot_transfer(matrix, k):\n res, seen = 0, set()\n for i in range(len(matrix)):\n for j in range(len(matrix)):\n if (i, j) in seen: continue\n x, y, S = i, j, {(i, j)}\n for _ in range(k):\n x, y = map(int, matrix[x][y].split(','))\n S.add((x, y))\n if (x, y) == (i, j) and len(S) == k:\n res += k\n seen |= S\n return res", "def f(matrix, k, i, j):\n i0, j0 = i, j\n for n in range(1, k+1):\n i, j = matrix[i][j]\n if i == i0 and j == j0:\n return n == k\n return False\n\ndef robot_transfer(matrix, k):\n matrix = [\n [tuple(map(int, x.split(','))) for x in row]\n for row in matrix\n ]\n return sum(\n f(matrix, k, i, j)\n for i, row in enumerate(matrix)\n for j, x in enumerate(row)\n )", "def robot_transfer(matrix, k):\n result = 0\n for i in range(len(matrix[0])):\n for j in range(len(matrix)):\n x, y, back = i, j, 0\n for _ in range(k):\n x, y = (int(n) for n in matrix[x][y].split(\",\"))\n back += ((i, j) == (x, y))\n result += ((i, j) == (x, y) and back == 1)\n return result\n\n", "def robot_transfer(matrix, k):\n cycles = 0\n for x, l in enumerate(matrix):\n for y, _ in enumerate(l):\n u, v = x, y\n for n in range(k):\n u, v = map(int, matrix[u][v].split(','))\n if (x, y) == (u, v):\n cycles += n == k-1\n break\n return cycles", "def robot_transfer(matrix, k):\n count = 0\n for start_y, row in enumerate(matrix):\n for start_x, point in enumerate(row):\n y, x = int(point[0]), int(point[2])\n for t in range(k-1):\n y, x = int(matrix[y][x][0]), int(matrix[y][x][2])\n if (y, x) == (start_y, start_x):\n count += (t+2 == k)\n break \n return count\n", "def robot_transfer(matrix, k):\n r=0\n n=len(matrix)\n for i in range(n):\n for j in range(n):\n x,y=i,j\n for step in range(k):\n x,y=map(int,matrix[x][y].split(','))\n if x==i and y==j:\n break\n if x==i and y==j and step==k-1:\n r+=1\n return r", "def robot_transfer(matrix, k):\n res = []\n for r, rows in enumerate(matrix):\n for c,point in enumerate(rows):\n kk = 1\n while kk <= k:\n t = list(map(int, point.split(',')))\n print(t)\n point = matrix[t[0]][t[1]]\n kk += 1\n if list(map(int, point.split(','))) == [r, c]: break\n if kk == k and list(map(int, point.split(','))) == [r, c]:\n res.append(1)\n return sum(res)", "def floyd(matrix, row, col):\n def f(row, col):\n return list(map(int, matrix[row][col].split(',')))\n x0 = [row,col]\n tortoise = f(*x0)\n hare = f(*f(*x0))\n while tortoise != hare:\n tortoise = f(*tortoise)\n hare = f(*f(*hare))\n \n mu = 0\n tortoise = x0\n while tortoise != hare:\n tortoise = f(*tortoise)\n hare = f(*hare)\n mu += 1\n \n lam = 1\n hare = f(*tortoise)\n while tortoise != hare:\n hare = f(*hare)\n lam += 1\n \n return lam if mu==0 else -1\n\ndef robot_transfer(matrix, k):\n SIZE = len(matrix)\n return sum(1 for row in range(SIZE) for col in range(SIZE) if floyd(matrix, row, col)==k)\n \n \n", "def robot_transfer(matrix, k):\n N=len(matrix)\n mat=[[0]*N for i in range(N)]\n for i in range(N):\n for j in range(N):\n mat[i][j]=(int(matrix[i][j][0]),int(matrix[i][j][2]))\n tot=0\n for i in range(N):\n for j in range(N):\n y=(i,j)\n for kk in range(k):\n y=mat[y[0]][y[1]]\n if y==(i,j) and kk<k-1: \n break\n if y==(i,j) and kk==k-1: tot+=1\n return tot"] | {"fn_name": "robot_transfer", "inputs": [[[["0,1", "0,0", "1,2"], ["1,1", "1,0", "0,2"], ["2,1", "2,0", "0,0"]], 2], [[["0,1", "0,0"], ["1,1", "1,0"]], 2]], "outputs": [[8], [4]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,570 |
def robot_transfer(matrix, k):
|
2ba9f0b6203f23e2e76225781fcf4df9 | UNKNOWN | You will be given a certain array of length ```n```, such that ```n > 4```, having positive and negative integers but there will be no zeroes and all the elements will occur once in it.
We may obtain an amount of ```n``` sub-arrays of length ```n - 1```, removing one element at a time (from left to right).
For each subarray, let's calculate the product and sum of its elements with the corresponding absolute value of the quotient, ```q = SubProduct/SubSum``` (if it is possible, SubSum cannot be 0).
Then we select the array with the lowest value of ```|q|```(absolute value)
e.g.: we have the array, ```arr = [1, 23, 2, -8, 5]```
```
Sub Arrays SubSum SubProduct |q|
[23, 2, -8, 5] 22 -1840 83.636363
[1, 2, -8, 5] 0 -80 No value
[1, 23, -8, 5] 21 -920 43.809524
[1, 23, 2, 5] 31 230 7.419355 <--- selected array
[1, 23, 2, -8] 18 368 20.444444
```
Let's compare the given array with the selected subarray:
```
[1, 23, 2, -8, 5]
[1, 23, 2, 5]
```
The difference between them is at the index ```3``` for the given array, with element ```-8```, so we put both things for a result ```[3, -8]```.
That means that to obtain the selected subarray we have to take out the value -8 at index 3.
We need a function that receives an array as an argument and outputs the the pair ```[index, arr[index]]``` that generates the subarray with the lowest value of ```|q|```.
```python
select_subarray([1, 23, 2, -8, 5]) == [3, -8]
```
Another case:
```python
select_subarray([1, 3, 23, 4, 2, -8, 5, 18]) == [2, 23]
```
In Javascript the function will be ```selectSubarray()```.
We may have some special arrays that may have more than one solution as the one that follows below.
```python
select_subarray([10, 20, -30, 100, 200]) == [[3, 100], [4, 200]]
```
If there is more than one result the function should output a 2Darray sorted by the index of the element removed from the array.
Thanks to Unnamed for detecting the special cases when we have multiple solutions.
Features of the random tests:
```
Number of tests = 200
length of the array, l, such that 20 <= l <= 100
```
Enjoy it!! | ["from functools import reduce\nfrom operator import mul\n\n\ndef select_subarray(arr):\n total = sum(arr)\n m = reduce(mul, arr)\n qs = [\n (abs((m // x) / (total - x)) if total - x else float(\"inf\"), i)\n for i, x in enumerate(arr)\n ]\n q = min(qs)\n result = [[i, arr[i]] for x, i in qs if x == q[0]]\n return result[0] if len(result) == 1 else result", "from operator import mul \nfrom functools import reduce\ndef select_subarray(array):\n l = []\n for i in array:\n arr = [j for j in array if j != i]\n if sum(arr):\n l.append(((abs(reduce(mul, arr)/float(sum(arr)))), array.index(i), i))\n c = [[j, k] for i, j, k in l if i == sorted(l)[0][0]]\n return c[0] if len(c) == 1 else c\n", "from functools import reduce\nfrom operator import mul\ndef select_subarray(a):\n sub = []\n for i in range(len(a)):\n t = a[:i] + a[i + 1:]\n p = reduce(mul, t)\n s = sum(t)\n if p and s : sub.append([abs(p / s), i, t])\n m = min(sub)[0]\n r = [i[1] for i in sub if i[0] == m]\n result = [[i, a[i]] for i in r]\n return result if len(result)>1 else result[0]", "import numpy as np\n\n\ndef calc_one(value, tot_sum, tot_prod):\n value[value==tot_sum] = np.nan\n return (tot_prod / value) / (tot_sum - value)\n\n\ndef select_subarray(arr):\n np_arr = np.array(arr).astype(np.float64)\n tot_sum = np_arr.sum()\n tot_prod = np_arr.prod()\n qs = np.apply_along_axis(\n calc_one,\n 0,\n np_arr,\n tot_sum,\n tot_prod,\n )\n qs = np.abs(qs)\n min_ = np.nanmin(qs)\n where_min = np.where(qs == min_)[0]\n out = [[where, arr[where]] for where in where_min]\n return out if len(out)>1 else out[0]", "import operator\nfrom functools import reduce\n\ndef min_in_dict(in_dict, original_arr):\n positions = [] # output variable\n min_value = float(\"inf\")\n for key, val in in_dict.items():\n if val == min_value:\n positions.append([original_arr.index(key), key])\n if val < min_value:\n min_value = val\n positions = [] # output variable\n positions.append([original_arr.index(key), key])\n return positions\n\ndef select_subarray(arr):\n q = dict()\n for el in arr:\n temp = arr.copy()\n temp.remove(el)\n if (sum(temp)):\n q[el] = abs(reduce(operator.mul, temp, 1)/sum(temp))\n if (len(min_in_dict(q, arr)) == 1):\n return min_in_dict(q, arr)[0]\n else:\n return min_in_dict(q, arr)", "from functools import reduce\n\ndef select_subarray(arr): \n d = {}\n for i in range(len(arr)):\n x = arr[:i]+arr[i+1:]\n s,p = sum(x),reduce(lambda x,y: x*y,x)\n n = abs(p/s) if s!=0 else float('inf')\n d.setdefault(n,[]).append([i,arr[i]])\n r = d.get(min(d))\n return r.pop() if len(r)==1 else r", "import math\nfrom functools import reduce\nimport operator\n\ndef select_subarray(arr):\n q_vals = []\n for i in range(len(arr)):\n a = arr[:i] + arr[i+1:]\n sum_a = sum(a)\n if sum_a == 0:\n q_vals.append(None)\n else:\n q_vals.append(math.fabs(reduce(operator.mul, a, 1) / sum_a))\n selected = min(filter(lambda x: x is not None, q_vals))\n indexes = [i for i,x in enumerate(q_vals) if x==selected]\n result = []\n for index in indexes:\n result.append([index,arr[index]])\n if len(result)==1:\n return result[0]\n return result", "def select_subarray(arr):\n s = 0\n p = 1\n for x in arr:\n s += x\n p *= x\n result = []\n q = None\n for i,x in enumerate(arr):\n if s!=x:\n new_q = abs((p/x)/(s-x))\n if not result or new_q<q:\n result = [[i, x]]\n q = new_q\n elif new_q == q:\n result.append([i,x])\n \n return result if len(result)>1 else result[0]"] | {"fn_name": "select_subarray", "inputs": [[[1, 23, 2, -8, 5]], [[1, 3, 23, 4, 2, -8, 5, 18]], [[2, -8, 5, 18]], [[10, 20, -30, 100, 200]]], "outputs": [[[3, -8]], [[2, 23]], [[1, -8]], [[[3, 100], [4, 200]]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,016 |
def select_subarray(arr):
|
ded009d4f7bbc00dadb19f69bf6d5a77 | UNKNOWN | ## MTV Cribs is back!

_If you haven't solved it already I recommend trying [this kata](https://www.codewars.com/kata/5834a44e44ff289b5a000075) first._
## Task
Given `n` representing the number of floors build a penthouse like this:
```
___
/___\
/_____\
| _ | 1 floor
|_|_|_|
_____
/_____\
/_______\
/_________\
/___________\
| |
| ___ | 2 floors
| | | |
|___|___|___|
_______
/_______\
/_________\
/___________\
/_____________\
/_______________\
/_________________\
| | 3 floors
| |
| _____ |
| | | |
| | | |
|_____|_____|_____|
```
**Note:** whitespace should be preserved on both sides of the roof. No invalid input tests.
Good luck! | ["def my_crib(n):\n wide = 4 + 3 + 6 * (n - 1)\n door = 2 + n - 1\n roof = 3 + 2 * (n - 1)\n r = '{0}{1}{0}\\n'.format(' ' * (wide // 2 - n), '_' * (3 + 2 * (n - 1)))\n for i in range(1, roof):\n r += '{0}/{1}\\\\{0}\\n'.format(' ' * (wide // 2 - n - i), '_' * (3 + 2 * (n - 1) + 2 * (i -1)))\n for i in range(roof - 1 - door):\n r += '|{}|\\n'.format(' ' * (wide - 2))\n r += '|{0}{1}{0}|\\n'.format(' ' * ((wide - 1) // 3), '_' * (1 + 2 * (n - 1)))\n for i in range(1, door - 1): \n r += '|{0}|{0}|{0}|\\n'.format(' ' * ((wide - 2) // 3))\n return r + '|{0}|{0}|{0}|'.format('_' * ((wide - 2) // 3))\n\n", "def my_crib(n):\n r, ws, wu = ['_' *(2*n + 1)], ' ' * (2*n - 1), '_' * (2*n - 1)\n r += ['/' + '_' *(2*(n + i) + 1) + '\\\\' for i in range(2*n)]\n r += ['|' + ws + ' ' + ws + ' ' + ws + '|' for i in range(n - 1)]\n r += ['|' + ws + ' ' + wu + ' ' + ws + '|']\n r += ['|' + ws + '|' + ws + '|' + ws + '|' for i in range(n - 1)]\n r += ['|' + wu + '|' + wu + '|' + wu + '|']\n return '\\n'.join(l.center(n*6 + 1) for l in r)", "def my_crib(n):\n # n -- integer number greater than one representing the number of floors\n n *= 2\n # Build the house from top to bottom\n # Roof and Ceiling\n mansion = [\"{}{}{}\".format(\" \" * n, \"_\" * (n+1), \" \" * n)]\n mansion.extend(\"{0}/{1}\\\\{0}\".format(\" \" * (n-i-1), \"_\" * (n+1+2*i)) for i in range(n))\n # Walls and Door\n mansion.extend(\"|{}|\".format(\" \" * (3*n-1)) for i in range(n // 2 - 1))\n mansion.append(\"|{0}{1}{0}|\".format(\" \" * n, \"_\" * (n-1)))\n mansion.extend(\"|{0}|{0}|{0}|\".format(\" \" * (n-1)) for i in range(n // 2 - 1))\n # Floor with the Door\n mansion.append(\"|{0}|{0}|{0}|\".format(\"_\" * (n-1)))\n return \"\\n\".join(mansion)\n", "def my_crib(n):\n mult = (2*n) - 1\n top_roof = \"_\" * ((n*2)+1)\n top_roof = top_roof.center((n*6)+1, ' ')\n resulty = ''\n resulty += top_roof + '\\n'\n for i in range(n*2):\n medium_roof = '/' + '_' * int((2*(i + n) + 1)) + '\\\\'\n medium_roof = medium_roof.center((n*6)+1, ' ')\n resulty += medium_roof + '\\n'\n for j in range(n - 1):\n top_house = '|' + ' ' * ((n*6) - 1) + '|'\n resulty += top_house + '\\n'\n upper_door = '|' + ' '*(n*2) + '_'*mult + ' '*(n*2) + '|'\n resulty += upper_door + '\\n'\n for h in range(n - 1):\n medium_house = '|' + ' '*mult + '|' + ' '*mult + '|' + ' '*mult + '|'\n resulty += medium_house + '\\n'\n basement = '|' + '_'*mult + '|' + '_'*mult + '|' + '_'*mult + '|'\n resulty += basement\n return resulty", "def my_crib(n):\n crib = [f\"{mult(n*2)}{mult(n*2+1, '_')}{mult(n*2)}\"]\n crib.extend(f\"{mult(n*2-i-1)}/{mult((n+i)*2+1, '_')}\\\\{mult(n*2-i-1)}\" for i in range(n*2))\n crib.extend(f\"|{mult(n*6-1)}|\" for _ in range(n-1))\n crib.append(f\"|{mult(n*2)}{mult(n*2-1, '_')}{mult(n*2)}|\")\n crib.extend(f\"|{mult(n*2-1)}|{mult(n*2-1)}|{mult(n*2-1)}|\" for _ in range(n-1))\n crib.append(f\"|{mult(n*2-1, '_')}|{mult(n*2-1, '_')}|{mult(n*2-1, '_')}|\")\n return \"\\n\".join(crib)\n\n\ndef mult(n, char=\" \"):\n return char * n", "def my_crib(n):\n \n line = lambda n,l,m,r: f'{ l }{ m*n }{ r }'.center(W)\n topDoor = lambda: f'|{ ( \"_\"*half_1 ).center(W-2) }|'\n door = lambda b: ( b*half_1 ).join('||||')\n \n W, H, half_1 = 6*n+1, 4*n+1, 2*n-1\n \n return '\\n'.join( line(2*(n+i)-1, *('/_\\\\' if i else '___')) if i<=2*n else\n line(W-2, *'| |') if i< 3*n else\n topDoor() if i==3*n else\n door('_' if i==4*n else ' ') for i in range(H) )", "def my_crib(n):\n req, space = 3 + (2 * (n - 1)), 3 + (2 * ((n + (n * 2)) - 1))\n door = (space - 2) - (n * 4)\n roof =[[('_'*req).center(space,' ')] +\n [('/'+'_'*(req+(2*i))+'\\\\').center(space,' ') for i in range(n*2)] + \n ['|'+' '*(space-2)+'|' for i in range(n-1)] +\n ['|'+(' '*n*2)+('_'*door)+(' '*n*2)+'|'] +\n ['|'+' '*(n*2-1)+'|'+' '*door+'|'+' '*(n*2-1)+'|' for i in range(n-1)] + \n ['|'+'_'*(n*2-1)+'|'+'_'*door+'|'+'_'*(n*2-1)+'|']]\n return \"\\n\".join(roof[0])", "def my_crib(n):\n #build roof\n crib_string = ' '*(2*n)+'_'*(2*n+1)+' '*(2*n)+'\\n'\n for i in range(1,2*n+1):\n crib_string += ' '*(2*n-i)+'/'+'_'*(2*n+2*i-1)+'\\\\'+' '*(2*n-i)+'\\n'\n \n #build floors\n for i in range(n-1):\n crib_string += '|'+' '*(6*n-1)+'|\\n'\n crib_string += '|'+' '*(2*n)+'_'*(2*n-1)+' '*(2*n)+'|\\n'\n for i in range(n-1):\n crib_string += '|'+' '*(2*n-1)+'|'+' '*(2*n-1)+'|'+' '*(2*n-1)+'|\\n'\n crib_string += '|'+'_'*(2*n-1)+'|'+'_'*(2*n-1)+'|'+'_'*(2*n-1)+'|'\n \n return(crib_string)", "def my_crib(n):\n temp = []\n temp.append(' '*(2*n) + '_'*(2*n+1) + ' '*(2*n))\n for i in range(2*n):\n strr = '\\n' + (2*n-i-1)*' ' + '/' + (2*n+1 +2*i) * '_' + '\\\\'\n if i!=2*n and i!=2*n-1:\n strr += ' '*(2*n-i-1)\n \n temp.append(strr)\n \n strr2 = '\\n|'+(n*6-1)*' ' + '|'\n temp.append((n-1)*strr2)\n strr3 = '\\n|' + 2*n*' ' + (2*n-1)*'_' + 2*n*' ' + '|'\n temp.append(strr3)\n strr4 = '\\n|' + (2*n-1)*' ' + '|' + (2*n-1)*' '+ '|' + (2*n-1)*' '+'|'\n temp.append((n-1)*strr4)\n temp.append('\\n|')\n strr5 = (2*n-1)*'_'+'|'\n temp.append(3*strr5)\n temp2 = ''.join(temp)\n\n return temp2"] | {"fn_name": "my_crib", "inputs": [[1], [2], [3]], "outputs": [[" ___ \n /___\\ \n/_____\\\n| _ |\n|_|_|_|"], [" _____ \n /_____\\ \n /_______\\ \n /_________\\ \n/___________\\\n| |\n| ___ |\n| | | |\n|___|___|___|"], [" _______ \n /_______\\ \n /_________\\ \n /___________\\ \n /_____________\\ \n /_______________\\ \n/_________________\\\n| |\n| |\n| _____ |\n| | | |\n| | | |\n|_____|_____|_____|"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 5,632 |
def my_crib(n):
|
2ad9e9263dd0c5b3a440b2c34c9892e6 | UNKNOWN | ```if-not:sql
Create a function (or write a script in Shell) that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.
```
```if:sql
## SQL Notes:
You will be given a table, `numbers`, with one column `number`.
Return a table with a column `is_even` containing "Even" or "Odd" depending on `number` column values.
### numbers table schema
* number INT
### output table schema
* is_even STRING
``` | ["def even_or_odd(number):\n return 'Odd' if number % 2 else 'Even'", "def even_or_odd(number):\n return 'Even' if number % 2 == 0 else 'Odd'", "def even_or_odd(number):\n if number % 2 == 0:\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n return [\"Even\", \"Odd\"][number % 2]", "def even_or_odd(number):\n # number % 2 will return 0 for even numbers and 1 for odd ones.\n # 0 evaluates to False and 1 to True, so we can do it with one line\n return \"Odd\" if number % 2 else \"Even\"", "def even_or_odd(number):\n status = \"\"\n if number % 2 == 0:\n status = \"Even\"\n else:\n status = \"Odd\"\n \n return status\n", "def even_or_odd(number):\n return 'Odd' if number & 1 else 'Even'", "def even_or_odd(number):\n if number % 2:\n return \"Odd\"\n return \"Even\"", "even_or_odd = lambda number: \"Odd\" if number % 2 else \"Even\"\n", "def even_or_odd(number):\n if number == 0:\n return \"Even\"\n elif number % 2 == 0:\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n if number%2 == 0: return 'Even'\n return 'Odd'", "def even_or_odd(number):\n return number % 2 and 'Odd' or 'Even'", "even_or_odd=lambda n:'EOvdedn'[n%2::2]", "even_or_odd = lambda n: [\"Even\",\"Odd\"][n % 2]", "def even_or_odd(number):\n even_or_odd = {0: \"Even\", 1: \"Odd\"}\n return even_or_odd[number % 2]", "even_or_odd = lambda i: 'Odd' if i&1 else 'Even'", "even_or_odd = lambda x: \"Even\" if x % 2 == 0 else \"Odd\"", "def even_or_odd(number):\n if(number <0):\n number = -1 * number\n if(number % 2 ==0 or number ==0):\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n if not isinstance(number, int):\n raise Exception('The input is not an integer')\n if number % 2 == 0:\n return 'Even'\n return 'Odd'", "def even_or_odd(x):\n if x % 2 == 0:\n return 'Even'\n else:\n return 'Odd'\n \n", "even_or_odd = lambda number: 'Even' if (number % 2 == 0) else 'Odd'", "even_or_odd = lambda n: \"Odd\" if n % 2 else \"Even\"", "even_or_odd = lambda n: \"Even\" if n%2 == 0 else \"Odd\"\n", "def even_or_odd(n):\n if n % 2 == 0:\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(n):\n return \"Even\" if n%2==0 else \"Odd\"\n", "def even_or_odd(number):\n \"\"\"Returns if number is even or odd\"\"\"\n return 'Even' if number % 2 == 0 else 'Odd'", "even_or_odd=lambda n:('Even','Odd')[n%2]", "def even_or_odd(number):\n return (\"Even\", \"Odd\")[number%2]", "def even_or_odd(number):\n output = [\"Even\", \"Odd\"]\n return output[(number % 2)]", "def even_or_odd(number):\n return('Even','Odd')[number&0x1]", "def even_or_odd(number):\n return ['Even','Odd'][number%2==1]", "def even_or_odd(n):\n return \"Odd\" if n & 1 else \"Even\"", "def even_or_odd(number):\n return [\"Even\",\"Odd\"][float(number) /2 != int(number/2)]", "def even_or_odd(number):\n if number % 2 == 1:\n return \"Odd\"\n else:\n return \"Even\"", "def even_or_odd(number):\n number = str(number)\n even = ['0', '2', '4', '6', '8']\n if number[-1] in even:\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n string = \"\"\n \n #check last bit of number, if 1 number is odd, if 0 number is even\n if (number & (1>>0)):\n string = \"Odd\"\n else: \n string = \"Even\"\n return string", "def even_or_odd(number):\n if number % 2 == 0:\n return\"Even\"\n elif number % 2 == 1:\n return\"Odd\"\n else:\n return\"you are somewhat wrong\"", "def even_or_odd(number):\n test = \"0\"\n if number %2 == 0:\n test=\"Even\"\n else:\n test=\"Odd\"\n return test", "def even_or_odd(value):\n value2 = 2\n result = value % value2\n\n if result == 0:\n result_real = \"Even\"\n else:\n result_real = \"Odd\"\n return result_real", "def even_or_odd(number):\n if number == 0:\n return(\"Even\")\n elif number % 2 == 0:\n return(\"Even\")\n else:\n return(\"Odd\")\n \neven_or_odd(2)\neven_or_odd(0)\neven_or_odd(7)\neven_or_odd(1)\neven_or_odd(-1)", "def even_or_odd(number):\n i = number / 2\n \n if int(i) == float(i):\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n message = \"\"\n if number % 2 == 0:\n message = \"Even\"\n else:\n message = \"Odd\"\n return message", "# takes number\n# returns \"Even\" for even numbers; \"Odd\" for odd numbers\ndef even_or_odd(number):\n return \"Even\" if number % 2 == 0 else \"Odd\"", " \ndef even_or_odd(number):\n if number % 2 == 0:\n return 'Even'\n else:\n return 'Odd'\n\n\ndef even_or_odd(number):\n return \"Even\" if number % 2 == 0 else \"Odd\"\n\n\ndef even_or_odd(number):\n return [\"Even\", \"Odd\"][number % 2]\n\n\n\n\n", "def even_or_odd(number):\n ievade = int(number)\n if ievade % 2 == 0:\n return(\"Even\")\n else:\n return(\"Odd\")\n", "def even_or_odd(number):\n number = 'Odd' if number % 2 else 'Even'\n return number", "def even_or_odd(number):\n modulo = number % 2\n\n if modulo == 1:\n return 'Odd'\n elif modulo == 0:\n return 'Even'", "def even_or_odd(number):\n \n f=number/2\n check = f.is_integer()\n \n if check == True :\n return \"Even\"\n else:\n return \"Odd\"\n", "def even_or_odd(num):\n if (num % 2 != 0):\n return 'Odd'\n else:\n return 'Even'", "def even_or_odd(number):\n divisable = number % 2\n if divisable == 0:\n return 'Even'\n else:\n return 'Odd'", "def even_or_odd(number):\n if not isinstance(number, int):\n print('This is not an integer')\n elif number % 2 == 0:\n return 'Even'\n else:\n return 'Odd'", "def even_or_odd (name):\n a = 'Even'\n b = 'Odd'\n if name % 2 == 0:\n return a\n else:\n return b\neven_or_odd(3)", "def even_or_odd(number=0):\n if number%2==0:\n return \"Even\"\n if number%2!=0:\n return \"Odd\"\n", "def even_or_odd(number):\n assert type(number) == int\n return \"Even\" if number%2 == 0 else \"Odd\"", "def even_or_odd(number):\n # \"Even\" when remainder is 0\n # Otherwise \"Odd\" when remainder is not 0\n if number % 2 == 0:\n return \"Even\"\n return \"Odd\"", "def even_or_odd(number):\n try:\n if number % 2 == 0:\n return('Even')\n elif number % 2 == 1:\n return('Odd')\n except:\n print('error: not a number')", "def even_or_odd(number):\n \"\"\"\n if number mod 2 equal 0 that means number is even\n otherwise its an odd number\n \"\"\"\n if (number%2) == 0:\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n res = number % 2\n if res == 0:\n return \"Even\"\n return \"Odd\"", "def even_or_odd(number):\n if int(number/2) == float(number/2):\n return \"Even\"\n else:\n return \"Odd\"\n\nnum = 10024001232\nprint(even_or_odd(num))", "def even_or_odd(number):\n ans = number % 2 \n if ans == 0 :\n return \"Even\"\n else :\n return \"Odd\"\n", "def even_or_odd(number):\n x= 'Odd'\n y='Even'\n if number % 2 == 0:\n return y\n else:\n return x", "def even_or_odd(number):\n \"\"\"If loop using modulo to return 0 or 1, even or odd\"\"\"\n if number % 2 == 0:\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n ostatok = number % 2\n if ostatok == 0:\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n if number%2 == 1:\n return 'Odd';\n if number%2 == 0:\n return 'Even';\n return\n", "def even_or_odd(number):\n if number % 2 == 0:\n return \"Even\"\n if number % 2 == 1:\n return \"Odd\"\n if number % 2 == -1:\n return \"Odd\"", "def even_or_odd(number):\n if number % 2 == 0:\n return 'Even'\n elif number < 0:\n return 'Odd'\n else:\n return 'Odd'", "def even_or_odd(number):\n return \"Even\" if is_even(number) else \"Odd\"\n\n\ndef is_even(number):\n return True if number % 2 == 0 else False\n", "def even_or_odd(number):\n \n if type(number) == int:\n return \"Even\" if number % 2 == 0 else \"Odd\"\n else:\n return \"Parameter needs to be an integer.\"", "def even_or_odd(number):\n \n if type(number) == int and number % 2 == 0:\n return \"Even\"\n elif type(number) == int and number % 2 != 0:\n return \"Odd\"\n else:\n return \"Parameter needs to be an integer.\"", "def even_or_odd(number):\n if number % 2 == 0:\n return 'Even'\n else:\n return 'Odd'\n \nprint(even_or_odd(153))", "def even_or_odd(number):\n solution = \"Odd\"\n if number % 2 == 0:\n solution = \"Even\"\n return solution\n", "def even_or_odd(number):\n if number % 2 == 0:\n print('This one is Even') \n return('Even')\n else:\n print('This one is Odd') \n return('Odd')\n", "def even_or_odd(n):\n if n%2 == 0 :\n return \"Even\"\n elif n%2 == 1:\n return \"Odd\"\n else:\n return \"Invalid input\"\n\n\na=even_or_odd(5) \nprint(a)", "def even_or_odd(number):\n a = int(number/2)\n if number/2 == a: return \"Even\"\n else: return \"Odd\"", "def even_or_odd(number):\n modresult = number % 2\n if modresult != 0:\n print(\"Odd\")\n return \"Odd\"\n else:\n print(\"Even\")\n return \"Even\"", "def even_or_odd(number):\n if number % 2: #any number above 0 is considered \"True\"\n return \"Odd\" #so you can skip needing to do an equality check\n return \"Even\"\n", "def even_or_odd(number):\n number = number%2\n if number == 0:\n return \"Even\"\n elif number == 1:\n return \"Odd\"", "def even_or_odd(number):\n check = abs(number) % 2\n if(check == 0):\n return(\"Even\")\n else:\n return(\"Odd\")", "def even_or_odd(number):\n if number % 2 == 0:\n return 'Even'\n elif number % 2 != 0:\n return 'Odd'\n else:\n return 'False'", "def even_or_odd(number):\n number>=0\n if number%2==0:\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n if number % 2 == 1:\n number = \"Odd\"\n return number\n else:\n number = \"Even\"\n return number", "def even_or_odd(number):\n \"\"\"Determines if a number is even or odd.\"\"\"\n if number % 2 == 0:\n return \"Even\"\n else:\n return \"Odd\"\n", "def even_or_odd(number): \n #and that's okay!\n if number % 2 == 0:\n #TELL MEEEEE\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n number = int(number)\n if number.__mod__(2) == 0:\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n if number % 2 == 0:\n return \"Even\"\n else:\n return \"Odd\"\n\nnumber = 0\neven_or_odd(number)", "def even_or_odd(number):\n if number % 2 == 0:\n return \"Even\"\n else:\n return \"Odd\"\n#pogchamp\n", "def even_or_odd(number):\n z = number % 2\n if z == 0:\n # print(f\"{number} Even\")\n return('Even')\n else:\n #print(f\"{number} Odd\")\n return('Odd')", "number=int(2)\ndef even_or_odd(number):\n if number%2==0:\n return \"Even\"\n else :\n return \"Odd\"", "def even_or_odd(number):\n if number % 2:\n return('Odd')\n else: \n return('Even')\neven_or_odd(1)", "def even_or_odd(number):\n r = (number) / 2\n if r % 1 :\n return (\"Odd\")\n else : return (\"Even\")", "def even_or_odd(number):\n num=int(number)\n if (num%2==0):\n return \"Even\"\n return \"Odd\"", "def even_or_odd(number):\n if (number % 2) == 0:\n return(\"Even\")\n else:\n return(\"Odd\")\n#He's only gone and done his fifth kata\n", "def even_or_odd(number):\n if number % 2 == 0:\n return \"Even\"\n else:\n return \"Odd\"\n\nx = even_or_odd(-1)\nprint(x)", "def even_or_odd(number: int) -> str:\n \"\"\"Check if number is even or odd. Return 'Even' or 'Odd'\"\"\"\n if type(number) is not int:\n print('Argument must be an integer!')\n else:\n return \"Even\" if number % 2 == 0 else \"Odd\"\n", "def even_or_odd(number):\n if number % 2 == 1:\n return \"Odd\"\n elif number % 2 ==0:\n return \"Even\"\n else:\n return \"Error\"", "def even_or_odd(number):\n if(number % 2) == 0: #check if the remainder of number is 0\n return \"Even\" #if no remainder then return even\n else:\n return \"Odd\" #if there is a remainder, return odd", "def even_or_odd(number):\n if number % 2 == 0 or number == 2 or number == 0:\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n bool = (number % 2 == 0)\n if bool:\n return 'Even'\n return 'Odd'", "def even_or_odd(number):\n num = number\n if num == 0:\n return \"Even\"\n if (num % 2) == 0:\n return \"Even\"\n if (num % 2) != 0:\n return \"Odd\"", "def even_or_odd(number):\n if number % 2 == 0:\n return \"Even\"\n else:\n return \"Odd\"\neven_or_odd(0)\nprint(even_or_odd)\n"] | {"fn_name": "even_or_odd", "inputs": [[2], [1], [0], [1545452], [7], [78], [17], [74156741], [100000], [-123], [-456]], "outputs": [["Even"], ["Odd"], ["Even"], ["Even"], ["Odd"], ["Even"], ["Odd"], ["Odd"], ["Even"], ["Odd"], ["Even"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 13,759 |
def even_or_odd(number):
|
a5be0482a08f5897095378d4c098ce28 | UNKNOWN | Hey CodeWarrior,
we've got a lot to code today!
I hope you know the basic string manipulation methods, because this kata will be all about them.
Here we go...
## Background
We've got a very long string, containing a bunch of User IDs. This string is a listing, which seperates each user ID with a comma and a whitespace ("' "). Sometimes there are more than only one whitespace. Keep this in mind! Futhermore, some user Ids are written only in lowercase, others are mixed lowercase and uppercase characters. Each user ID starts with the same 3 letter "uid", e.g. "uid345edj". But that's not all! Some stupid student edited the string and added some hashtags (#). User IDs containing hashtags are invalid, so these hashtags should be removed!
## Task
1. Remove all hashtags
2. Remove the leading "uid" from each user ID
3. Return an array of strings --> split the string
4. Each user ID should be written in only lowercase characters
5. Remove leading and trailing whitespaces
---
## Note
Even if this kata can be solved by using Regex or Linq, please try to find a solution by using only C#'s string class.
Some references for C#:
- [Microsoft MDSN: Trim](https://msdn.microsoft.com/de-de/library/t97s7bs3%28v=vs.110%29.aspx)
- [Microsoft MSDN: Split](https://msdn.microsoft.com/de-de/library/tabh47cf%28v=vs.110%29.aspx)
- [Microsoft MSDN: ToLower](https://msdn.microsoft.com/en-us/library/system.string.tolower%28v=vs.110%29.aspx)
- [Microsoft MSDN: Replace](https://msdn.microsoft.com/de-de/library/fk49wtc1%28v=vs.110%29.aspx)
- [Microsoft MSDN: Substring](https://msdn.microsoft.com/de-de/library/aka44szs%28v=vs.110%29.aspx) | ["def get_users_ids(string):\n return [w.replace(\"uid\", \"\", 1).strip() for w in string.lower().replace(\"#\", \"\").split(\",\")]", "def get_users_ids(strng):\n result = []\n for a in strng.split(','):\n result.append(a.lower().replace('#', '').replace('uid', '', 1).strip())\n return result", "def get_users_ids(strng):\n return [a.replace('uid', '', 1).strip()\n for a in strng.lower().replace('#', '').split(',')]\n\n", "def get_users_ids(string):\n return [uid.replace(\"uid\", \"\", 1).strip() for uid in string.replace(\"#\", \"\").lower().split(\", \")]", "import re\n\ndef get_users_ids(s):\n s = s.lower().replace('#', '')\n return [re.sub(r'^uid', '', x.strip(), count=1).strip() for x in s.split(',')]", "def get_users_ids(s):\n return [x.strip()[3:].strip() for x in s.replace('#','').lower().split(',')]", "get_users_ids = lambda string: [x.strip()[3:].strip() for x in string.lower().replace('#','').split(', ')]", "get_users_ids=lambda s:[w.strip()[3:].strip()for w in s.replace('#','').lower().split(',')]", "def get_users_ids(string):\n return [word.strip()[3:].strip() for word in string.replace(\"#\",\"\").lower().split(\", \")]", "def get_users_ids(s):\n s = ''.join(i for i in s if i is not '#' or i in ', ' ).lower().strip()\n return [x.replace('uid','',1).strip() for x in s.split(', ')]", "def get_users_ids(s):\n s=s.replace('#', '').lower()\n r = [e.rstrip().strip() for e in s.split(', ')]\n r = [e[3:].strip() if e[:3]=='uid' else e for e in r]\n return r"] | {"fn_name": "get_users_ids", "inputs": [["uid12345"], [" uidabc "], ["#uidswagger"], ["uidone, uidtwo"], ["uidCAPSLOCK"], ["uid##doublehashtag"], [" uidin name whitespace"], ["uidMultipleuid"], ["uid12 ab, uid#, uidMiXeDcHaRs"], [" uidT#e#S#t# "]], "outputs": [[["12345"]], [["abc"]], [["swagger"]], [["one", "two"]], [["capslock"]], [["doublehashtag"]], [["in name whitespace"]], [["multipleuid"]], [["12 ab", "", "mixedchars"]], [["test"]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,556 |
def get_users_ids(s):
|
d8b16c57ce6576ad229129585310e08d | UNKNOWN | Normally, we decompose a number into binary digits by assigning it with powers of 2, with a coefficient of `0` or `1` for each term:
`25 = 1*16 + 1*8 + 0*4 + 0*2 + 1*1`
The choice of `0` and `1` is... not very binary. We shall perform the *true* binary expansion by expanding with powers of 2, but with a coefficient of `1` or `-1` instead:
`25 = 1*16 + 1*8 + 1*4 - 1*2 - 1*1`
Now *this* looks binary.
---
Given any positive number `n`, expand it using the true binary expansion, and return the result as an array, from the most significant digit to the least significant digit.
`true_binary(25) == [1,1,1,-1,-1]`
It should be trivial (the proofs are left as an exercise to the reader) to see that:
- Every odd number has infinitely many true binary expansions
- Every even number has no true binary expansions
Hence, `n` will always be an odd number, and you should return the *least* true binary expansion for any `n`.
Also, note that `n` can be very, very large, so your code should be very efficient. | ["def true_binary(n):\n return [(c == '1') * 2 - 1 for c in '1' + bin(n)[2:-1]]", "def true_binary(n):\n return [-1 if x == '0' else 1 for x in bin(n)[1:-1]]", "def true_binary(n):\n return [1] + [1 if b=='1' else -1 for b in bin(n)[2:-1]]", "def true_binary(n):\n return [1 if d == \"1\" else -1 for d in (f\"1{n>>1:b}\" if n > 1 else \"1\")]\n", "true_binary=lambda n:[1]+[int(c)*2-1 for c in bin(n)[2:-1]]", "import math as m\ndef true_binary(n):\n c = 1\n c = m.ceil(m.log(n,2))\n if c == 0:\n c = 1\n n = (n+(2**c-1))//2\n\n return [(char == '1')*2-1 for char in bin(n)[2:]]", "def true_binary(n):\n temp=bin(n)[2:]\n return [1 if i==\"1\" else -1 for i in temp[-1]+temp[:-1]]", "def true_binary(n):\n temp=bin(n)[2:]\n res=[]\n for i in temp[-1]+temp[:-1]:\n res.append(1) if i==\"1\" else res.append(-1)\n return res", "def true_binary(n):\n suma = \"{:0b}\".format(n)\n ans = [int(suma[0])]\n for i in range(1,len(suma)):\n if suma[i-1] == \"0\": ans.append(-1)\n else: ans.append(1)\n return ans", "import re\ndef true_binary(n):\n s = bin(n)[2:]\n s = re.sub(r'0+1', lambda x: '1' + '0'*(len(x[0])-1), s)\n return [1 if c == '1' else -1 for c in s]"] | {"fn_name": "true_binary", "inputs": [[25], [47], [1], [3], [1234567]], "outputs": [[[1, 1, 1, -1, -1]], [[1, 1, -1, 1, 1, 1]], [[1]], [[1, 1]], [[1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,255 |
def true_binary(n):
|
94ef3d2e1ce8045c4ccc01b206b834af | UNKNOWN | # Task
A newspaper is published in Walrusland. Its heading is `s1` , it consists of lowercase Latin letters.
Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string.
After that walrus erase several letters from this string in order to get a new word `s2`.
It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.
For example, the heading is `"abc"`. If we take two such headings and glue them one to the other one, we get `"abcabc"`. If we erase the 1st letter("a") and 5th letter("b"), we get a word `"bcac"`.
Given two string `s1` and `s2`, return the least number of newspaper headings `s1`, which Fangy will need to receive the word `s2`. If it is impossible to get the word `s2` in the above-described manner, return `-1`.
# Example
For `s1="abc", s2="bcac"`, the output should be `2`.
```
"abcabc" --> "bcac"
x x
```
For `s1="abc", s2="xyz"`, the output should be `-1`.
It's impossible to get the word `s2`. | ["import re\n\n\ndef buy_newspaper(s1, s2):\n p = re.sub(r\"(.)\", r\"\\1?\", s1)\n return -1 if set(s2) - set(s1) else len(re.findall(p, s2)) - 1", "from collections import deque\n\ndef buy_newspaper(s1,s2):\n if set(s2) - set(s1):\n return -1\n q = deque(s1)\n n = 0\n for c in s2:\n i = q.index(c)\n n += i + 1\n q.rotate(-i-1)\n return n // len(s1) + (n % len(s1) > 0)\n", "import re\ndef buy_newspaper(s1, s2):\n if not set(s2) <= set(s1):\n return -1\n regex = ''.join(c + '?' for c in s1)\n return len([match for match in re.findall(regex, s2) if match])", "def buy_newspaper(s1, s2):\n t, i = 0, len(s1)\n for c in s2:\n i = s1.find(c, i) + 1\n if not i:\n t += 1\n i = s1.find(c) + 1\n if not i: return -1\n return t", "def buy_newspaper(s1, s2):\n count, temp = 0, \"\"\n for index, c in enumerate(s2):\n if c not in s1:\n # Required letter not available\n return -1\n \n # Strip incorrect characters until we get the right character or run out of characters to remove\n while index < len(temp) and temp[index] != c:\n temp = temp[:index] + temp[index + 1:]\n \n # Add a new set of characters from the first instance of the required character\n if not temp or index == len(temp):\n temp += s1[s1.find(c):]\n count += 1\n\n return count", "from itertools import cycle\n\ndef buy_newspaper(s1,s2):\n if set(s2)-set(s1): return -1\n c, n = cycle(s1), 0\n for c2 in s2:\n while True:\n n, c1 = n+1, next(c)\n if c1 == c2: break\n return n//len(s1) + (n%len(s1) != 0)", "def buy_newspaper(s1,s2):\n if not all(i in s1 for i in s2):return -1\n copy,i = s1,1\n while True:\n pos = [float('-inf')]\n for k in s2:\n t = next((o for o, p in enumerate(s1) if p == k and o > pos[-1]), -1)\n if t == -1 : break\n pos.append(t)\n else : return i\n s1 += copy ; i += 1", "import re\ndef buy_newspaper(s1,s2):\n m = re.findall(\"\".join((i+\"?\" for i in s1)),s2)[:-1]\n return len(m) if \"\" not in m else -1", "def buy_newspaper(s1,s2):\n if [1 for i in s2 if i not in s1]: return -1\n p=0 \n for i in s2:\n while i!=s1[p%len(s1)]:\n p+=1\n p+=1\n return p//len(s1)+(1 if p%len(s1) else 0)", "def buy_newspaper(s1,s2):\n a = []\n for i in s2:\n try:\n a += [s1.index(i)]\n except:\n return -1\n c = 1\n for i in range(len(a)-1):\n if a[i+1] <= a[i]:\n c += 1\n return c"] | {"fn_name": "buy_newspaper", "inputs": [["abc", "bcac"], ["abc", "xyz"], ["abc", "abcabc"], ["abc", "abccba"], ["abc", "aaaaaa"]], "outputs": [[2], [-1], [2], [4], [6]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,727 |
def buy_newspaper(s1,s2):
|
8af520d79e898d6f8dd3b7b46299b7e9 | UNKNOWN | # Task
Given an integer array `arr`. Your task is to remove one element, maximize the product of elements.
The result is the element which should be removed. If more than one valid results exist, return the smallest one.
# Input/Output
`[input]` integer array `arr`
non-empty unsorted integer array. It contains positive integer, negative integer or zero.
`3 ≤ arr.length ≤ 15`
`-10 ≤ arr[i] ≤ 10`
`[output]` an integer
The element that should be removed.
# Example
For `arr = [1, 2, 3]`, the output should be `1`.
For `arr = [-1, 2, -3]`, the output should be `2`.
For `arr = [-1, -2, -3]`, the output should be `-1`.
For `arr = [-1, -2, -3, -4]`, the output should be `-4`. | ["def maximum_product(arr):\n if arr.count(0) > 1:\n return min(arr)\n neg = [n for n in arr if n < 0]\n pos = [n for n in arr if n >= 0]\n if len(neg) % 2:\n return min(neg) if 0 in arr else max(neg)\n else:\n return min(pos) if pos else min(neg)", "from operator import mul\nfrom functools import reduce\n\ndef maximum_product(arr):\n prod_dct = { x: reduce(mul, arr[:i]+arr[i+1:], 1) for i,x in enumerate(arr)}\n return max(arr, key=lambda x:(prod_dct[x],-x))", "from functools import reduce\nfrom operator import mul\n\ndef maximum_product(arr):\n l = [(reduce(mul, arr[:i] + arr[i+1:]),j) for i,j in enumerate(arr)]\n return max(l, key=lambda x: (x[0], -x[1]))[1]", "import numpy as np\ndef maximum_product(arr):\n return -max((np.multiply.reduce(arr[:c] + arr[c + 1:]), -a) for c, a in enumerate(arr))[1]", "from functools import reduce\nfrom operator import mul\n\ndef maximum_product(arr):\n prods = {}\n \n for e in sorted(set(arr))[::-1]:\n a = arr[:]\n a.remove(e)\n prods[reduce(mul, a)] = e\n \n return prods[max(prods)]", "from functools import reduce\nfrom operator import mul\n\ndef maximum_product(arr):\n omit_prod = lambda i: reduce(mul, arr[:i] + arr[i + 1:])\n return sorted([(omit_prod(i), -n, n) for i, n in enumerate(arr)], reverse=True)[0][2]\n", "def maximum_product(arr):\n pos = [x for x in arr if x > 0]\n neg = [x for x in arr if x < 0]\n if 0 in arr:\n return min(neg) if len(neg) % 2 or (arr.count(0) - 1 and len(neg)) else 0\n if len(neg) % 2: return max(neg)\n return min(pos) if len(pos) else min(neg)", "def maximum_product(arr):\n a = [n for n in arr if n < 0]\n b = [n for n in arr if n > 0]\n if not a:\n return min(arr)\n if len(a) % 2:\n if 0 in arr:\n return min(a)\n return max(a)\n if not len(a) % 2:\n if arr.count(0) == 1:\n return 0\n if arr.count(0) > 1:\n return min(arr)\n if b:\n return min(b)\n if b:\n return max(b)\n return min(arr)"] | {"fn_name": "maximum_product", "inputs": [[[1, 2, 3]], [[-1, 2, -3]], [[-1, -2, -3]], [[-1, -2, -3, -4]], [[0, 1, 2, 3]], [[0, -1, -2, -3]], [[0, -1, -2, -3, -4]], [[0, -1, 2, -3, 4]], [[0, -1, 2, 3]], [[0, -1, -2, -3, 4]], [[0, 0, 1]], [[0, 0, -1]], [[0, -1, 1]], [[0, 0, -1, 1]], [[0, 0, 0]], [[0, 0, 1, 2, 3]], [[-1, -2, -3, 0, 1, 2, 3]], [[-1, -2, 0, 1, 2]], [[-1, -2, 1, 2]], [[-1, -2, -3, 1, 2, 3]]], "outputs": [[1], [2], [-1], [-4], [0], [-3], [0], [0], [-1], [-3], [0], [-1], [-1], [-1], [0], [0], [-3], [0], [1], [-1]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,118 |
def maximum_product(arr):
|
8827be1f9cd8f46be95ca4e9b230bce8 | UNKNOWN | It's been a tough week at work and you are stuggling to get out of bed in the morning.
While waiting at the bus stop you realise that if you could time your arrival to the nearest minute you could get valuable extra minutes in bed.
There is a bus that goes to your office every 15 minute, the first bus is at `06:00`, and the last bus is at `00:00`.
Given that it takes 5 minutes to walk from your front door to the bus stop, implement a function that when given the curent time will tell you much time is left, before you must leave to catch the next bus.
## Examples
```
"05:00" => 55
"10:00" => 10
"12:10" => 0
"12:11" => 14
```
### Notes
1. Return the number of minutes till the next bus
2. Input will be formatted as `HH:MM` (24-hour clock)
3. The input time might be after the buses have stopped running, i.e. after `00:00` | ["def bus_timer(current_time):\n h, m = map(int, current_time.split(':'))\n\n if h<6:\n m = (5 - h) * 60 + 60 - m\n elif h == 23 and m > 55:\n return 355 + 60 - m\n else:\n m = 15 - m % 15\n\n if m > 4:\n return m - 5\n else:\n return m + 10", "def bus_timer(time):\n h,m = map(int,time.split(':'))\n t = (5+h*60+m)%1440\n return -t%(360 if t<360 else 15)", "from datetime import datetime, timedelta\n\ndef bus_timer(current_time):\n \n ct = datetime.strptime(current_time, \"%H:%M\")\n \n if ct >= datetime.strptime(\"5:55\", \"%H:%M\") and ct <= datetime.strptime(\"23:55\", \"%H:%M\"):\n if ct.minute <= 10:\n time_left = 10 - ct.minute\n elif ct.minute <= 25 and ct.minute > 10:\n time_left = 25 - ct.minute\n elif ct.minute <= 40 and ct.minute > 25:\n time_left = 40 - ct.minute\n elif ct.minute <= 55 and ct.minute > 40:\n time_left = 55 - ct.minute\n else:\n time_left = 70 - ct.minute\n else:\n delta = datetime.strptime(\"5:55\", \"%H:%M\") - ct\n time_left = int(delta.seconds / 60)\n \n return time_left", "def bus_timer(current_time):\n h, m = map(int, current_time.split(\":\"))\n current_time = 60 * h + m\n if current_time >= 1436 or current_time <= 355:\n return (355 - current_time) % 1440\n else:\n return (10 - current_time) % 15", "def bus_timer(time):\n c = time.split(\":\")\n z = int(c[1]) + 5\n t = 0\n if int(c[0]) == 23 and int(c[1]) >= 55:\n c[0] = 0\n c[1] = (int(c[1]) + 5) - 60\n if int(c[1]) == 0:\n t = 0\n elif int(c[1]) > 0:\n t = (((5 - int(c[0]))*60) + (60 - int(c[1]))) \n elif int(c[0]) == 5 and int(c[1]) >= 55:\n c[0] = 6\n c[1] = (int(c[1]) + 5) - 60\n if int(c[1]) == 0:\n t = 0\n elif int(c[1]) > 0:\n t = 15 - int(c[1])\n elif int(c[0]) < 6 :\n if int(c[1]) == 0:\n t = ((6 - int(c[0]))*60) - 5\n elif int(c[1]) > 0:\n t = (((5 - int(c[0]))*60) + (60 - int(c[1]))) - 5\n else:\n if z > 60:\n z = z - 60\n if z < 15:\n t = 15 - z\n elif z > 15 and z < 30:\n t = 30 - z\n elif z > 30 and z < 45:\n t = 45 - z\n elif z > 45:\n t = 60 - z\n return t", "def bus_timer(current_time):\n hh,mm = [int(v) for v in current_time.split(':')]\n time = (hh*60+mm+5)%1440\n if time == 0: return 0\n if time <= 360: return 360-time\n return -time % 15\n", "def bus_timer(time):\n hh, mm = time.split(':')\n hh, mm = int(hh), int(mm)\n \n if hh == 23:\n if mm <= 55: return 10 - mm % 15 if mm % 15 <= 10 else 15 - (mm % 15 - 10)\n else: return 5 * 60 + 55 + (60 - mm)\n elif 6 <= hh:\n return 10 - mm % 15 if mm % 15 <= 10 else 15 - (mm % 15 - 10)\n \n return ((5 - hh) * 60) + (55 - mm) if hh < 5 or (hh == 5 and mm <= 55) else 15 - (mm % 15 - 10)\n", "def bus_timer(time):\n print(time)\n hour,mins=map(int,time.split(\":\"))\n mins+=hour*60\n if 0<=mins<355 or mins>1435:return 355-mins+1440*(mins>1435)\n mins=10-mins+((mins//15)*15)\n return mins+15*(mins<0)", "def bus_timer(current_time):\n h, m = list(map(int, current_time.split(':')))\n t = h * 60 + m - 55\n if t < 60 * 5 or t > 23 * 60:\n return (5 + 24 * (h == 23)) * 60 - t\n return min(a - m for a in (10, 25, 40, 55, 70) if a - m >= 0)\n", "def bus_timer(current_time):\n tim = current_time[3:]\n time = int(tim)\n tume = int(current_time[:2])\n if tume == 5 and time > 55:\n return 60 - time + 15 - 5\n elif tume < 6 and tume >= 0:\n return ((6 - tume) * 60) - 5 - time\n \n else:\n if tume == 23 and time > 55:\n return 360 - 5 + 60 - time\n elif time < 15 and time <= 10:\n return 15 - time - 5\n elif time < 30 and time <= 25:\n return 30 - time - 5\n elif time < 45 and time <=40:\n return 45 - time - 5\n elif time < 15 and time > 10:\n return 30 - time - 5\n elif time < 30 and time > 25:\n return 45 - time - 5\n elif time < 45 and time > 40:\n return 60 - time - 5\n elif time < 60 and time > 55:\n return 75 - time - 5\n else:\n return 60 - time - 5\n"] | {"fn_name": "bus_timer", "inputs": [["10:00"], ["10:45"], ["15:05"], ["06:10"], ["05:10"], ["04:50"], ["05:55"], ["23:57"], ["00:00"], ["23:55"]], "outputs": [[10], [10], [5], [0], [45], [65], [0], [358], [355], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,523 |
def bus_timer(current_time):
|
abfd67a38d3278f89a0112b19dc67544 | UNKNOWN | You know combinations: for example,
if you take 5 cards from a 52 cards deck you have 2,598,960 different combinations.
In mathematics the number of x combinations you can take from a set of n elements
is called the binomial coefficient of n and x, or more often `n choose x`.
The formula to compute `m = n choose x` is: `m = n! / (x! * (n - x)!)`
where ! is the factorial operator.
You are a renowned poster designer and painter. You are asked to provide 6 posters
all having the same design each in 2 colors. Posters must all have a different color combination and you have the choice of 4 colors: red, blue, yellow, green.
How many colors can you choose for each poster?
The answer is two since `4 choose 2 = 6`. The combinations will be:
{red, blue}, {red, yellow}, {red, green}, {blue, yellow}, {blue, green}, {yellow, green}.
Now same question but you have 35 posters to provide and 7 colors available. How many colors for each poster?
If you take combinations `7 choose 2` you will get 21 with the above formula.
But 21 schemes aren't enough for 35 posters. If you take `7 choose 5` combinations you will get 21 too.
Fortunately if you take `7 choose 3` or `7 choose 4` combinations you get 35 and so each poster will have a different combination of
3 colors or 5 colors. You will take 3 colors because it's less expensive.
Hence the problem is:
knowing `m` (number of posters to design),
knowing `n` (total number of available colors),
let us
search `x` (number of colors for each poster so that each poster has a unique combination of colors and the number of combinations is exactly the same as the number of posters).
In other words we must find **x** such as `n choose x = m (1)` for a given m and a given n;
`m >= 0 and n > 0`. If many x are solutions give as result the smallest x.
It can happen that when m is given at random there are no x satisfying `equation (1)` then
return -1.
Examples:
```
checkchoose(6, 4) --> 2
checkchoose(4, 4) --> 1
checkchoose(4, 2) --> -1
checkchoose(35, 7) --> 3
checkchoose(36, 7) --> -1
a = 47129212243960
checkchoose(a, 50) --> 20
checkchoose(a + 1, 50) --> -1
``` | ["def checkchoose(m, n):\n c = 1\n for x in range(n // 2 + 1):\n if c == m: return x\n c = c * (n-x) // (x+1)\n else: return -1\n", "from math import factorial\n\ndef choose(n, x):\n return factorial(n) // (factorial(x) * factorial(n-x)) if x else 1\n\ndef checkchoose(m, n):\n for x in range(n+1):\n if choose(n, x) == m:\n return x\n return -1", "from math import factorial as fact\n\ndef checkchoose(m, n):\n for k in range(0, (n)//2 + 1):\n if fact(n) // (fact(n-k) * fact(k)) == m:\n return k\n return -1", "from math import factorial as fact\n\ndef combinations(n, k):\n return fact(n) // (fact(k) * fact(n-k))\n\ndef checkchoose(posters, colors):\n return min([k for k in range(colors//2 +1) if combinations(colors, k) == posters], default=-1)", "def checkchoose(m, n):\n from math import factorial as f\n a = 0\n while a <= n//2:\n if m == f(n) / (f(a)*f(n-a)):\n return(a)\n else:\n a += 1\n return(-1)", "from math import factorial as fact\ndef checkchoose(m, n):\n l = [i for i in range(1, n+1) if fact(n)/(fact(i)*fact(n-i))==m]\n return 0 if m<n else l[0] if l else -1", "def checkchoose(m, n):\n for k in range(n + 1):\n nk = n - k\n ans = partial_fact(n, k) / factorial(nk) if k > nk else partial_fact(n, nk) / factorial(k)\n if m == ans: return k\n if m < ans: return -1 #No need to search the other side of the triangle\n return -1\n\nf = [0, 1, 2, 6, 24, 120]\ndef factorial(n):\n if n == 0 or n == 1: return 1\n if n < len(f): return f[n]\n f.append(factorial(n - 1) * n)\n return f[n]\npartial_fact = lambda hi, le: 1 if hi <= le else hi * partial_fact(hi - 1, le)", "from operator import mul\nfrom functools import reduce\n\ndef choose(n, p):\n if (p > n): \n return 0\n if (p > n - p): \n p = n - p\n return reduce(mul, range((n-p+1), n+1), 1) // reduce( mul, range(1,p+1), 1)\n\ndef checkchoose(m, n):\n mx = choose(n, n // 2)\n if (m > mx): \n return -1\n i = 0\n while (i <= (n // 2) + 1):\n if choose(n, i) == m:\n return i\n i += 1\n return -1"] | {"fn_name": "checkchoose", "inputs": [[1, 6], [6, 4], [4, 4], [4, 2], [35, 7], [36, 7], [184756, 20], [184756, 10], [3268760, 25], [155117520, 30], [155117530, 30]], "outputs": [[0], [2], [1], [-1], [3], [-1], [10], [-1], [10], [15], [-1]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,202 |
def checkchoose(m, n):
|
949d560f3e79fa734474e0a3150c7e44 | UNKNOWN | Goal
Given a list of elements [a1, a2, ..., an], with each ai being a string, write a function **majority** that returns the value that appears the most in the list.
If there's no winner, the function should return None, NULL, nil, etc, based on the programming language.
Example
majority(["A", "B", "A"]) returns "A"
majority(["A", "B", "B", "A"]) returns None | ["from collections import Counter\n\ndef majority(arr):\n mc = Counter(arr).most_common(2)\n if arr and (len(mc) == 1 or mc[0][1] != mc[1][1]):\n return mc[0][0]", "def majority(arr):\n dic = {}\n n = 0\n c = 0\n for x in arr:\n if not x in dic:\n dic[x] = 1\n else:\n dic[x] += 1\n for x in dic:\n n = max(n,dic[x])\n for x in dic: \n if dic[x] == n: \n r = x\n c += 1\n if c==1: \n return r\n else:\n return None", "from collections import Counter\n\ndef majority(arr):\n c = Counter(arr).most_common(2) + [(0,0)]*2\n if c[0][1] != c[1][1]:\n return c[0][0]", "def majority(arr):\n cnt = sorted(([arr.count(i), i] for i in set(arr)), reverse = True)\n if len(cnt) == 1 or (len(cnt)>1 and cnt[0][0] != cnt[1][0]): return(cnt[0][1])\n else: return(None)", "def majority(arr):\n# d = {}\n# l = []\n# for elem in arr:\n# d[elem] = arr.count(elem)\n# for k,v in d.items():\n# if v == max(d.values()):\n# l.append(k)\n# return l[0] if len(l) == 1 else None\n \n d = {elem : arr.count(elem) for elem in arr}\n \n l = [k for k,v in list(d.items()) if v == max(d.values())]\n \n return l[0] if len(l) == 1 else None \n", "from collections import Counter\n\ndef majority(arr):\n m = Counter(arr).most_common(2)\n return None if (len(arr) == 0 or (len(m) == 2 and m[0][1] == m[1][1])) else m[0][0]", "from collections import Counter\n\ndef majority(arr):\n counter = Counter(arr)\n best = counter.most_common(2)\n if not best:\n return None\n elif len(best) == 1 or best[0][1] != best[1][1]:\n return best[0][0]\n", "from collections import Counter\n\ndef majority(arr):\n c = Counter(arr)\n t = c.most_common(2)\n if len(t) == 1 or len(t) > 1 and t[1][1] < t[0][1]:\n return t[0][0]\n return None", "from collections import Counter\n\ndef majority(arr):\n try:\n c = Counter(arr)\n val = list(c.values())\n assert val.count(max(val)) == 1\n return sorted([ (v,k) for k,v in list(c.items()) ], reverse=True)[0][1]\n except:\n return None\n", "from collections import *\ndef majority(arr):\n for k, v in list(Counter(arr).items()):\n if len(Counter(arr)) == 1: return k\n else:\n if v > max([j for i, j in list(Counter(arr).items()) if i != k]):\n return k \n"] | {"fn_name": "majority", "inputs": [[["A", "B", "A"]], [["A", "B", "C"]], [["A", "B", "B", "A"]], [["A", "A", "A", "A"]], [["A"]], [["A", "A", "A", "BBBBBBBB"]], [["A", "B", "C", "C"]], [[]], [["B", "C", "", ""]]], "outputs": [["A"], [null], [null], ["A"], ["A"], ["A"], ["C"], [null], [""]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,449 |
def majority(arr):
|
310542ca9150a39e35af3fa43b0b790c | UNKNOWN | # Task
Some people are standing in a row in a park. There are trees between them which cannot be moved.
Your task is to rearrange the people by their heights in a non-descending order without moving the trees.
# Example
For `a = [-1, 150, 190, 170, -1, -1, 160, 180]`, the output should be
`[-1, 150, 160, 170, -1, -1, 180, 190]`.
# Input/Output
- `[input]` integer array `a`
If a[i] = -1, then the ith position is occupied by a tree. Otherwise a[i] is the height of a person standing in the ith position.
Constraints:
`5 ≤ a.length ≤ 30,`
`-1 ≤ a[i] ≤ 200.`
- `[output]` an integer array
`Sorted` array a with all the trees untouched. | ["def sort_by_height(a):\n s = iter(sorted(x for x in a if x != -1))\n return [x if x == -1 else next(s) for x in a]", "def sort_by_height(arr):\n heights = iter(sorted(i for i in arr if i > 0))\n for idx, i in enumerate(arr):\n if i > 0:\n arr[idx] = next(heights)\n return arr", "def sort_by_height(a):\n people = iter(sorted([i for i in a if i != -1]))\n return [i if i == -1 else next(people) for i in a]", "def sort_by_height(a):\n people = iter(sorted(n for n in a if n != -1))\n return [next(people) if n != -1 else n for n in a]", "def sort_by_height(a):\n filtered = list(sorted(filter(lambda x: x != -1, a), key=lambda x: -x))\n return [-1 if i == -1 else filtered.pop() for i in a]", "def sort_by_height(arr):\n s=sorted(n for n in arr if n!=-1)\n return [n if n==-1 else s.pop(0) for n in arr]", "def sort_by_height(a):\n people = sorted([j for j in a if j != -1])\n for i in range(len(a)):\n if a[i] != -1:\n a[i] = people.pop(0)\n return a\n \n", "def sort_by_height(a):\n it = iter(sorted([x for x in a if x >= 0]))\n return [x if x < 0 else next(it) for x in a]", "def sort_by_height(a):\n list_index = [x for x,i in enumerate(a) if i == -1] \n list_sorted = sorted([i for x,i in enumerate(a) if i != -1]) \n \n for new_item in list_index:\n list_sorted.insert(new_item, -1)\n \n return list_sorted", "def sort_by_height(a):\n h, k = sorted([i for i in a if i!=-1]), []\n for i in a:\n if i!=-1:\n k+=[h[0]]\n h=h[1:]\n else:\n k+=[i]\n return k"] | {"fn_name": "sort_by_height", "inputs": [[[-1, 150, 190, 170, -1, -1, 160, 180]], [[-1, -1, -1, -1, -1]], [[4, 2, 9, 11, 2, 16]]], "outputs": [[[-1, 150, 160, 170, -1, -1, 180, 190]], [[-1, -1, -1, -1, -1]], [[2, 2, 4, 9, 11, 16]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,641 |
def sort_by_height(a):
|
c94be165ff6821ef11a55cc28960bf71 | UNKNOWN | Bob is a theoretical coder - he doesn't write code, but comes up with theories, formulas and algorithm ideas. You are his secretary, and he has tasked you with writing the code for his newest project - a method for making the short form of a word. Write a function ```shortForm```(C# ```ShortForm```, Python ```short_form```) that takes a string and returns it converted into short form using the rule: Remove all vowels, except for those that are the first or last letter. Do not count 'y' as a vowel, and ignore case. Also note, the string given will not have any spaces; only one word, and only Roman letters.
Example:
```
shortForm("assault");
short_form("assault")
ShortForm("assault");
// should return "asslt"
```
Also, FYI: I got all the words with no vowels from
https://en.wikipedia.org/wiki/English_words_without_vowels | ["from re import *\ndef short_form(s):\n return sub(r\"(?<!^)[aeiou](?=.)\", '', s, flags=I)", "import re\n\ndef short_form(s):\n regex = re.compile(\"(?!^)[aeiou](?!$)\", re.I)\n return re.sub(regex, \"\", s)\n", "def short_form(s):\n return s[0]+''.join(x for x in s[1:-1] if x not in 'aeiouAEIOU')+s[-1]", "from re import sub\ndef short_form(s):\n return sub(r\"(?!^)[aeiouAEIOU](?!$)\", '', s)", "from re import compile\nfrom functools import partial\n\nshort_form = partial(compile(r\"(?i)(?<!^)[aeiou](?!$)\").sub, \"\")", "def short_form(s):\n return ''.join(c for i,c in enumerate(s) if c.lower() not in 'aeiou' or (i==0 or i==len(s)-1))", "def short_form(s):\n n = len(s)\n return ''.join(c for i, c in enumerate(s) if c not in 'aeiouAEIOU' or (i == 0 or i == n - 1))", "import re\ndef short_form(s):\n return s[0] + re.sub(r'[aeiou]', '', s[1:-1], flags=re.I) + s[-1]"] | {"fn_name": "short_form", "inputs": [["typhoid"], ["fire"], ["destroy"], ["kata"], ["codewars"], ["assert"], ["insane"], ["nice"], ["amazing"], ["incorrigible"], ["HeEllO"], ["inCRediBLE"], ["IMpOsSiblE"], ["UnInTENtiONAl"], ["AWESOme"], ["rhythm"], ["hymn"], ["lynx"], ["nymph"], ["pygmy"]], "outputs": [["typhd"], ["fre"], ["dstry"], ["kta"], ["cdwrs"], ["assrt"], ["insne"], ["nce"], ["amzng"], ["incrrgble"], ["HllO"], ["inCRdBLE"], ["IMpsSblE"], ["UnnTNtNl"], ["AWSme"], ["rhythm"], ["hymn"], ["lynx"], ["nymph"], ["pygmy"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 906 |
def short_form(s):
|
33f634b90a1a698c67cfd2d1c3a9528a | UNKNOWN | Given a positive number n > 1 find the prime factor decomposition of n.
The result will be a string with the following form :
```
"(p1**n1)(p2**n2)...(pk**nk)"
```
where ```a ** b``` means ```a``` to the power of ```b```
with the p(i) in increasing order and n(i) empty if
n(i) is 1.
```
Example: n = 86240 should return "(2**5)(5)(7**2)(11)"
``` | ["def primeFactors(n):\n ret = ''\n for i in range(2, n + 1):\n num = 0\n while(n % i == 0):\n num += 1\n n /= i\n if num > 0:\n ret += '({}{})'.format(i, '**%d' % num if num > 1 else '')\n if n == 1:\n return ret\n", "def primeFactors(n):\n i, j, p = 2, 0, []\n while n > 1:\n while n % i == 0: n, j = n / i, j + 1\n if j > 0: p.append([i,j])\n i, j = i + 1, 0\n return ''.join('(%d' %q[0] + ('**%d' %q[1]) * (q[1] > 1) + ')' for q in p)", "def primeFactors(n):\n i = 2\n r = ''\n while n != 1:\n k = 0\n while n%i == 0:\n n = n / i\n k += 1\n if k == 1:\n r = r + '(' + str(i) + ')'\n elif k == 0: pass\n else:\n r = r + '(' + str(i) + '**' + str(k) + ')'\n i += 1\n \n return r\n \n", "def primeFactors(n):\n result = ''\n fac = 2\n while fac <= n:\n count = 0\n while n % fac == 0:\n n /= fac\n count += 1\n if count:\n result += '(%d%s)' % (fac, '**%d' % count if count > 1 else '')\n fac += 1\n return result\n", "import math\nfrom itertools import count\nfrom collections import Counter\n\n#Prime generator based on https://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python/10733621#10733621\ndef genPrimes():\n #initial primes\n yield from [2,3,5]\n gen = genPrimes()\n \"\"\"Store count generators starting from the next base prime's square\n incrementing by two times the last prime number. This is for tracking the multiples.\"\"\"\n mults_set = {}\n prime = next(gen)\n prime_sq = prime ** 2\n for i in count(3, 2):\n #if i is a multiple of a prime...\n if i in mults_set:\n mults = mults_set.pop(i)\n \n #if i is the next prime...\n elif i < prime_sq:\n yield i\n continue\n \n #else i is the next primes square\n else:\n mults = count(prime_sq+2*prime, 2*prime)\n prime = next(gen)\n prime_sq = prime ** 2\n \n #get the next multiple that isnt already in the set\n for mult in mults:\n if mult not in mults_set: break\n \n mults_set[mult] = mults\n \ndef primeFactors(n):\n #track count of prime\n output = Counter()\n rem_n = n\n \"\"\"Continue dividing n by it's smallest prime factor, adding each\n factor to the Counter.\"\"\"\n while rem_n > 1:\n #continue generating primes until one that can divide n is reached\n for prime in genPrimes():\n if rem_n % prime == 0:\n output[prime] += 1\n rem_n /= prime\n break\n \n return \"\".join(f\"({prime}**{count})\" if count > 1 else f\"({prime})\" for prime, count in output.items())", "from collections import defaultdict\n\ndef primeFactors(n):\n factors = defaultdict(int)\n n_prime = n\n for i in range(2, int(n**0.5)+1):\n while not n_prime % i:\n factors[i] += 1\n n_prime /= i\n if n_prime != 1:\n factors[n_prime] += 1\n f = lambda x, y: '(%d)' % x if y is 1 else '(%d**%d)' % (x,y)\n return ''.join(f(k, factors[k]) for k in sorted(factors))\n", "from collections import Counter\n\ndef fac(n):\n maxq = int(n ** .5)\n d, q = 1, n % 2 == 0 and 2 or 3\n while q <= maxq and n % q != 0:\n q = 1 + d*4 - d//2*2\n d += 1\n res = Counter()\n if q <= maxq:\n res += fac(n//q)\n res += fac(q)\n else: res[n] = 1\n return res\n\ndef primeFactors(n):\n return ''.join(('({})' if m == 1 else '({}**{})')\n .format(p, m) for p, m in sorted(fac(n).items()))", "def primeFactors(n):\n result = \"\"\n for k, v in factorize(n).items():\n result += f'({k})' if v == 1 else f'({k}**{v})'\n return result\n\n\ndef factorize(n):\n result, i = {}, 2\n while n >= i ** 2:\n if n % i == 0:\n result[i] = 1 if not result.__contains__(i) else result[i] + 1\n n = n // i\n else:\n i += 1\n result[n] = 1 if not result.__contains__(n) else result[n] + 1\n return result", "def primeFactors(n):\n ret = ''\n for i in range(2, int(n **0.5)+1):\n num = 0\n while(n % i == 0):\n num += 1\n n /= i\n if num > 0:\n ret += f'({i}**{num})' if num > 1 else f'({i})'\n if n == 1:\n return ret\n \n return ret + f'({int(n)})'", "def primeFactors(n):\n r = \"\"\n pf = 1\n while n>1:\n pf += 1\n num = 0\n while n%pf == 0:\n n/=pf\n num+=1\n if num>0:\n r += \"(\"+str(pf)+\"**\"+str(num)+\")\"\n r=r.replace(\"**1\",\"\")\n return r\n", "from itertools import compress\ndef sieve(n):\n out = [True] * ((n-2)//2)\n for i in range(3,int(n**0.5)+1,2):\n if out[(i-3)//2]:\n out[(i**2-3)//2::i] = [False] * ((n-i**2-1)//(2*i)+1)\n return [2] + list(compress(range(3,n,2), out))\ndef primeFactors(n):\n str_lst = []\n for i in sieve(int(n**0.5)+1):\n if n%i==0:\n str_lst.extend([\"(\", str(i)])\n counter=0\n while n%i==0:\n n=n//i\n counter+=1\n if counter==1:\n str_lst.append(\")\")\n else:\n str_lst.extend([\"**\",str(counter),\")\"])\n if n!=1:\n str_lst.extend([\"(\",str(n),\")\"])\n return \"\".join(str_lst)", "import math\nfrom collections import Counter\ndef primeFactors(n): \n total = []\n while n % 2 == 0: \n total.append(2)\n n = n // 2\n \n for i in range(3,int(math.sqrt(n))+1,2): \n \n\n while n % i== 0: \n total.append(i)\n n //= i \n \n if n > 2: \n total.append(n)\n return ''.join([f'({key}**{value})' if value > 1 else f'({key})' for key, value in Counter(total).items()])", "def factors(n): \n res = [] \n while n%2 == 0:\n res.append(2)\n n/=2\n for i in range(3,int(n**.5)+1,2): \n while n%i == 0:\n res.append(int(i)) \n n/= i\n if n>2:\n res.append(int(n))\n return res\ndef primeFactors(n):\n factor = dict() \n for i in factors(n): \n if i not in factor:\n factor[i] = 1 \n else:\n factor[i] += 1\n res = \"\"\n for a,b in factor.items(): \n if b == 1:\n res += f'({a})'\n else:\n res += f'({a}**{b})'\n return res", "def primeFactors(n):\n s = {k for k in range(2,int(abs(n)**0.5)+1) for i in range(2,int(abs(k)**0.5)+1) if k%i==0} \n p = [j for j in range(2,int(abs(n)**0.5)+1) if j not in s]\n z = [i for i in f_idx(n,p) if i!=1]\n return ''.join([f\"({i}**{z.count(i)})\" if z.count(i)>1 else f\"({i})\" for i in sorted(set(z))])\n\ndef f_idx(n, p):\n from functools import reduce\n e = list(filter(lambda t: n%t==0, p)) \n a = reduce(lambda x,y: x*y, e) if e!=[] else 1\n return e+[n] if a==1 else e + f_idx(n//a, e)", "def primeFactors(n):\n if isinstance(((n+1)/6),int) or isinstance(((n-1)/6),int): return n\n g=n\n pf=''\n prime=2\n while g!=1:\n count=0\n if (prime-1)%6==0 or (prime+1)%6==0 or prime==2 or prime==3:\n while g%prime==0:\n g=g/prime\n count+=1\n if count>1:\n pf=pf+'('+str(prime)+'**'+str(count)+')'\n elif count>0:\n pf=pf+'('+str(prime)+')'\n prime+=1\n return pf", "from collections import Counter\n\n \ndef get_factors(num):\n if num % 2 == 0:\n return (2, num // 2)\n for i in range(3, num // 2, 2):\n if num % i == 0:\n return (i, num // i)\n return (num, None)\n\n\ndef string_builder(count_dict):\n s = \"\"\n for element in count_dict:\n if count_dict[element] == 1:\n s += f\"({element})\"\n else:\n s += f\"({element}**{count_dict[element]})\"\n return s\n\n\ndef primeFactors(n):\n factors = [n]\n count_dict = Counter()\n \n while factors:\n result = get_factors(factors.pop())\n count_dict[result[0]] += 1\n if result[1]:\n factors.append(result[1])\n \n return string_builder(count_dict)\n", "from collections import Counter\n\ndef primeFactors(n):\n c = Counter()\n while n % 2 == 0:\n c[2] += 1\n n //= 2\n\n d = 3\n while n > 1:\n while n % d == 0:\n c[d] += 1\n n //= d\n d += 2\n \n return ''.join(f'({key}**{value})' if value > 1 else f'({key})' for key, value in sorted(c.items()))", "def primeFactors(n):\n a=[]\n i=2\n while i*i<=n:\n while n%i==0:\n a.append(i)\n n//=i\n i+=1\n if n!=1:\n a.append(n)\n s=[i for i in set(a)]\n s.sort()\n return ''.join('({})'.format(i) if a.count(i)==1 else '({}**{})'.format(i,a.count(i)) for i in s ) ", "from itertools import count\n\ndef primeFactors(n):\n def power(x, n, res=\"\"):\n i = 0\n while not n%x: n, i = n//x, i+1\n return n, res+(f\"({x})\" if i==1 else f\"({x}**{i})\" if i>1 else \"\")\n n, res = power(2, n)\n for x in count(3, 2):\n if n == 1: return res\n n, res = power(x, n, res)", "from collections import Counter\n\ndef primeFactors(number):\n ret, i = [], 2\n while i <= number:\n if number % i == 0:\n ret.append(i)\n number = number // i\n continue\n if i is not 2:\n i += 2\n else:\n i += 1\n count = Counter(ret)\n ret_string = []\n for key in sorted(count):\n ret_string.append('({})'.format(key)) if count[key] == 1 else ret_string.append('({}**{})'.format(key, count[key]))\n\n return ''.join(ret_string)", "def primeFactors(n):\n c = 0\n m = 2\n r = []\n while(True):\n if n == 1:\n r.append('(' + str(m) + ')')\n return ''.join(r)\n if n % m == 0:\n n = n / m\n c += 1\n else:\n if c != 0 and c != 1:\n r.append('(' + str(m) + '**' + str(c) + ')') \n if c == 1:\n r.append('(' + str(m) + ')')\n m += 1\n c = 0\n \n", "def primeFactors(n):\n ret,p,k=\"\",2,0\n while (p<=n):\n while (n%p==0):\n n=n//p\n k+=1\n if (k):\n ret=ret+\"(\"+str(p)+((\"**\"+str(k)) if k>1 else \"\")+\")\"\n k=0\n p+=1+(p>2)\n return(ret)", "def primeFactors(n):\n factors=[]\n n1=n\n while n1%2 == 0:\n n1=n1/2\n factors.append(2)\n for i in range (3, int(n1**(1/2.0))):\n while n1%i == 0:\n n1=n1/i\n factors.append(i)\n if factors==[]:\n factors.append(n)\n elif n1 != 1:\n factors.append(int(n1))\n factors.append(0)\n x=0\n l=''\n final=\"\"\n for a in factors:\n if l=='':\n l=a\n x=x+1\n elif l != a:\n if x==1:\n final=final+\"(\"+str(l)+\")\"\n l=a\n x=1\n else:\n final=final+\"(\"+str(l)+\"**\"+str(x)+\")\"\n l=a\n x=1\n else:\n x=x+1\n return final\n \n", "from collections import defaultdict\n\n\ndef is_prime(a):\n return all(a % i for i in range(2, a))\n\n\ndef primeFactors(n):\n factors = defaultdict(int)\n rest = n\n while rest != 1:\n for num in range(2, rest+1):\n if rest % num == 0 and is_prime(num):\n factors[num] += 1\n rest //= num\n break\n\n return ''.join(\n map(\n lambda nc: '({}**{})'.format(nc[0], nc[1]) if nc[1] > 1 else '({})'.format(nc[0]),\n sorted(factors.items(), key=lambda x: x[0])\n )\n )", "def primeFactors(n):\n res = \"\"\n fac = 2\n while fac <= n:\n count = 0\n while n % fac == 0:\n count += 1\n n = n / fac\n if count > 0:\n res += \"(\" + str(fac)\n res += \"**\" + str(count) if (count > 1) else \"\" \n res += \")\"\n fac += 1\n return res\n", "def primeFactors(n):\n i = 2\n j = 0\n out = ''\n while n > 1:\n if n % i == 0:\n n //= i\n j += 1\n else:\n if j == 1:\n out += '({})'.format(i)\n elif j > 1:\n out += '({}**{})'.format(i, j)\n i += 1\n j = 0\n return out + '({})'.format(i)", "def primeFactors(n):\n div = 2\n k = 0\n s = ''\n while div < n:\n while n%div!=0:\n div +=1\n while n%div ==0:\n n=n//div\n k+=1\n s+='({}{})'.format(str(div), '**'+ str(k) if k > 1 else '')\n k = 0\n return s", "import math\n\n\ndef primeFactors(n):\n primes = {}\n while n % 2 == 0:\n n //= 2\n try:\n primes[2] += 1\n except:\n primes[2] = 1\n for i in range(3, int(math.sqrt(n)) + 1, 2):\n while n % i == 0:\n n //= i\n try:\n primes[i] += 1\n except:\n primes[i] = 1\n if n != 1:\n primes[n] = 1\n primes = sorted(list(primes.items()), key=lambda k: k[0])\n return \"\".join(\n [\n \"({}**{})\".format(k, v) if v > 1 else \"({})\".format(k)\n for k, v in primes\n ]\n )\n\n\n", "def primeFactors(n):\n power = {}\n div = 2\n while div <= n:\n if n % div == 0:\n if div in power:\n power[div] += 1\n else:\n power[div] = 1\n n /= div\n else:\n div +=1\n return ''.join([f\"({k}**{v})\" if v > 1 else f\"({k})\" for k, v in power.items()])", "import math\n\ndef primeFactors(n):\n # returns the maximum prime factor\n max = maxPrimeFactors(n)\n \n # factorize n and stores factors in facts\n facts = []\n for i in range(2, int(max + 1)):\n while n % i == 0:\n facts.append(i)\n n = n/i\n \n # removes duplicates for ret and sorts the list\n facts_nodup = list(set(facts))\n facts_nodup.sort()\n # formats return string\n ret_str = \"\"\n for x in facts_nodup:\n count = facts.count(x)\n if count > 1:\n ret_str += \"({}**{})\".format(x, count)\n else:\n ret_str += \"({})\".format(x)\n \n return ret_str\n \n# A function to find largest prime factor \ndef maxPrimeFactors(n): \n \n # Initialize the maximum prime factor \n # variable with the lowest one \n maxPrime = -1\n \n # Print the number of 2s that divide n \n while n % 2 == 0: \n maxPrime = 2\n n >>= 1 # equivalent to n /= 2 \n \n # n must be odd at this point, \n # thus skip the even numbers and \n # iterate only for odd integers \n for i in range(3, int(math.sqrt(n)) + 1, 2): \n while n % i == 0: \n maxPrime = i \n n = n / i \n \n # This condition is to handle the \n # case when n is a prime number \n # greater than 2 \n if n > 2: \n maxPrime = n \n \n return int(maxPrime) \n", "import math\ndef primeFactors(n):\n ar=[]\n while n%2==0: \n ar.append(2) \n n=n/2 \n for i in range(3,int(math.sqrt(n))+1,2):\n while n%i==0: \n ar.append(i) \n n=n/i\n if n>2: \n ar.append(n)\n ax='**'\n x=''\n for i in sorted(set(ar)):\n c=ar.count(i)\n if c>1:\n x+='('+str(i)+ax+str(c)+')'\n else: x+='('+str(int(i))+')'\n return x", "def primeFactors(n):\n i=2\n li=[]\n s=\"\"\n while n!=1:\n count=0\n while n%i==0:\n n=n/i\n count=count+1\n if count!=0:\n re=(i,count)\n li.append(re)\n i=i+1\n for i in li:\n if i[1]!=1:\n s=s+\"(\"+str(i[0])+\"**\"+str(i[1])+\")\"\n else:\n s=s+\"(\"+str(i[0])+\")\"\n return s", "def primeFactors(n):\n comp=[]\n i=1\n o=0\n while n!=1:\n i=i+1\n if n%i==0:\n o=o+1\n while n%i==0:\n n=n/i\n comp.append(i)\n if o==0:\n return '('+str(n)+')'\n g=['('+str(x)+ '**'+str(comp.count(x))+')' if comp.count(x)>1 else '('+str(x)+')' for x in sorted(list(set(comp))) ]\n return ''.join(g)\n \n", "from collections import OrderedDict\nfrom math import sqrt\n\n\nclass OrderedIntDict(OrderedDict):\n def __missing__(self, key):\n return 0\n\n\ndef format_factor(n, times):\n return (\n \"({n})\".format(n=n) if times == 1\n else \"({n}**{times})\".format(n=n, times=times)\n )\n\n\ndef prime_factors(number):\n factors = OrderedIntDict()\n for n in range(2, int(sqrt(number))+1):\n while number % n == 0:\n number //= n\n factors[n] += 1\n if number > 1:\n factors[number] = 1\n return \"\".join(\n format_factor(n, times)\n for n, times in factors.items()\n )\n \n\nprimeFactors = prime_factors", "def primeFactors(n):\n factors = []\n p = 2 \n while n != 1 and p <= n**0.5:\n if n % p == 0:\n factors.append(p)\n n = n // p\n else:\n p = p + 1\n if n != 1:\n factors.append(n)\n n = 1\n \n distinct = sorted(set(factors))\n \n answer = \"\"\n for prime in distinct:\n if factors.count(prime) == 1:\n answer = answer + \"(\" + str(prime) + \")\"\n else:\n answer = answer + \"(\" + str(prime) + \"**\" + str(factors.count(prime)) + \")\"\n \n return answer", "import math\n\ndef primeFactors(n:int)-> str:\n list_result = []\n while n % 2 == 0: \n n = n / 2\n list_result.append(2) \n for i in range(3,int(math.sqrt(n))+1,2): \n while n % i== 0: \n n = n // i\n list_result.append(i) \n if n > 2: \n list_result.append(int(n))\n \n return ''.join([f\"({i})\" if list_result.count(i) == 1 else f\"({i}**{list_result.count(i)})\" for i in sorted(list(set(list_result)))])\n\n", "# Using the sqrt function for speed (instead of **0.5)\nfrom math import sqrt\ndef seiveOfEratosthenes(n):\n # For speed, only grabbing all odd numbers from 3 to SQRT N\n flags = [True for i in range(3, int(sqrt(n))+1, 2)]\n # Adding a flag for \"2\" (effectively a pre-pend here)\n flags.append(True)\n \n # Iterate through Primes\n prime = 2\n while (prime <= sqrt(n)):\n # Cross Off all multiples of Prime\n for i in range(prime**2, len(flags), prime):\n flags[i] = False\n \n # Get next Prime\n prime += 1\n while (prime < len(flags) and not flags[prime]):\n prime += 1\n # Get the list of Primes as actual #'s; We need a special case for \"2\" because it doesn't fit the odds pattern\n if flags[0]:\n primes = [2]\n else:\n primes = []\n primes += [i for i in range(3, len(flags), 2) if flags[i]]\n \n return primes\n \n \n\ndef primeFactors(n):\n # Get applicable Prime numbers\n primes = seiveOfEratosthenes(n)\n primes_in_number = []\n \n for prime in primes:\n # Iterate through each prime, and figure out how many times it goes in\n repeat = 0\n while (not (n % prime)):\n repeat += 1\n n /= prime\n \n # Add appearing Primes appropriately\n if repeat == 1:\n primes_in_number.append(\"(\" + str(prime) + \")\")\n elif repeat:\n primes_in_number.append(\"(\" + str(prime) + \"**\" + str(repeat) + \")\")\n \n # Only testing primes up to sqrt of n, so we need to add n if it hasn't been reduced to 1\n if n > 1:\n primes_in_number.append(\"(\" + str(int(n)) + \")\")\n \n return ''.join(primes_in_number)", "def primeFactors(n):\n s=str()\n for i in range(2, int(n**(1/2))+1):\n j=0\n while n/i%1==0.0:\n j+=1\n n/=i\n if j>1:\n s+=\"(\"\n s+=str(i)\n s+=\"**\"\n s+=str(j)\n s+=\")\"\n if j==1:\n s+=\"(\"\n s+=str(i)\n s+=\")\"\n if n!=1:\n s+=\"(\"\n s+=str(int(n))\n s+=\")\"\n return s \n else:\n return s ", "import math\ndef primeFactors(number):\n\n # create an empty list and later I will\n # run a for loop with range() function using the append() method to add elements to the list.\n prime_factors = []\n\n # First get the number of two's that divide number\n # i.e the number of 2's that are in the factors\n while number % 2 == 0:\n prime_factors.append(2)\n number = number / 2\n\n # After the above while loop, when number has been\n # divided by all the 2's - so the number must be odd at this point\n # Otherwise it would be perfectly divisible by 2 another time\n # so now that its odd I can skip 2 ( i = i + 2) for each increment\n for i in range(3, int(math.sqrt(number)) + 1, 2):\n while number % i == 0:\n prime_factors.append(int(i))\n number = number / i\n\n if number > 2:\n prime_factors.append(int(number))\n \n distinct_set = sorted(set(prime_factors))\n \n output = \"\"\n \n for i in distinct_set:\n \n if(prime_factors.count(i) == 1):\n \n output = output + '(' + str(i) + ')'\n else:\n output = output + '(' + str(i)+ '**' + str(prime_factors.count(i)) + ')'\n \n return output", "def primeFactors(n):\n result = ''\n factor = 2\n while 1:\n count = 0\n while n % factor == 0:\n count += 1\n n = n / factor\n if count == 1 and count != 0:\n result = result + '(%s)' % factor\n elif count != 0:\n result = result + '({}**{})'.format(factor, count)\n else:\n factor += 1\n continue\n factor += 1\n if n == 1:\n break\n return result\n \n \n ...", "def primeFactors(n):\n i = 2\n a = []\n while i <= n:\n if n % i == 0:\n if not any([i%x[0]==0 for x in a]):\n max_power = 0\n div = n\n while div%i==0:\n max_power+=1\n div/=i\n a.append((i, max_power))\n n/=i\n i+=1\n return ''.join([f'({x}**{y})' if y!=1 else f'({x})' for x,y in a ])", "import collections\ndef primeFactors(n):\n ret = []\n pows = {}\n st = \"\"\n i = 2\n while(i<n):\n if n%i == 0:\n n /= i\n ret.append(i)\n else:\n i += 1\n ret.append(int(n))\n for j in set(ret):\n pows.update({int(j):ret.count(j)})\n print(pows)\n pows = collections.OrderedDict(sorted(pows.items()))\n for key in pows:\n if pows[key] > 1:\n st += \"(\"+ str(key)+\"**\"+ str(pows[key])+\")\"\n else:\n st += \"(\"+str(key)+\")\"\n return st", "def primeFactors(x):\n primes = {}\n prime_int = 2\n y = x\n while prime_int < x+1:\n while x % prime_int == 0:\n if prime_int not in primes:\n primes[prime_int] = 1 \n else:\n primes[prime_int] += 1 \n x //= prime_int\n prime_int += 1\n phrase = ''\n for digit,count in primes.items():\n if count == 1:\n phrase += f'({digit})'\n continue\n phrase += f'({digit}**{count})'\n print(phrase)\n return phrase", "def primeFactors(n):\n i = 2\n factors = {}\n while i * i <= n:\n if n % i:\n i += 1\n else:\n n //= i\n if(i in factors.keys()):\n factors[i]+=1\n else:\n factors[i]=1\n if n > 1:\n factors[n]=1\n string=\"\"\n for key in factors.keys():\n if factors[key]==1:\n string+=\"({})\".format(key)\n else:\n string+=\"({}**{})\".format(key,factors[key])\n return string", "def primeFactors(n):\n def is_prime(number):\n if number == 1: return False\n for num in range(3,(int)(number**.5) + 1,2):\n if number % num == 0:\n return False\n return True\n primes_prelimenary = []\n while n > 1:\n if is_prime(n):\n primes_prelimenary.append(n)\n n = 1\n continue\n while n % 2 == 0:\n primes_prelimenary.append(2)\n n = n / 2\n for num in range(3,(int)(n**.5) + 1,2):\n if n % num == 0 and is_prime(num): \n while n % num == 0:\n primes_prelimenary.append(num)\n n = n / num\n return ''.join(f'({(int)(factor)}**{primes_prelimenary.count(factor)})' for factor in sorted(set(primes_prelimenary))).replace('**1','')", "def primeFactors(n):\n list = []\n for i in range(2, round(n**0.5)):\n while (n/i).is_integer():\n n /= i\n list.append(i)\n if len(list) < 2:\n list.append(int(n))\n list_seen = []\n str1 = ''\n for x in list:\n if x in list_seen:\n pass\n else:\n list_seen.append(x)\n if list.count(x) > 1:\n str1 += f\"({str(x)}**{str(list.count(x))})\"\n else:\n str1 += \"(\" + str(x) + \")\"\n return str1", "import math\n\ndef primeFactors(n):\n dic_prime = {}\n dic_prime[2] = 0\n while n%2 ==0:\n dic_prime[2] += 1\n n = n/2\n if dic_prime[2] == 0:\n dic_prime.pop(2)\n\n for i in range(3,int(n+1),2):\n dic_prime[i] = 0\n while n%i ==0:\n dic_prime[i] += 1\n n = n/i\n if n <= 1:\n break\n if dic_prime[i] == 0:\n dic_prime.pop(i)\n\n output_str = \"\"\n for k,v in dic_prime.items():\n if v == 1:\n output_str += \"({})\".format(str(k))\n else:\n output_str +=\"({}**{})\".format(str(k),str(v))\n\n return output_str"] | {"fn_name": "primeFactors", "inputs": [[7775460], [7919], [18195729], [933555431], [342217392], [35791357], [782611830], [775878912]], "outputs": [["(2**2)(3**3)(5)(7)(11**2)(17)"], ["(7919)"], ["(3)(17**2)(31)(677)"], ["(7537)(123863)"], ["(2**4)(3)(11)(43)(15073)"], ["(7)(5113051)"], ["(2)(3**2)(5)(7**2)(11)(13)(17)(73)"], ["(2**8)(3**4)(17)(31)(71)"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 27,122 |
def primeFactors(n):
|
c8a0b33a2d8fbfdad6e71db779b0d1ea | UNKNOWN | As you may know, once some people pass their teens, they jokingly only celebrate their 20th or 21st birthday, forever. With some maths skills, that's totally possible - you only need to select the correct number base!
For example, if they turn 32, that's exactly 20 - in base 16... Already 39? That's just 21, in base 19!
Your task is to translate the given age to the much desired 20 (or 21) years, and indicate the number base, in the format specified below.
**Note:** input will be always > 21
### Examples:
```
32 --> "32? That's just 20, in base 16!"
39 --> "39? That's just 21, in base 19!"
```
*Hint: if you don't know (enough) about [numeral systems](https://en.wikipedia.org/wiki/Numeral_system) and [radix](https://en.wikipedia.org/wiki/Radix), just observe the pattern!*
---
## My other katas
If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-)
---
### *Translations are welcome!* | ["def womens_age(n):\n return f\"{n}? That's just {20+n%2}, in base {n//2}!\"", "womens_age = lambda n: f\"{n}? That's just 2{n % 2}, in base {n // 2}!\"", "def womens_age(n):\n return f\"{n}? That's just 2{n % 2}, in base {n // 2}!\"", "def womens_age(n):\n return f\"{n}? That's just {21 if n % 2 else 20}, in base {(n - 1) // 2 if n % 2 else n // 2}!\"", "def womens_age(n):\n for i in range(11, 100):\n a, b = divmod(n, i)\n if a == 2 and b < 2:\n return f\"{n}? That's just {a}{b}, in base {i}!\"", "def womens_age(n):\n a = 2\n L1 = [0, 1]\n for i in L1:\n x = int((n - L1[i]) / a)\n if (n % x) == L1[i]:\n base = x\n result = \"%d%d\" % (a , L1[i])\n return str(n) + \"? That's just \" + str(result) + \", in base \" + str(base) + \"!\"", "womens_age = lambda Q : f\"{Q}? That's just 2{1 & Q}, in base {Q >> 1}!\"", "def womens_age(n):\n base = (n//2)\n if n % 2 == 0:\n return f\"{n}? That's just 20, in base {base}!\"\n else:\n return f\"{n}? That's just 21, in base {base}!\"", "def womens_age(n):\n return f\"{ n }? That's just { 20+n%2 }, in base { n>>1 }!\"", "def womens_age(n):\n return str(n) + \"? That's just 20, in base \" + str(n//2) + \"!\" if n % 2 == 0 else str(n) + \"? That's just 21, in base \" + str(n//2) + \"!\""] | {"fn_name": "womens_age", "inputs": [[32], [39], [22], [65], [83]], "outputs": [["32? That's just 20, in base 16!"], ["39? That's just 21, in base 19!"], ["22? That's just 20, in base 11!"], ["65? That's just 21, in base 32!"], ["83? That's just 21, in base 41!"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,356 |
def womens_age(n):
|
290bf1ec18f9a73249d347a894fb8b3a | UNKNOWN | ~~~if-not:ruby,python
Return `1` when *any* odd bit of `x` equals 1; `0` otherwise.
~~~
~~~if:ruby,python
Return `true` when *any* odd bit of `x` equals 1; `false` otherwise.
~~~
Assume that:
* `x` is an unsigned, 32-bit integer;
* the bits are zero-indexed (the least significant bit is position 0)
## Examples
```
2 --> 1 (true) because at least one odd bit is 1 (2 = 0b10)
5 --> 0 (false) because none of the odd bits are 1 (5 = 0b101)
170 --> 1 (true) because all of the odd bits are 1 (170 = 0b10101010)
``` | ["MATCH = int('10'*16,2)\n\ndef any_odd(x): return bool(MATCH & x)", "def any_odd(n):\n return 1 if '1' in bin(n)[2:][-2::-2] else 0", "def any_odd(x):\n return x & 0xaaaaaaaa != 0", "def any_odd(x):\n return int(\"1\" in f\"{x:032b}\"[::2])", "def any_odd(x):\n bin = \"{0:b}\".format(x)\n bin = bin[::-1]\n odd = 0\n print(bin)\n for letter in bin:\n if odd%2 == 1 and letter == '1':\n return 1\n odd+= 1\n return 0", "def any_odd(x):\n # Write code here...\n a = bin(x)[2:]\n b = a[-2::-2]\n return 1 if '1' in b else 0\n", "def any_odd(x):\n return '1' in f'0{x:b}'[-2::-2]", "def any_odd(x):\n binary=bin(x)\n answer=0\n binary_reversed=str(binary[::-1])\n for k in range (0,len(binary_reversed)):\n if (k % 2 !=0 and binary_reversed[k]=='1'):\n answer=1\n return answer", "def any_odd(x):\n return '1' in list(bin(x)[-2::-2])", "def any_odd(x):\n bina=bin(x).split('b')[1]\n for a,b in enumerate(bina,start=len(bina)-1):\n if a%2:\n if '1' in b:\n return 1\n return 0"] | {"fn_name": "any_odd", "inputs": [[2863311530], [128], [131], [2], [24082], [0], [85], [1024], [1], [1365]], "outputs": [[true], [true], [true], [true], [true], [false], [false], [false], [false], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,120 |
def any_odd(x):
|
6cbdf418f4652fe909d51de2f94e9988 | UNKNOWN | Let's take an integer number, ``` start``` and let's do the iterative process described below:
- we take its digits and raise each of them to a certain power, ```n```, and add all those values up. (result = ```r1```)
- we repeat the same process with the value ```r1``` and so on, ```k``` times.
Let's do it with ```start = 420, n = 3, k = 5```
```
420 ---> 72 (= 4³ + 2³ + 0³) ---> 351 (= 7³ + 2³) ---> 153 ---> 153 ----> 153
```
We can observe that it took ```3``` steps to reach a cyclical pattern ```[153]```(```h = 3```). The length of this cyclical pattern is ```1```, ```patt_len```. The last term of our k operations is 153, ```last_term```
Now, ```start = 420, n = 4, k = 30```
```
420 ---> 272 ---> 2433 ---> 434 ---> 593 ---> 7267 --->
6114 ---> 1554 ---> 1507 ---> 3027 ---> 2498 ---> 10929 --->
13139 ---> 6725 ---> 4338 ---> 4514 ---> 1138 ---> 4179 ---> 9219 --->
13139 ---> 6725 ---> 4338 ---> 4514 ---> 1138 ---> 4179 ---> 9219 --->
13139 ---> 6725 ---> 4338 ---> 4514 ---> 1138 ---> 4179 ---> 9219......
```
In this example we can observe that the cyclical pattern (```cyc_patt_arr```) is ```[13139, 6725, 4338, 4514, 1138, 4179, 9219]``` with a length of ```7```, (```patt_len = 7```), and it took ```12``` steps (```h = 12```) to reach the cyclical pattern. The last term after doing ```30``` operations is ```1138```
Make the function ```sum_pow_dig_seq()```, that receives the arguments in the order shown below with the corresponding output:
```python
sum_pow_dig_seq(start, n, k) ---> [h, cyc_patt_arr, patt_len, last_term]
```
For our given examples,
```python
sum_pow_dig_seq(420, 3, 5) == [3, [153], 1, 153]
sum_pow_dig_seq(420, 4, 30) == [12, [13139, 6725, 4338, 4514, 1138, 4179, 9219], 7, 1138]
```
Constraints for tests:
```
500 ≤ start ≤ 8000
2 ≤ n ≤ 9
100 * n ≤ k ≤ 200 * n
```
Do your best! | ["def sum_pow_dig_seq(num, exp, k):\n seq = []\n \n for step in range(k):\n seq.append(num)\n num = sum( int(dig) ** exp for dig in str(num) )\n \n if num in seq:\n cycle_start = seq.index(num)\n cycle = seq[cycle_start:]\n last_term = cycle[(k - cycle_start) % len(cycle)]\n return [ cycle_start, cycle, len(cycle), last_term ]\n \n return [ 0, [], 0, num ]", "def sum_pow_dig_seq(start, n, k):\n seq = [start]\n num = start\n for i in range(k):\n num = sum([int(x)**n for x in str(num)])\n if num in seq:\n # We got the loop!\n loop_starts_from = seq.index(num)\n loop_array = seq[loop_starts_from:]\n tail_size = loop_starts_from\n loop_size = len(loop_array)\n last_term = loop_array[(k - tail_size) % loop_size]\n return [tail_size, loop_array, loop_size, last_term]\n seq.append(num)\n else:\n # What if we didn`t get the loop?\n return [len(seq), [], 0, seq[-1]]\n \n", "def sum_pow_dig_seq(start, n, k):\n seen = [start]\n for i in range(k):\n r1 = sum(map(lambda x: x**n, map(int,str(seen[-1]))))\n if r1 in seen: #Cycle detected.\n h = seen.index(r1)\n cyc_patt_arr = seen[h:]\n patt_len = len(seen) - h\n last_term = cyc_patt_arr[(k-i-1)%patt_len]\n break\n seen.append(r1)\n \n return [h, cyc_patt_arr, patt_len, last_term]", "def sum_of_digits_pow(n, e):\n return sum([i**e for i in map(int, str(n))])\n\ndef sum_pow_dig_seq(start, e, k):\n h = 0\n cyc_patt_arr, sums = [], []\n for i in range(1, k+1):\n start = sum_of_digits_pow(start, e)\n if not cyc_patt_arr and start in sums:\n cyc_patt_arr = [j for j in sums[sums.index(start):]]\n h = sums.index(start) + 1\n return [h, cyc_patt_arr, len(cyc_patt_arr), cyc_patt_arr[(k-i) % len(cyc_patt_arr)]]\n sums.append(start)\n \n", "def sum_pow_dig_seq(start, n, k):\n def next_(v):\n return sum(int(c) ** n for c in str(v))\n \n history = []\n history_set = set()\n x = start\n while True:\n if x in history_set:\n i = history.index(x)\n cyc = history[i:]\n if k < len(history):\n return [i, cyc, len(cyc), history[k]]\n return [i, cyc, len(cyc), cyc[(k - i) % len(cyc)]]\n history.append(x)\n history_set.add(x)\n x = next_(x)", "def sum_pow_dig_seq(start, n, k):\n cycle, l, h, drop = set(), [], -1, False\n for i in range(k):\n start = sum(int(d)**n for d in str(start))\n if h != -1 and start in cycle: break\n if h == -1 and start in cycle:\n cycle, h, l = set(), i, []\n cycle.add(start)\n l.append(start)\n return [h-len(l)+1, l, len(l), l[(k-i-1)%len(l)]]", "def sum_pow_dig_seq(start, n, k):\n x = start\n series = []\n seen_at = {}\n i = 0\n while x not in seen_at:\n series.append(x)\n seen_at[x] = i\n x = sum(int(d) ** n for d in str(x))\n i += 1\n i_first = seen_at[x]\n cycle_length = i - i_first\n if k >= i:\n k = i_first + (k - i_first) % cycle_length\n return [i_first, series[i_first:], cycle_length, series[k]]", "def sum_pow_dig_seq(start, n, k):\n r=[]\n for i in range (0,k):\n c=0\n for d in str(start):\n c+=int(d)**n\n r.append(c); start=c\n for i in range (0,k):\n if r[i] in r[i+1:]:\n posE=r.index(r[i],i+1)\n if posE>=0:\n if r[i:posE-1]==r[posE:posE+posE-1-i]: posS=i; break \n return [posS+1, r[posS:posE], posE-posS, start]", "def sum_pow_dig_seq(start, n, k):\n li = []\n for _ in range(k):\n r = sum([j ** n for j in map(int, str(start))])\n if r in li:\n reach = n = li.index(r) + 1 ; series = li[li.index(r):] ; s_l = len(series)\n while n + s_l <= k : n += s_l\n return [reach, series, s_l, series[k - n]]\n li.append(r) ; start = r", "def sum_pow_dig_seq(n, e, k):\n path = [n]\n while True:\n n = sum(int(d)**e for d in str(n))\n if n in path: break\n path.append(n)\n h = path.index(n)\n loop = path[h:]\n return [h, loop, len(loop), loop[(k-h)%len(loop)]]\n"] | {"fn_name": "sum_pow_dig_seq", "inputs": [[420, 3, 5], [420, 4, 30], [420, 5, 100]], "outputs": [[[3, [153], 1, 153]], [[12, [13139, 6725, 4338, 4514, 1138, 4179, 9219], 7, 1138]], [[23, [9045, 63198, 99837, 167916, 91410, 60075, 27708, 66414, 17601, 24585, 40074, 18855, 71787, 83190, 92061, 66858, 84213, 34068, 41811, 33795, 79467, 101463], 22, 18855]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,444 |
def sum_pow_dig_seq(start, n, k):
|
90f0561fb0e9d1ca9fab6f6c295d8428 | UNKNOWN | **This Kata is intended as a small challenge for my students**
All Star Code Challenge #19
You work for an ad agency and your boss, Bob, loves a catchy slogan. He's always jumbling together "buzz" words until he gets one he likes. You're looking to impress Boss Bob with a function that can do his job for him.
Create a function called sloganMaker() that accepts an array of string "buzz" words. The function returns an array of all possible UNIQUE string permutations of the buzz words (concatonated and separated by spaces).
Your boss is not very bright, so anticipate him using the same "buzz" word more than once, by accident. The function should ignore these duplicate string inputs.
```
sloganMaker(["super", "hot", "guacamole"]);
//[ 'super hot guacamole',
// 'super guacamole hot',
// 'hot super guacamole',
// 'hot guacamole super',
// 'guacamole super hot',
// 'guacamole hot super' ]
sloganMaker(["cool", "pizza", "cool"]); // => [ 'cool pizza', 'pizza cool' ]
```
Note:
There should be NO duplicate strings in the output array
The input array MAY contain duplicate strings, which should STILL result in an output array with all unique strings
An empty string is valid input
```if-not:python,crystal
The order of the permutations in the output array does not matter
```
```if:python,crystal
The order of the output array must match those rules:
1. Generate the permutations in lexicographic order of the original array.
2. keep only the first occurence of a permutation, when duplicates are found.
``` | ["def slogan_maker(array):\n print(array)\n from itertools import permutations \n array = remove_duplicate(array)\n return [' '.join(element) for element in list(permutations(array, len(array)))]\n \ndef remove_duplicate(old_list): \n final_list = [] \n for num in old_list: \n if num not in final_list: \n final_list.append(num) \n return final_list ", "from itertools import permutations\n\ndef slogan_maker(arr):\n return list(map(' '.join, permutations(dict(list(zip(arr, list(range(len(arr)))))))))\n", "slogan_maker=lambda a:list(map(' '.join,__import__('itertools').permutations(dict.fromkeys(a))))", "import itertools, collections\n\ndef slogan_maker(array):\n return [' '.join(i) for i in itertools.permutations(collections.OrderedDict.fromkeys(array))]", "def slogan_maker(array):\n ls=[]\n for i in array:\n if i not in ls:\n ls.append(i)\n if len(ls) ==0:\n return []\n if len(ls) ==1:\n return ls\n l=[]\n for i in range(len(ls)):\n e = ls[i]\n re = [i for i in ls if i!=e]\n \n for p in slogan_maker(re):\n l.append(e+\" \"+p)\n return l", "from itertools import permutations\n\ndef remove_duplicates(list):\n unique = []\n for l in list:\n if l not in unique:\n unique.append(l)\n return unique\n\ndef slogan_maker(input):\n input = remove_duplicates(input)\n output = []\n for p in permutations(input, len(input)):\n output.append(' '.join(p))\n return output", "\nimport itertools\n\ndef slogan_maker(a):\n a2 = list(set(a))\n a2.sort(key=a.index) # \u5b57\u7b26\u4e32\u53bb\u91cd\u540e\u6309\u539f\u987a\u5e8f\u6392\u5217\n x = []\n result = list(itertools.permutations(a2, len(a2))) # \u5b57\u7b26\u4e32\u6392\u5217\u7ec4\u5408\u8003\u8651\u987a\u5e8f\n for i in range(0,len(result)):\n x.append(join1(result[i]))\n i+=1\n return x\n\ndef join1(x): # \u5b57\u7b26\u4e32\u5408\u5e76join\n x1 = list(x)\n return ' '.join(x1)\n", "from itertools import permutations\n\ndef slogan_maker(array):\n array = [e for index, e in enumerate(array) if array.index(e) == index]\n buzz_words = permutations(array,len(array))\n return [' '.join(buzz) for buzz in buzz_words]\n \n \n", "import itertools\ndef slogan_maker(tab):\n tab_set = set()\n unique = [x for x in tab if x not in tab_set and (tab_set.add(x) or True)]\n generator = [] * len(unique)\n x = list(itertools.permutations(unique))\n for i in x:\n generator.append(\" \".join(i))\n return generator", "from collections import Counter\nfrom itertools import permutations\ndef slogan_maker(array):\n slogan=[i for i in list(Counter(array).keys())]\n res=[]\n for i in permutations(slogan, len(slogan)):\n res.append(\" \".join(i))\n return res\n"] | {"fn_name": "slogan_maker", "inputs": [[["super"]], [["super", "hot"]], [["super", "hot", "guacamole"]], [["super", "guacamole", "super", "super", "hot", "guacamole"]], [["testing", "testing", "testing"]]], "outputs": [[["super"]], [["super hot", "hot super"]], [["super hot guacamole", "super guacamole hot", "hot super guacamole", "hot guacamole super", "guacamole super hot", "guacamole hot super"]], [["super guacamole hot", "super hot guacamole", "guacamole super hot", "guacamole hot super", "hot super guacamole", "hot guacamole super"]], [["testing"]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,896 |
def slogan_maker(array):
|
564e6fb8fcfbba46b36ed49bf34889dc | UNKNOWN | You are to write a function to transpose a guitar tab up or down a number of semitones. The amount to transpose is a number, positive or negative. The tab is given as an array, with six elements for each guitar string (fittingly passed as strings). Output your tab in a similar form.
Guitar tablature (or 'tab') is an alternative to sheet music, where notes are replaced by fret numbers and the five lines of the staff are replaced by six lines to represent each of the guitar's strings. It is still read from left to right like sheet music, and notes written directly above each other are played at the same time.
For example, Led Zeppelin's Stairway to Heaven begins:
```
e|-------5-7-----7-|-8-----8-2-----2-|-0---------0-----|-----------------|
B|-----5-----5-----|---5-------3-----|---1---1-----1---|-0-1-1-----------|
G|---5---------5---|-----5-------2---|-----2---------2-|-0-2-2-----------|
D|-7-------6-------|-5-------4-------|-3---------------|-----------------|
A|-----------------|-----------------|-----------------|-2-0-0---0--/8-7-|
E|-----------------|-----------------|-----------------|-----------------|
```
Transposed up two semitones, it would look like this:
```
e|-------7-9-----9-|-10-----10-4-----4-|-2---------2-----|------------------|
B|-----7-----7-----|----7--------5-----|---3---3-----3---|-2-3-3------------|
G|---7---------7---|------7--------4---|-----4---------4-|-2-4-4------------|
D|-9-------8-------|-7---------6-------|-5---------------|------------------|
A|-----------------|-------------------|-----------------|-4-2-2---2--/10-9-|
E|-----------------|-------------------|-----------------|------------------|
```
Note how when the 8th fret note on the top string in bar 2 gets transposed to the 10th fret, extra '-' are added on the other strings below so as to retain the single '-' that originally separated that beat (i.e. column) from the following note – fret 7 on the B string.
Each beat must retain at least one '-' separator before the next, to keep the tab legible. The inputted test tabs all obey this convention.
Electric guitars usually have 22 frets, with the 0th fret being an open string. If your fret numbers transpose to either negative values or values over 22, you should return 'Out of frets!' (and probably detune your guitar).
Tests include some randomly generated guitar tabs, which come with no guarantee of musical quality and/or playability...! | ["def transpose(amount, tab):\n stack, tab = [], list(map(list, tab))\n for n, col in reversed(list(enumerate(zip(*tab)))):\n if any(map(str.isdigit, col)):\n stack.append(col)\n elif stack:\n frets = [''.join(r).strip('-') for r in zip(*reversed(stack))]\n frets = [fret and int(fret) + amount for fret in frets]\n if any(fret and not 0 <= fret <= 22 for fret in frets): return 'Out of frets!'\n frets = list(map(str, frets))\n pad = max(map(len, frets))\n for row, fret in zip(tab, frets):\n row[n+1: n+1+len(stack)] = str(fret).ljust(pad, '-')\n stack.clear()\n return list(map(''.join, tab))", "from itertools import groupby\nimport re\n\nclass OutOfFrets(Exception): pass\n\n\ndef convert(k,grp,amount):\n \n def convertOrRaise(m):\n v = int(m.group()) + amount\n if not (0 <= v < 23): raise OutOfFrets()\n return str(v)\n \n lst = list(map(''.join, list(zip(*grp))))\n if isinstance(k,str): return lst\n\n col = [re.sub(r'\\d+', convertOrRaise, l.strip('-')) for l in lst]\n maxL = max(list(map(len,col)))\n return [l.ljust(maxL, '-') for l in col]\n \n \ndef transpose(amount, tab):\n try: lst = [convert(k,g,amount) for k,g in groupby(list(zip(*tab)), key=lambda t: len(set(t))!=1 or t[0])]\n except OutOfFrets: return \"Out of frets!\"\n \n return list(map(''.join, list(zip(*lst))))\n", "import re\n\ndef transpose(amount, tab):\n \n # get start and end of all frets\n fret_pos = get_all_fret_positions(tab)\n # process each column that contains frets\n pos = 0\n tab_new = ['' for string in tab]\n for fret_start in sorted(fret_pos):\n fret_end = fret_pos[fret_start]\n # get all sub strings from one column\n col = [string[fret_start:fret_end] for string in tab]\n # apply amount to all frets\n col, col_width = apply_amount(col, amount)\n if col == 'Out of frets!':\n return 'Out of frets!'\n # adjust column width\n col = adjust_column_width(col, col_width)\n # add modified column back to tablature\n for i, row in enumerate(col):\n tab_new[i] = tab_new[i] + tab[i][pos:fret_start] + row\n pos = fret_end\n # add the part after the final fret\n for i, row in enumerate(col):\n tab_new[i] = tab_new[i] + tab[i][fret_end:]\n\n return tab_new\n\ndef get_all_fret_positions(tab):\n fret_pos = {}\n for string in tab:\n for match in re.finditer('[0-9]+', string):\n if match.start() in fret_pos.keys():\n if fret_pos[match.start()] < match.end():\n fret_pos[match.start()] = match.end()\n else:\n fret_pos[match.start()] = match.end()\n return fret_pos\n\ndef apply_amount(col, amount):\n col_width = 0\n for i, fret in enumerate(col):\n new_fret = re.search('[0-9]+', fret)\n if new_fret:\n new_fret = int(new_fret.group(0)) + amount\n if new_fret > 22 or new_fret < 0:\n return 'Out of frets!', None\n if len(str(new_fret)) > col_width:\n col_width = len(str(new_fret))\n col[i] = str(new_fret)\n return col, col_width\n\ndef adjust_column_width(col, col_width):\n for i, row in enumerate(col):\n if len(row) < col_width:\n col[i] = col[i] + '-' * (col_width - len(row))\n if len(row) > col_width:\n col[i] = col[i][:col_width - len(row)]\n return col\n\n\nt = transpose(2, [\n'e|--------5-7-----7-|-8-----8-2-----2-|-0---------0-----|-----------------|',\n'B|-10---5-----5-----|---5-------3-----|---1---1-----1---|-0-1-1-----------|',\n'G|----5---------5---|-----5-------2---|-----2---------2-|-0-2-2-----------|',\n'D|-12-------6-------|-5-------4-------|-3---------------|-----------------|',\n'A|------------------|-----------------|-----------------|-2-0-0---0--/8-7-|',\n'E|------------------|-----------------|-----------------|-----------------|']) \n\nprint(t)\n\n\"\"\"\nt = transpose(-1, [\n'e|-----------------|---------------|----------------|------------------|',\n'B|-----------------|---------------|----------------|------------------|',\n'G|--0---3---5----0-|---3---6-5-----|-0---3---5----3-|---0----(0)-------|',\n'D|--0---3---5----0-|---3---6-5-----|-0---3---5----3-|---0----(0)-------|',\n'A|-----------------|---------------|----------------|------------------|',\n'E|-----------------|---------------|----------------|------------------|'])\nt = transpose(+2, [\n'e|----------5/6-6-6-5/6-6-6-6-6-6------------------------------------|',\n'B|-------6--5/6-6-6-5/6-6-6-6-6-6-9-8-6-6----------------------------|',\n'G|---6h7--------------------------------6h7--------------------------|',\n'D|-8----------------------------------------8-6--8-8-8-8-8-8-8-8-----|',\n'A|-----------------------------------------------8-8-8-8-8-8-8-8-----|',\n'E|-------------------------------------------------------------------|'])\nprint(t)\n\"\"\"\n\n\"\"\"\n'e|-----------7/8-8-8-7/8-8-8-8-8-8-----------------------------------------------|',\n'B|--------8--7/8-8-8-7/8-8-8-8-8-8-11-10-8-8-------------------------------------|',\n'G|----8h9----------------------------------8h9-----------------------------------|',\n'D|-10------------------------------------------10-8--10-10-10-10-10-10-10-10-----|',\n'A|---------------------------------------------------10-10-10-10-10-10-10-10-----|',\n'E|-------------------------------------------------------------------------------|'\n\"\"\"", "import itertools\n\ndef transpose(amount, tab):\n shorten_dash = False\n for i in range(0,6):\n split_i = [\"\".join(y) for x,y in itertools.groupby(tab[i],key=str.isdigit)]\n trans = \"\"\n for gr in split_i:\n if gr.isnumeric():\n old = int(gr)\n new = old + amount\n if not 0 <= new <=22: return 'Out of frets!'\n trans += str(new)\n if (old < 10) and (new >= 10):\n ins = len(trans) - 1\n for j in range(0,6):\n if not j == i:\n if tab[j][ins-1:ins+1].isdigit(): shorten_dash = True\n if not shorten_dash:\n for j in range(0,6):\n if not j == i:\n tab[j] = tab[j][:ins] + \"-\" + tab[j][ins:]\n if (old >= 10) and (new < 10):\n ins = len(trans)\n add_dash = False\n for j in range(0,6):\n if not j == i:\n if tab[j][ins-1:ins+1].isdigit(): add_dash = True\n if add_dash:\n trans += \"-\"\n else:\n for j in range(0,6):\n if not j == i:\n tab[j] = tab[j][:ins] + tab[j][ins+1:]\n else:\n if shorten_dash:\n gr = gr[1:]\n shorten_dash = False\n trans += gr\n tab[i] = trans\n return tab", "def transpose(amount, tab):\n col_tab = list(map(list, zip(*tab)))\n\n for i, j in enumerate(col_tab):\n double = False\n for a in range(len(j)):\n if col_tab[i][a].isdigit() and col_tab[i+1][a].isdigit():\n double = True\n col_tab[i][a] = col_tab[i][a] + col_tab[i+1][a]\n\n if double:\n col_tab.remove(col_tab[i+1])\n\n for i, j in enumerate(col_tab):\n for a in range(len(j)):\n if j[a].isdigit(): \n new_note = int(j[a]) + amount\n if new_note < 0 or new_note > 22:\n return 'Out of frets!'\n else:\n col_tab[i][a] = str(new_note)\n\n for j, k in enumerate(col_tab):\n if any(len(x) > 1 for x in k):\n col_tab[j] = [i + '-' if len(i) < 2 else i for i in k]\n \n return [''.join(j) for i, j in enumerate(list(map(list, zip(*col_tab))))]", "def transpose(amount, tab):\n position = []\n position_neg = False\n result = []\n for line in tab:\n res = ''\n for counter, letter in enumerate(line):\n if letter.isdigit():\n if line[counter-1].isdigit():\n continue\n if line[counter+1].isdigit():\n if (int(letter+line[counter+1]) + amount) <= 22:\n res += str(int(letter+line[counter+1]) + amount)\n if len(str(int(letter+line[counter+1]) + amount)) == 1:\n position.append(counter)\n position_neg = True\n else:\n return 'Out of frets!'\n else:\n if len(str(int(letter) + amount)) == 2:\n if int(letter) + amount < 0:\n return 'Out of frets!'\n res += str(int(letter) + amount)\n position.append(counter)\n else:\n res += str(int(letter) + amount)\n else:\n res += letter\n result.append(res)\n\n position = list(set(position))\n position.sort()\n for counter, line in enumerate(result):\n added = 0\n for insert in position:\n if not position_neg:\n double_in_col = False\n for line2 in tab:\n if line2[insert].isdigit() and line2[insert + 1].isdigit():\n double_in_col = True\n if double_in_col:\n if result[counter][insert + added].isdigit():\n if result[counter][insert + added + 1].isdigit():\n if not tab[counter][insert + 1].isdigit():\n result[counter] = result[counter][:insert + added + 2] + result[counter][insert + added + 3:]\n else:\n if result[counter][insert+added].isdigit():\n if result[counter][insert+added+1].isdigit():\n if tab[counter][insert+1].isdigit():\n result[counter] = result[counter][:insert+added+2] +'-'+ result[counter][insert+added+2:]\n else:\n result[counter] = result[counter][:insert+added+1] +'-'+ result[counter][insert+added+1:]\n else:\n result[counter] = result[counter][:insert + added + 1] + '-' + result[counter][insert + added + 1:]\n added += 1\n else:\n double_in_col = False\n for line2 in result:\n if line2[insert+added].isdigit() and line2[insert+1+added].isdigit():\n double_in_col=True\n if double_in_col:\n if result[counter][insert + added].isdigit():\n if not result[counter][insert + added + 1].isdigit():\n if tab[counter][insert + 1].isdigit():\n result[counter] = result[counter][:insert + added + 1] + '-' + result[counter][insert + added + 1:]\n else:\n if result[counter][insert + added].isdigit():\n if not result[counter][insert + added + 1].isdigit():\n if tab[counter][insert + 1].isdigit():\n added -= 1\n continue\n result[counter] = result[counter][:insert + added + 2] + result[counter][insert + added + 3:]\n added -= 1\n return result", "\ndef transpose(amount, tab): \n resultTab = ['' for tabStr in tab]\n numChars = set(char for char in '0123456789')\n \n i = 0\n while i < len(tab[0]):\n for tabNum, tabStr in enumerate(tab):\n try:\n valStr = tabStr[i]\n \n # Are we looking at the second character of a two character number\n if not (i > 0 and valStr in numChars and tabStr[i-1] in numChars): \n \n # If the next character is a number to complete a two character number\n if valStr is not '-' and i+1 < len(tabStr) and tabStr[i+1] in numChars:\n valStr += tabStr[i+1]\n\n val = int(valStr)\n transposedVal = val + amount\n\n if transposedVal > 22 or transposedVal < 0:\n return 'Out of frets!'\n\n resultTab[tabNum] += str(transposedVal)\n \n except ValueError:\n resultTab[tabNum] += tabStr[i]\n \n maxLineLength = max([len(s) for s in resultTab])\n minLineLength = min([len(s) for s in resultTab])\n\n shouldTrim = False\n if maxLineLength != minLineLength:\n # This happens if the input string had a two character number that went down to a one\n # character number after the transpose\n shouldTrim = all([ (len(s) == minLineLength or s[len(s)-1] == '-') for s in resultTab])\n if shouldTrim:\n i += 1\n \n \n for resTabNum, resTabStr in enumerate(resultTab):\n if shouldTrim:\n resultTab[resTabNum] = (resTabStr)[0:minLineLength]\n resultTab[resTabNum] = (resTabStr + '-')[0:maxLineLength]\n \n i += 1\n \n return resultTab\n", "import re\n\nempty = [''] * 6\nseparator = ['-'] * 6\nbar = ['|'] * 6\n\ndef transpose(amount, tab):\n\n # \"And if you listen very hard\n # The tune will come to you at last...\"\n\n # -- Stairway to Heaven (1971)\n\n try:\n result = empty\n chunk = empty\n\n for i in range(len(tab[0])):\n column = get_column(tab, i)\n chunk = merge(chunk, column)\n \n if chunk == separator or chunk == bar:\n result = merge(result, chunk)\n chunk = empty\n elif column == separator:\n recalculated = recalculate(amount, chunk)\n result = merge(result, recalculated)\n chunk = empty\n\n return result\n except OutOfFretsException as oof:\n return str(oof)\n\ndef get_column(tab, column_idx):\n return [tab[string][column_idx] for string in range(0, 6)]\n\ndef merge(left, right):\n return [left[i] + right[i] for i in range(0, 6)]\n\ndef recalculate(amount, chunk):\n recalculated = [shift(string, amount) for string in chunk]\n max_length = max([len(s) for s in recalculated])\n padded = [string.ljust(max_length, '-') for string in recalculated]\n return shrink(padded)\n\ndef shrink(chunk):\n new_chunk = empty\n for i in range(len(chunk[0])):\n current_column = get_column(chunk, i)\n next_column = get_column(chunk, i + 1) if i + 1 < len(chunk[0]) else None\n\n if current_column == separator and next_column == separator:\n continue\n else:\n new_chunk = merge(new_chunk, current_column)\n\n return new_chunk\n\ndef shift(string, amount):\n tokens = re.findall(r'[^\\d]*[0-9]+[^\\d]*', string)\n if len(tokens) > 0:\n numbers = [int(re.findall(r'[0-9]+', t)[0]) for t in tokens]\n shifted = [(n, n + amount) for n in numbers]\n if (any(s[1] > 22 or s[1] < 0 for s in shifted)):\n raise OutOfFretsException()\n else:\n replaced = [tokens[i].replace(str(shifted[i][0]), str(shifted[i][1])) for i in range(len(tokens))]\n return \"\".join(replaced)\n else:\n return string\n\nclass OutOfFretsException(Exception):\n def __init__(self):\n Exception.__init__(self, 'Out of frets!')", "def write_bar(new_bar, beat, amount): \n new_beat = [str(int(fret) + amount) if fret.isnumeric() else fret for fret in beat]\n values = [int(fret) for fret in new_beat if fret.lstrip('-').isnumeric()] \n if values and (max(values) > 22 or min(values) <= 0): \n raise ValueError('Out of frets!') \n formatted_beat = [beat.ljust(len(max(new_beat, key=len)), '-') for beat in new_beat]\n for beat in range(len(formatted_beat)): \n new_bar[beat] += formatted_beat[beat] \n return new_bar \n \ndef transpose_bar(amount, bar): \n new_bar = [''] * 6 \n frets = [''] * 6 \n joined = False \n for beat in range(len(bar[0])): \n if not joined: \n previous_beat = frets \n else: \n previous_beat = [''] * 6 \n joined = False \n frets = [gen[beat] for gen in bar] \n for fret in range(len(frets)): \n if frets[fret].isnumeric() and previous_beat[fret].isnumeric(): \n previous_beat[fret] += frets[fret] \n joined = True \n new_bar = write_bar(new_bar, previous_beat, amount) \n \n if not joined: \n new_bar = write_bar(new_bar, frets, amount) \n \n return new_bar \n \n \ndef transpose(amount, tab): \n string_bars = [gen.split('|')[1:-1] for gen in tab] \n bars = list(zip(*string_bars)) \n new_bars = [('e','B','G','D','A','E'),] \n try: \n for bar in bars: \n new_bars.append(transpose_bar(amount, bar)) \n new_bars.append([''] * 6) \n transposed = list(zip(*new_bars)) \n return ['|'.join(gen) for gen in transposed] \n except ValueError as e: \n return str(e) ", "class EndException(Exception):\n pass\n\nclass DoneAccumulatingException(Exception):\n pass\n\nclass OutOfFretsException(Exception):\n pass\n\ndef get_column(array, index):\n ret = []\n try:\n for line in array:\n ret.append(line[index])\n return ret\n except IndexError:\n raise EndException()\n \n \ndef add_to_tab(tab, column):\n for i, value in enumerate(column):\n tab[i] += value\n\n\ndef accumulate(accumulate_array, column):\n if set(map(lambda x: str.isnumeric(x), column)) == {False}:\n raise DoneAccumulatingException()\n else:\n for i, value in enumerate(column):\n accumulate_array[i] += value\n\n\ndef adjust_accumulator(accumulator, adjustment):\n \n column_width = 0\n adjusted_values = []\n for item in accumulator:\n item = item.strip('-')\n if str.isnumeric(item):\n new_value = int(item) + adjustment\n if new_value < 0 or new_value > 22:\n raise OutOfFretsException()\n item = str(new_value)\n adjusted_values.append(item)\n if len(item) > column_width:\n column_width = len(item)\n\n new_accumulator = [x + ('-' * (column_width - len(x))) for x in adjusted_values]\n return new_accumulator\n\ndef transpose(amount, tab):\n\n idx = 0\n new_tab = [''] * 6\n aa = [''] * 6\n while True:\n try:\n column = get_column(tab, idx)\n except EndException:\n break\n \n try:\n accumulate(aa, column)\n except DoneAccumulatingException:\n try:\n aa = adjust_accumulator(aa, amount)\n except OutOfFretsException:\n return \"Out of frets!\"\n\n add_to_tab(new_tab, aa)\n add_to_tab(new_tab, column)\n aa = [''] * 6\n \n #print(\"UPDATED TAB\")\n #for item in new_tab:\n # print(item[-20:])\n\n idx += 1\n \n return new_tab"] | {"fn_name": "transpose", "inputs": [[2, ["e|-------5-7-----7-|-8-----8-2-----2-|-0---------0-----|-----------------|", "B|-----5-----5-----|---5-------3-----|---1---1-----1---|-0-1-1-----------|", "G|---5---------5---|-----5-------2---|-----2---------2-|-0-2-2-----------|", "D|-7-------6-------|-5-------4-------|-3---------------|-----------------|", "A|-----------------|-----------------|-----------------|-2-0-0---0--/8-7-|", "E|-----------------|-----------------|-----------------|-----------------|"]], [2, ["e|-----------------------------------------------------------------------------|", "B|---------------------------8-----------------------8-------------------------|", "G|-------------------------7-----------------------7---------------------------|", "D|----8-----8-----8----8/9-------7-7/5-0--------/9-----7-7/5-0-----------------|", "A|------------------------------------------5/7------------------5/7-----------|", "E|-6-----6-----6----6---------------------0--------------------0---------------|"]], [-4, ["e|--------------15----14-----|--------------15----14-----|", "B|-----15--------------------|-----15--------------------|", "G|--------14-12----14----14--|--------14-12----14----14--|", "D|--12-----------------------|--12-----------------------|", "A|---------------------------|---------------------------|", "E|---------------------------|---------------------------|"]], [2, ["e|----------5/6-6-6-5/6-6-6-6-6-6------------------------------------|", "B|-------6--5/6-6-6-5/6-6-6-6-6-6-9-8-6-6----------------------------|", "G|---6h7--------------------------------6h7--------------------------|", "D|-8----------------------------------------8-6--8-8-8-8-8-8-8-8-----|", "A|-----------------------------------------------8-8-8-8-8-8-8-8-----|", "E|-------------------------------------------------------------------|"]], [-1, ["e|-----------------|---------------|----------------|------------------|", "B|-----------------|---------------|----------------|------------------|", "G|--0---3---5----0-|---3---6-5-----|-0---3---5----3-|---0----(0)-------|", "D|--0---3---5----0-|---3---6-5-----|-0---3---5----3-|---0----(0)-------|", "A|-----------------|---------------|----------------|------------------|", "E|-----------------|---------------|----------------|------------------|"]], [9, ["E----------------------|------------------------------------------------|", "B----------------------|------------------------------------------------|", "G----------11--13--13b-|----------11--13--13b----------13b--------------|", "D------14--------------|------14---------------14-----------14----------|", "A--14------------------|--14-----------------------14-----------14-12---|", "E----------------------|------------------------------------------------|"]]], "outputs": [[["e|-------7-9-----9-|-10-----10-4-----4-|-2---------2-----|------------------|", "B|-----7-----7-----|----7--------5-----|---3---3-----3---|-2-3-3------------|", "G|---7---------7---|------7--------4---|-----4---------4-|-2-4-4------------|", "D|-9-------8-------|-7---------6-------|-5---------------|------------------|", "A|-----------------|-------------------|-----------------|-4-2-2---2--/10-9-|", "E|-----------------|-------------------|-----------------|------------------|"]], [["e|-------------------------------------------------------------------------------------|", "B|--------------------------------10------------------------10-------------------------|", "G|------------------------------9-------------------------9----------------------------|", "D|----10-----10-----10----10/11--------9-9/7-2--------/11------9-9/7-2-----------------|", "A|------------------------------------------------7/9--------------------7/9-----------|", "E|-8------8------8-----8------------------------2----------------------2---------------|"]], [["e|------------11----10-----|------------11----10-----|", "B|----11-------------------|----11-------------------|", "G|-------10-8----10----10--|-------10-8----10----10--|", "D|--8----------------------|--8----------------------|", "A|-------------------------|-------------------------|", "E|-------------------------|-------------------------|"]], [["e|-----------7/8-8-8-7/8-8-8-8-8-8-----------------------------------------------|", "B|--------8--7/8-8-8-7/8-8-8-8-8-8-11-10-8-8-------------------------------------|", "G|----8h9----------------------------------8h9-----------------------------------|", "D|-10------------------------------------------10-8--10-10-10-10-10-10-10-10-----|", "A|---------------------------------------------------10-10-10-10-10-10-10-10-----|", "E|-------------------------------------------------------------------------------|"]], ["Out of frets!"], ["Out of frets!"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 22,159 |
def transpose(amount, tab):
|
7c679f8a3fc18ba16f186e47016632e7 | UNKNOWN | # Background
My TV remote control has arrow buttons and an `OK` button.
I can use these to move a "cursor" on a logical screen keyboard to type words...
# Keyboard
The screen "keyboard" layout looks like this
#tvkb {
width : 400px;
border: 5px solid gray; border-collapse: collapse;
}
#tvkb td {
color : orange;
background-color : black;
text-align : center;
border: 3px solid gray; border-collapse: collapse;
}
abcde123
fghij456
klmno789
pqrst.@0
uvwxyz_/
aASP
* `aA` is the SHIFT key. Pressing this key toggles alpha characters between UPPERCASE and lowercase
* `SP` is the space character
* The other blank keys in the bottom row have no function
# Kata task
How many button presses on my remote are required to type the given `words`?
## Notes
* The cursor always starts on the letter `a` (top left)
* The alpha characters are initially lowercase (as shown above)
* Remember to also press `OK` to "accept" each letter
* Take a direct route from one letter to the next
* The cursor does not wrap (e.g. you cannot leave one edge and reappear on the opposite edge)
* Although the blank keys have no function, you may navigate through them if you want to
* Spaces may occur anywhere in the `words` string.
* Do not press the SHIFT key until you need to. For example, with the word `e.Z`, the SHIFT change happens **after** the `.` is pressed (not before)
# Example
words = `Code Wars`
* C => `a`-`f`-`k`-`p`-`u`-`aA`-OK-`U`-`P`-`K`-`F`-`A`-`B`-`C`-OK = 14
* o => `C`-`H`-`M`-`R`-`W`-`V`-`U`-`aA`-OK-`SP`-`v`-`q`-`l`-`m`-`n`-`o`-OK = 16
* d => `o`-`j`-`e`-`d`-OK = 4
* e => `d`-`e`-OK = 2
* space => `e`-`d`-`c`-`b`-`g`-`l`-`q`-`v`-`SP`-OK = 9
* W => `SP`-`aA`-OK-`SP`-`V`-`W`-OK = 6
* a => `W`-`V`-`U`-`aA`-OK-`u`-`p`-`k`-`f`-`a`-OK = 10
* r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6
* s => `r`-`s`-OK = 2
Answer = 14 + 16 + 4 + 2 + 9 + 6 + 10 + 6 + 2 = 69
*Good Luck!
DM.*
Series
* TV Remote
* TV Remote (shift and space)
* TV Remote (wrap)
* TV Remote (symbols) | ["import re\n\nKEYBOARD = \"abcde123fghij456klmno789pqrst.@0uvwxyz_/* \"\nMAP = {c: (i//8, i%8) for i,c in enumerate(KEYBOARD)}\n\n\ndef manhattan(*pts): return 1 + sum( abs(z2-z1) for z1,z2 in zip(*pts))\n\ndef toggle(m):\n ups, end = m.group(1), m.group(2)\n off = '*' * bool(end)\n return f'*{ups.lower()}{off}{end}' # Toggle Shift ON if uppercase presents, and then OFF if lowercase after\n\ndef tv_remote(words):\n reWords = re.sub(r'([A-Z][^a-z]*)([a-z]?)', toggle, words)\n return sum( manhattan(MAP[was], MAP[curr]) for was,curr in zip('a'+reWords, reWords))\n", "raw = 'abcde123fghij456klmno789pqrst.@0uvwxyz_/'\nlayout = {char: divmod(i, 8) for i, char in enumerate(raw)}\nlayout['SHIFT'] = (5, 0)\nlayout[' '] = (5,1)\n\ndef distance(a, b):\n return abs(a[0] - b[0]) + abs(a[1] - b[1]) + 1\n\n\nclass Keyboard:\n def __init__(self):\n self.total = 0\n self.cap = False\n self.current = (0,0)\n \n def hit_shift(self):\n self.total += distance(self.current, layout['SHIFT'])\n self.cap = not self.cap\n self.current = layout['SHIFT']\n \n def next_letter(self, letter):\n if letter.isupper() and not self.cap:\n self.hit_shift()\n elif letter.islower() and self.cap:\n self.hit_shift()\n \n self.total += distance(self.current, layout[letter.lower()])\n self.current = layout[letter.lower()]\n \n def solve(self, word):\n for char in word:\n self.next_letter(char)\n\n\ndef tv_remote(words):\n k = Keyboard()\n k.solve(words)\n return k.total\n", "import re\n\ndef tv_remote(words):\n letters = {c: (x, y)\n for y, row in enumerate((\n \"abcde123\",\n \"fghij456\",\n \"klmno789\",\n \"pqrst.@0\",\n \"uvwxyz_/\",\n \"\u21e7 \"))\n for x, c in enumerate(row)}\n words = re.sub(r'((?:^|[a-z])[^A-Z]*)([A-Z])', r'\\1\u21e7\\2', words)\n words = re.sub(r'([A-Z][^a-z]*)([a-z])', r'\\1\u21e7\\2', words)\n words = words.lower()\n return sum(\n abs(letters[c1][0] - letters[c2][0]) +\n abs(letters[c1][1] - letters[c2][1]) + 1\n for c1, c2 in zip(\"a\" + words, words))", "keyboard = (\"abcde123\", \"fghij456\", \"klmno789\", \"pqrst.@0\", \"uvwxyz_/\", \"# \")\nD = {c:(i,j) for i,row in enumerate(keyboard) for j,c in enumerate(row)}\n\ndef tv_remote(words):\n i = j = up = res = 0\n for c in words:\n if c.isalpha() and c.isupper() != up:\n k, l = D['#']\n res += abs(i-k) + abs(j-l) + 1\n i, j, up = k, l, 1-up\n k, l = D[c.lower()]\n res += abs(i-k) + abs(j-l) + 1\n i, j = k, l\n return res", "def tv_remote(words):\n pad = [\"abcde123\", \"fghij456\", \"klmno789\", \"pqrst.@0\", \"uvwxyz_/\", \"S \"]\n index = {c: (x, y) for x, lst in enumerate(pad) for y, c in enumerate(lst)}\n res = 0\n pos = (0, 0)\n caps = False\n for char in words:\n if char.isalpha() and (char.isupper() != caps):\n res += (abs(pos[0] - index[\"S\"][0]) + abs(pos[1] - index[\"S\"][1])) + 1\n pos = index[\"S\"]\n caps = not caps\n \n char = char.lower()\n res += (abs(pos[0] - index[char][0]) + abs(pos[1] - index[char][1])) + 1\n pos = index[char]\n return res", "from collections import namedtuple\n\n\ndef tv_remote(word: str):\n remote = (\n 'a', 'b', 'c', 'd', 'e', '1', '2', '3',\n 'f', 'g', 'h', 'i', 'j', '4', '5', '6',\n 'k', 'l', 'm', 'n', 'o', '7', '8', '9',\n 'p', 'q', 'r', 's', 't', '.', '@', '0',\n 'u', 'v', 'w', 'x', 'y', 'z', '_', '/',\n '', ' '\n )\n Position = namedtuple('Position', 'y x')\n shift, shift_pressed = Position(5, 0), False\n\n prev = Position(0, 0)\n button_presses = 0\n for letter in word:\n if letter.isalpha() and letter.isupper() != shift_pressed:\n button_presses += abs(prev.y - shift.y) + abs(prev.x - shift.x) + 1\n prev, shift_pressed = shift, not shift_pressed\n\n cur = Position(*divmod(remote.index(letter.lower()), 8))\n button_presses += abs(prev.y - cur.y) + abs(prev.x - cur.x) + 1\n prev = cur\n\n return button_presses", "def tv_remote(word):\n caps, cases, shift = coords[\"\u2191\"], (str.isupper, str.islower), 0\n moves, current = 0, (0, 0)\n for char in word:\n target = coords[char.lower()]\n if cases[shift](char):\n moves, current = 1 + moves + distance(current, caps), caps\n shift = 1 - shift\n moves, current = moves + distance(current, target), target\n return moves + len(word)\n\nkeyboard = (\"abcde123\", \"fghij456\", \"klmno789\", \"pqrst.@0\", \"uvwxyz_/\", \"\u2191 \")\ncoords = {char: (line.index(char), y) for y, line in enumerate(keyboard) for char in line}\n\ndef distance(pos1, pos2):\n return abs(pos2[0] - pos1[0]) + abs(pos2[1] - pos1[1])", "def tv_remote(word):\n matrix = [\n ['a', 'b', 'c', 'd', 'e', '1', '2', '3'],\n ['f', 'g', 'h', 'i', 'j', '4', '5', '6'],\n ['k', 'l', 'm', 'n', 'o', '7', '8', '9'],\n ['p', 'q', 'r', 's', 't', '.', '@', '0'],\n ['u', 'v', 'w', 'x', 'y', 'z', '_', '/'],\n ['aA', ' '],\n ]\n\n actions = ([0, 0],)\n upper_mode = False\n press_ok = 0\n func = lambda x, y: (abs(x[0]-y[0]) + abs(x[1]-y[1]))\n\n for char in word:\n for i in range(6):\n if char.lower() in matrix[i]:\n if char.isupper() and not upper_mode:\n actions += ([5, 0],)\n upper_mode = True\n press_ok += 1\n actions += ([i, matrix[i].index(char.lower())],)\n press_ok += 1\n elif char.isupper() and upper_mode:\n actions += ([i, matrix[i].index(char.lower())],)\n press_ok += 1\n elif char.islower() and upper_mode:\n actions += ([5, 0],)\n upper_mode = False\n press_ok += 1\n actions += ([i, matrix[i].index(char.lower())],)\n press_ok += 1\n elif char.islower() and not upper_mode:\n actions += ([i, matrix[i].index(char.lower())],)\n press_ok += 1\n else:\n actions += ([i, matrix[i].index(char.lower())],)\n press_ok += 1\n\n return sum([func(i[0], i[1]) for i in list(zip(actions, actions[1:]))]) + press_ok", "def tv_remote(s):\n d = {y: (i, x) for i, j in enumerate([\"abcde123\", \"fghij456\", \"klmno789\", \"pqrst.@0\", \"uvwxyz_/\", \"# *!$%^&\"]) for x, y in enumerate(j)}\n does = lambda a, b: (abs(d[a][0] - d[b][0]) + (abs(d[a][1] - d[b][1]))) + 1\n status, c = False, 0\n for i, j in zip(s, 'a' + s):\n t, t1 = i.lower(), j.lower()\n if i.isupper():\n if not status : t1, status, c = \"#\", 1, c + does('#', t1)\n elif i.islower():\n if status : t1, status, c = '#', 0, c + does('#', t1)\n c += does(t1, t) \n return c", "D = {v:(r, c) for r, row in enumerate('''abcde123 fghij456 klmno789 pqrst.@0 uvwxyz_/'''.split() +[' ']) for c, v in enumerate(row)}\n\ndef tv_remote(words):\n t, lr, lc, lower = 0, 0, 0, True\n\n for e in words:\n if e.isalpha() and lower != e.islower():\n t, lr, lc = move(t, lr, lc, 5, 0)\n lower = not lower\n t, lr, lc = move(t, lr, lc, *D[e.lower()])\n return t\n \ndef move(t, lr, lc, r, c):\n return t + abs(lr - r) + abs(lc - c) + 1, r, c"] | {"fn_name": "tv_remote", "inputs": [["Code Wars"], ["does"], ["your"], ["solution"], ["work"], ["for"], ["these"], ["words"], ["DOES"], ["YOUR"], ["SOLUTION"], ["WORK"], ["FOR"], ["THESE"], ["WORDS"], ["Does"], ["Your"], ["Solution"], ["Work"], ["For"], ["These"], ["Words"], ["A"], ["AADVARKS"], ["A/A/A/A/"], ["1234567890"], ["MISSISSIPPI"], ["a"], ["aadvarks"], ["a/a/a/a/"], ["mississippi"], ["Xoo ooo ooo"], ["oXo ooo ooo"], ["ooX ooo ooo"], ["ooo Xoo ooo"], ["ooo oXo ooo"], ["ooo ooX ooo"], ["ooo ooo Xoo"], ["ooo ooo oXo"], ["ooo ooo ooX"], ["The Quick Brown Fox Jumps Over A Lazy Dog."], ["Pack My Box With Five Dozen Liquor Jugs."], [""], [" "], [" "], [" x X "]], "outputs": [[69], [16], [23], [33], [20], [12], [27], [25], [27], [26], [38], [23], [21], [32], [28], [40], [37], [49], [30], [28], [41], [35], [12], [45], [96], [28], [42], [1], [34], [85], [35], [57], [65], [53], [53], [65], [53], [53], [65], [53], [306], [290], [0], [7], [9], [34]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 7,799 |
def tv_remote(words):
|
1100c9639fc0210f779b68d99e81a396 | UNKNOWN | A function receives a certain numbers of integers ```n1, n2, n3 ..., np```(all positive and different from 0) and a factor ```k, k > 0```
The function rearranges the numbers ```n1, n2, ..., np``` in such order that generates the minimum number concatenating the digits and this number should be divisible by ```k```.
The order that the function receives their arguments is:
```python
rearranger(k, n1, n2, n3,....,np)
```
## Examples
```python
rearranger(4, 32, 3, 34, 7, 12) == "Rearrangement: 12, 3, 34, 7, 32 generates: 12334732 divisible by 4"
rearranger(10, 32, 3, 34, 7, 12) == "There is no possible rearrangement"
```
If there are more than one possible arrengement for the same minimum number, your code should be able to handle those cases:
```python
rearranger(6, 19, 32, 2, 124, 20, 22) == "Rearrangements: 124, 19, 20, 2, 22, 32 and 124, 19, 20, 22, 2, 32 generates: 124192022232 divisible by 6"
```
The arrangements should be in sorted order, as you see: `124, 19, 20, 2, 22, 32` comes first than `124, 19, 20, 22, 2, 32`.
Have an enjoyable time!
(Thanks to `ChristianE.Cooper` for his contribution to this kata) | ["from itertools import permutations\n\ndef rearranger(k, *args):\n perms = permutations(map(str, args), len(args))\n divisible_by_k = filter(lambda x: int(''.join(x)) % k == 0, perms)\n try:\n rearranged = min(divisible_by_k, key=lambda x: int(''.join(x)))\n return 'Rearrangement: {} generates: {} divisible by {}'.format(', '.join(rearranged), ''.join(rearranged), k)\n except ValueError:\n return \"There is no possible rearrangement\"", "import itertools\ndef rearranger(k, *args):\n arrengment, prep = list(set(itertools.permutations([x for x in args]))), []\n for key, char in enumerate(arrengment):\n seriesOfNumbers = [str(x) for x in arrengment[key]]\n number = int(''.join([x for x in ''.join(str(arrengment[key])) if x.isdigit()]))\n if number%k==0:\n prep.append([seriesOfNumbers,number])\n try:\n minimum = min([x[1] for x in prep])\n answer = [x[0] for x in prep if x[1]==minimum]+[x[1] for x in prep if x[1]==minimum]\n if len(answer)==0: return 'There is no possible rearrangement'\n elif len(answer)==2: return 'Rearrangement: %s generates: %d divisible by %d'%(', '.join([x for x in answer[0]]),\n [y for x,y in enumerate(answer)if x%2 !=0][0], k)\n elif len(answer)>2: return \"Rearrangements: %s and %s generates: %d divisible by %d\"%(\n ', '.join([x for x in answer[0]]), ', '.join([x for x in answer[1]]), \n [y for x,y in enumerate(answer)][2], k)\n except ValueError:\n return 'There is no possible rearrangement'", "from itertools import permutations\n\ndef rearranger(k, *args):\n arguments = []\n numbers = []\n min_num = 10 ** 50\n for arg in [*args]:\n arguments.append(str(arg))\n for perm in permutations(arguments):\n num = int(\"\".join(perm))\n if num % k == 0:\n if num == min_num and not perm in numbers:\n numbers.append(perm)\n if num < min_num:\n min_num = num\n numbers = [perm]\n \n if len(numbers) == 0:\n answer = \"There is no possible rearrangement\"\n elif len(numbers) == 1:\n nums = ', '.join(numbers[0])\n answer = f\"Rearrangement: {nums} generates: {min_num} divisible by {k}\"\n elif len(numbers) == 2:\n nums1 = ', '.join(numbers[0])\n nums2 = ', '.join(numbers[1])\n answer = f\"Rearrangements: {nums1} and {nums2} generates: {min_num} divisible by {k}\"\n return answer", "from itertools import permutations as p\n\ndef rearranger(k, *args):\n res, u, t = 1E200, len(args),(0,0)\n for i in p(args,u):\n a = int(''.join(map(str,i)))\n if a % k == 0:\n if a < res:\n res = a\n t = i\n if a == res:\n if i < t:\n t = i\n if t == (0,0):\n return \"There is no possible rearrangement\"\n else:\n return \"Rearrangement: \" + str(t)[1:-1] + \" generates: \" + str(res) + \" divisible by \" + str(k)", "from itertools import permutations\n\ndef rearranger(k, *args):\n options = sorted(permutations(args, len(args)), key=lambda option: (''.join(str(x) for x in option), option))\n res = \"There is no possible rearrangement\"\n for option in options: \n aux = int(''.join(str(x) for x in option))\n if aux%k==0: \n res = \"Rearrangement: {} generates: {} divisible by {}\".format(', '.join(str(x) for x in option), aux, k)\n break\n return res\n", "from itertools import permutations\ndef rearranger(k, *args):\n min_d=[10e50,None]\n for p in permutations(args):\n n=int(''.join(str(x) for x in p))\n if n%k==0:\n if n<min_d[0]:\n min_d=[n,set({', '.join(map(str,p))})]\n elif n==min_d[0]:\n min_d[1].add(', '.join(map(str,p)))\n if min_d[1] is None:\n return 'There is no possible rearrangement'\n return 'Rearrangement: {0} generates: {1} divisible by {2}'.format(' and '.join(min_d[1]),min_d[0],k)", "from itertools import permutations\nfrom collections import defaultdict\n\ndef rearranger(k, *args):\n vals, D = map(str, args), defaultdict(set)\n for p in permutations(vals):\n x = int(''.join(p))\n if not x % k: D[x].add(p)\n try:\n mini = min(D)\n res = D[mini]\n return f\"Rearrangement{'s' if len(res) > 1 else ''}: {' and '.join(map(', '.join, res))} generates: {mini} divisible by {k}\"\n except:\n return \"There is no possible rearrangement\"", "from itertools import permutations\n\ndef rearranger(k, *args):\n res = set([(int(''.join(map(str, p))), p) for p in permutations(args) if int(''.join(map(str, p))) % k == 0])\n if res:\n res = sorted(res)\n ans = []\n min_val = res[0][0]\n for i, p in res:\n if i != min_val:\n break\n ans.append(f'{\", \".join(map(str, p))}')\n return f'Rearrangement{\"s\" if len(ans) > 1 else \"\"}: {\" and \".join(ans)} {\" \" if len(ans) > 1 else \"\"}generates: {min_val} divisible by {k}'\n return 'There is no possible rearrangement'", "import itertools\n\ndef from_list_to_string(A):\n st = ''\n for x in A:\n st += str(x)\n return st\n\ndef from_list_to_string_with_comma(A):\n st = ''\n for x in A:\n st = st + str(x) + ', '\n return st[:-2]\n\ndef rearranger(k, *args):\n min = float(\"inf\")\n index = None\n list_of_permutations = list(itertools.permutations(args))\n for i in range(len(list_of_permutations)):\n tmp = int(from_list_to_string(list_of_permutations[i]))\n if tmp % k == 0 and tmp < min:\n min = tmp\n index = i\n if index == None:\n return \"There is no possible rearrangement\"\n else:\n return \"Rearrangement: \" + str(from_list_to_string_with_comma(list_of_permutations[index])) + \" generates: \" + str(min) + \" divisible by \" + str(k)"] | {"fn_name": "rearranger", "inputs": [[4, 32, 3, 34, 7, 12], [10, 32, 3, 34, 7, 12]], "outputs": [["Rearrangement: 12, 3, 34, 7, 32 generates: 12334732 divisible by 4"], ["There is no possible rearrangement"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 6,091 |
def rearranger(k, *args):
|
7effbb0404215ee0e02505f1796ae6d5 | UNKNOWN | >When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description:
John learns to play poker with his uncle. His uncle told him: Poker to be in accordance with the order of "2 3 4 5 6 7 8 9 10 J Q K A". The same suit should be put together. But his uncle did not tell him the order of the four suits.
Give you John's cards and Uncle's cards(two string `john` and `uncle`). Please reference to the order of Uncle's cards, sorting John's cards.
# Examples
```
For Python:
Suits are defined as S, D, H, C.
sort_poker("D6H2S3D5SJCQSKC7D2C5H5H10SA","S2S3S5HJHQHKC8C9C10D4D5D6D7")
should return "S3SJSKSAH2H5H10C5C7CQD2D5D6"
sort_poke("D6H2S3D5SJCQSKC7D2C5H5H10SA","C8C9C10D4D5D6D7S2S3S5HJHQHK")
should return "C5C7CQD2D5D6S3SJSKSAH2H5H10"
``` | ["import re\nfrom collections import OrderedDict\nscale = \"2 3 4 5 6 7 8 9 10 J Q K A\".split(\" \")\ndef sort_poker(john, uncle):\n order = list(OrderedDict.fromkeys(re.findall(r\"([SDHC])[0-9JQKA]+\",uncle)))\n john = re.findall(r\"([SDHC])([0-9JQKA]+)\",john)\n return \"\".join(\"\".join(i) for i in sorted(john,key=lambda x : (order.index(x[0]),scale.index(x[1])) ))", "import re\ndef sort_poker(H, U, OD='2 3 4 5 6 7 8 9 10 J Q K A'.split()):\n ORDER = re.findall(r'(.)\\1*',re.sub(r'[\\dJQKA]','', U))\n return ''.join(sorted(re.findall(r'[SDHC](?:[23456789JQKA]|10)',H), key=lambda x:(ORDER.index(x[0]), OD.index(x[1:]))))", "order = lambda arr: {card[0]: i for i, card in enumerate(arr)}\nranks = order(\"2 3 4 5 6 7 8 9 10 J Q K A\".split())\nsuit_table = {ord(suit): ' ' + suit for suit in 'SDHC'}\nsplit_hand = lambda hand: hand.translate(suit_table).split()\n\ndef sort_poker(john, uncle):\n suits = order(split_hand(uncle))\n return ''.join(sorted(split_hand(john),\n key=lambda card: (suits[card[0]], ranks[card[1]])))", "def sort_poker(john, uncle):\n card_order = \"23456789TJQKA\"\n suit_order = [('S', uncle.index('S')), ('D', uncle.index('D')), ('H', uncle.index('H')), ('C',uncle.index('C'))]\n suit_order = [X[0] for X in sorted(suit_order, key=lambda x : x[1])]\n john = john.replace('10', 'T')\n john = [john[i:i+2] for i in range(0, len(john), 2)]\n john = sorted(john, key=lambda x: (suit_order.index(x[0]),card_order.index(x[1])))\n return ''.join(john).replace('T', '10')", "S=lambda h,t={ord(s):' '+s for s in 'SDHC'}:h.translate(t).split()\nsort_poker=lambda a,b:(lambda s,r:''.join(sorted(S(a),key=lambda c:(s[c[0]],r[c[1]])))\n)(*[{c[0]:i for i,c in enumerate(S(p))}for p in(b,\"2 3 4 5 6 7 8 9 10 J Q K A\")])", "def sort_poker(john, uncle):\n res=[]\n index=0\n while True:\n try:\n temp=john[index]+john[index+1]\n if john[index+1]==\"1\":\n temp+=john[index+2]\n index+=3\n else:\n index+=2\n res.append(temp)\n temp=\"\"\n except:\n break\n dict={}\n for i in \"SDHC\":\n dict[i]=uncle.index(i)\n rec=\"2 3 4 5 6 7 8 9 10 J Q K A\"\n dict2={}\n for i,j in enumerate(rec.split()):\n dict2[j]=i\n for i,j in enumerate(res):\n res[i]=list(j)\n if len(res[i])==3:\n res[i][1]=res[i][1]+res[i][2]\n res[i].pop()\n for i in range(len(res)):\n for j in range(i+1,len(res)):\n if dict2[res[j][1]]<dict2[res[i][1]]:\n temp=res[i]\n res[i]=res[j]\n res[j]=temp\n final=sorted(res, key=lambda x: (dict[x[0][0]]))\n return \"\".join(sum(final, []))", "import re\ndef sort_poker(john, uncle):\n SUITS = re.compile('[SHCD]')\n order = list(dict.fromkeys(SUITS.findall(uncle)))\n ord = {x:order.index(x) for x in order}\n john = re.findall('([CDHS])(\\d+|[JKQA])', john)\n suit = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'J':11, 'K':13, 'Q':12, 'A':14}\n a = [(ord[x[0]], suit[x[1]], str(x)) for x in john]\n a.sort(key= lambda x:x[1])\n a.sort(key=lambda x:x[0])\n return ''.join([x for x in ''.join([x[2] for x in a])if x.isalpha() or x.isnumeric()])\n\n", "def sort_poker(john, uncle):\n suits = ('S', 'D', 'H', 'C')\n values = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')\n get_value = lambda index, hand: hand[index + 1:index + 3] if hand[index + 1] == '1' else hand[index + 1]\n get_all_indexes = lambda suit, hand: [i for i in range(len(hand)) if hand.startswith(suit, i)]\n get_cards = lambda hand: {suit: [get_value(index, hand) for index in get_all_indexes(suit, hand)] for suit in suits}\n get_suit_rating = lambda hand: list(dict.fromkeys(symbol for symbol in hand if symbol in suits))\n johns_hand = sorted([(suit, sorted([card for card in value], key=lambda x: values.index(x)))\n for suit, value in list(get_cards(john).items())], key=lambda x: get_suit_rating(uncle).index(x[0]))\n return ''.join(''.join(suit[0] + value for value in suit[1]) for suit in johns_hand)\n", "import re\ndef sort_poker(john, uncle):\n j,s=re.findall(r'([SDHC])([0-9A-Z]0?)',john),''.join(re.findall('[SDHC]',uncle))\n n='2 3 4 5 6 7 8 9 10 J Q K A'\n return''.join(map(''.join, sorted(j,key=lambda c:(s.find(c[0]),n.find(c[1])))))"] | {"fn_name": "sort_poker", "inputs": [["D6H2S3D5SJCQSKC7D2C5H5H10SA", "S2S3S5HJHQHKC8C9C10D4D5D6D7"], ["D6H2S3D5SJCQSKC7D2C5H5H10SA", "C8C9C10D4D5D6D7S2S3S5HJHQHK"]], "outputs": [["S3SJSKSAH2H5H10C5C7CQD2D5D6"], ["C5C7CQD2D5D6S3SJSKSAH2H5H10"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,517 |
def sort_poker(john, uncle):
|
b465162e6f152d6931d8c070a7ed3a06 | UNKNOWN | ## Task
Create a function that given a sequence of strings, groups the elements that can be obtained by rotating others, ignoring upper or lower cases.
In the event that an element appears more than once in the input sequence, only one of them will be taken into account for the result, discarding the rest.
## Input
Sequence of strings. Valid characters for those strings are uppercase and lowercase characters from the alphabet and whitespaces.
## Output
Sequence of elements. Each element is the group of inputs that can be obtained by rotating the strings.
Sort the elements of each group alphabetically.
Sort the groups descendingly by size and in the case of a tie, by the first element of the group alphabetically.
## Examples
```python
['Tokyo', 'London', 'Rome', 'Donlon', 'Kyoto', 'Paris', 'Okyot'] --> [['Kyoto', 'Okyot', 'Tokyo'], ['Donlon', 'London'], ['Paris'], ['Rome']]
['Rome', 'Rome', 'Rome', 'Donlon', 'London'] --> [['Donlon', 'London'], ['Rome']]
[] --> []
``` | ["def group_cities(seq):\n result = []\n sort_result =[]\n seq = list(dict.fromkeys(seq)) #removing duplicates\n for e, i in enumerate(seq):\n sort_result = [j for j in seq if len(j)==len(i) and j.lower() in 2*(i.lower())]\n if not sorted(sort_result) in result :\n result.append(sorted(sort_result))\n return(sorted(sorted(result),key=len,reverse=True))", "from collections import Counter, defaultdict\n\ndef group_cities(seq):\n bases = defaultdict(lambda: defaultdict(list))\n for W in set(seq):\n w = W.lower()\n d = bases[ frozenset(Counter(w).items()) ]\n k = next( (w2 for w2 in d if w in w2), w*2)\n d[k].append(W)\n \n return sorted( [sorted(lst) for d in bases.values() for lst in d.values()],\n key=lambda g: (-len(g),g[0]) )", "from collections import deque\n\ndef group_cities(seq):\n result = []\n \n # Remove duplicates\n seq = sorted(set(seq))\n\n # Convert to lower case for comparisons\n simples = [c.lower() for c in seq]\n \n # Indices that have already been added to a set\n skip = set()\n \n # Look for matches\n for i, c1 in enumerate(simples):\n if i in skip:\n # Already matched\n continue\n city_match = [i]\n skip.add(i)\n \n # Create all the rolled versionos of this city name\n rolls = []\n roller = deque(c1)\n roller.rotate(1)\n while ''.join(roller) != c1:\n rolls.append(''.join(roller))\n roller.rotate(1)\n \n # See if a rolled name is present in any names later in the list\n for roll in rolls:\n for j, c2 in enumerate(simples[i + 1:], i + 1):\n if j in skip:\n # Already matched\n continue\n if c2 == roll:\n # Found a matching name, add this index to the matches and skip set\n skip.add(j)\n city_match.append(j)\n \n # Convert matched indices back to original name\n result.append(sorted([seq[k] for k in city_match]))\n \n # Sort by decreasing length and then alphabetically\n result.sort(key=lambda a: (-len(a), a[0]))\n return result\n", "def group_cities(seq):\n res = {}\n for w in seq:\n temp = [str(w[i:] + w[:i]).title() for i in range(1, len(w)) \n if str(w[i:] + w[:i]).title() in seq]\n temp.append(w)\n res[frozenset(temp)] = sorted(set(temp))\n return sorted(res.values(), key=lambda x: (-len(x), x[0]))", "def is_palindrome(a,b):\n if len(a)!=len(b):\n return False\n else:\n for i in range(1,len(a)):\n if a.lower()[i:] + a.lower()[:i] == b.lower():\n return True\n return False\ndef group_cities(seq): \n ans=[]\n already_chosen=[]\n for term in seq:\n if term not in already_chosen:\n temp=[term]\n already_chosen.append(term)\n for thing in seq:\n if thing not in already_chosen and thing!=term and is_palindrome(thing,term):\n temp.append(thing)\n already_chosen.append(thing)\n ans.append(temp)\n for thing in ans:\n thing.sort()\n ans.sort(key=lambda x:x[0])\n ans.sort(key=len,reverse=True)\n return ans\n \n", "from collections import defaultdict\n\ndef key(s):\n s = s.lower().replace(' ', '')\n return min(s[i:] + s[:i] for i in range(len(s)))\n\ndef group_cities(seq): \n result = defaultdict(list)\n for city in set(seq):\n result[key(city)].append(city)\n for cities in result.values():\n cities.sort()\n return sorted(result.values(), key=lambda cities: (-len(cities), cities[0]))", "def group_cities(seq): \n result = []\n for element in sorted(list(dict.fromkeys(seq)), key=str.lower):\n for group in result:\n if element.lower() in [group[0].lower()[r:] + group[0].lower()[:r] for r in range(len(group[0].lower()))]:\n group.append(element)\n break\n else:\n result.append([element])\n\n return sorted(result, key=len, reverse=True)\n", "from collections import deque\nfrom operator import itemgetter\n\n\ndef group_cities(seq):\n seq_by_length = {}\n for s in seq:\n l = len(s)\n if l in seq_by_length:\n seq_by_length[l].append(s)\n else:\n seq_by_length[l] = [s]\n\n groups = []\n for elems in seq_by_length.values():\n to_check = deque(set(elems))\n\n while to_check:\n cur_check = to_check.pop()\n group, check = [cur_check], cur_check.lower() * 2\n\n for c in to_check.copy():\n if c.lower() in check:\n group.append(c)\n to_check.remove(c)\n\n groups.append(sorted(group))\n\n return sorted(sorted(groups, key=itemgetter(0)), key=len, reverse=True)", "from collections import defaultdict\n\ndef group_cities(l):\n def make_key(s):\n return min(s[-i:] + s[:-i] for i in range(len(s)))\n d = defaultdict(list)\n for item in sorted(set(l)):\n d[make_key(item.lower())].append(item)\n return sorted(d.values(), key=len, reverse=True)", "from collections import defaultdict\n\ndef group_cities(seq): \n key = lambda s: min(s[i:]+s[:i] for i in range(len(s)))\n d = defaultdict(set)\n for e in seq: d[key(e.lower())].add(e)\n return sorted((sorted(v) for v in d.values()), key=lambda x: (-len(x),x))"] | {"fn_name": "group_cities", "inputs": [[["Tokyo", "London", "Rome", "Donlon", "Kyoto", "Paris", "Okyot"]], [["Tokyo", "London", "Rome", "Donlon"]], [["Rome", "Rome", "Rome", "Donlon", "London"]], [["Ab", "Aa"]], [[]]], "outputs": [[[["Kyoto", "Okyot", "Tokyo"], ["Donlon", "London"], ["Paris"], ["Rome"]]], [[["Donlon", "London"], ["Rome"], ["Tokyo"]]], [[["Donlon", "London"], ["Rome"]]], [[["Aa"], ["Ab"]]], [[]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 5,673 |
def group_cities(seq):
|
f97f004ec309ada8929add44c340ae11 | UNKNOWN | In this Kata, you will be given a series of times at which an alarm goes off. Your task will be to determine the maximum time interval between alarms. Each alarm starts ringing at the beginning of the corresponding minute and rings for exactly one minute. The times in the array are not in chronological order. Ignore duplicate times, if any.
```Haskell
For example:
solve(["14:51"]) = "23:59". If the alarm goes off now, it will not go off for another 23 hours and 59 minutes.
solve(["23:00","04:22","18:05","06:24"]) == "11:40". The max interval that the alarm will not go off is 11 hours and 40 minutes.
```
In the second example, the alarm goes off `4` times in a day.
More examples in test cases. Good luck! | ["from datetime import datetime\n\ndef solve(arr):\n dts = [datetime(2000, 1, 1, *map(int, x.split(':'))) for x in sorted(arr)]\n delta = max(int((b - a).total_seconds() - 60) for a, b in zip(dts, dts[1:] + [dts[0].replace(day=2)]))\n return '{:02}:{:02}'.format(*divmod(delta//60, 60))", "def solve(arr):\n arr = sorted(int(m[:2]) * 60 + int(m[3:]) for m in set(arr))\n arr += [arr[0] + 1440]\n h, m = divmod(max(arr[i + 1] - arr[i] - 1 for i in range(len(arr) - 1)), 60)\n return \"{:02}:{:02}\".format(h, m)\n", "def solve(arr):\n sorted_arr = sorted(arr, reverse=True)\n sorted_as_min = list(map(time_to_minutes, sorted_arr))\n windows = list(zip(sorted_as_min, sorted_as_min[1:]))\n differences = list(map(lambda w: w[0] - w[1], windows))\n differences.append(24*60 - sorted_as_min[0] + sorted_as_min[-1])\n return minutes_to_time(max(differences) - 1)\n\ndef time_to_minutes(time):\n (hr, min) = time.split(\":\")\n return int(hr)*60 + int(min)\n\ndef minutes_to_time(minutes):\n return \"{H:0=2d}:{M:0=2d}\".format(H=minutes // 60, M=minutes % 60)", "def solve(arr):\n k = sorted(int(x[:2])*60 + int(x[3:]) for x in arr)\n z = [(k[i] - k[i-1])%1440 for i in range(len(k))]\n return len(k) > 1 and '{:02}:{:02}'.format(*divmod(max(z)-1,60)) or \"23:59\"\n", "def minutes(s):\n return int(s[0:2]) * 60 + int(s[-2:])\n\ndef timeformat(m):\n return \"{:02d}:{:02d}\".format(m // 60, m % 60)\n\ndef solve(arr):\n arr = list(set(arr))\n m = [minutes(arr) for arr in sorted(arr)]\n difference = [(m[(i+1)%len(m)] - a - 1) % (60*24) for i, a in enumerate(m)]\n\n return(timeformat(max(difference)))", "def solve(arr):\n m = sorted(int(t[:2])*60 + int(t[-2:]) for t in arr)\n difs = [m[i+1] - m[i] - 1 for i in range(len(m)-1)]\n difs.append(1440 - m[-1] + m[0] - 1)\n maxd = max(difs)\n return f\"{str(maxd//60).zfill(2)}:{str(maxd%60).zfill(2)}\"", "def solve(times):\n def to_minutes(time):\n hh, mm = time.split(':')\n return int(hh) * 60 + int(mm)\n times = sorted(to_minutes(time) for time in times)\n times.append(times[0] + 24 * 60)\n result = max(b - a - 1 for a, b in zip(times, times[1:]))\n return '{:02d}:{:02d}'.format(*divmod(result, 60))", "def solve(times):\n mins = sorted(int(t[:2])*60 + int(t[3:]) for t in set(times))\n mins += [mins[0] + 1440]\n max_time = max(b - a - 1 for a, b in zip(mins, mins[1:]))\n return '%02d:%02d' % divmod(max_time, 60)", "from datetime import timedelta\n\ndef solve(arr):\n max = 0\n a = list(dict.fromkeys(arr)) # Used to remove duplicate times\n new_list = []\n if len(a) > 1:\n for i in enumerate(a): # Numbered iteration though List a\n new_list.append(str(i[1].replace(\":\",\"\")))\n new_list.sort() # Chronologically ordered alarm times\n new_list.reverse() # From highest to lowest\n \n for i in enumerate(new_list): # numbered list to make further code simpler/more organised\n if i[0] <= (len(new_list)-2):\n delta_hours = int((i[1])[:2:]) - int((new_list[i[0]+1])[:2:]) # This prepares the hour difference for the timedelata function later\n delta_mins = int((i[1])[2::]) - int((new_list[i[0]+1])[2::]) - 1 # This prepares the minutes difference for the timedelata function later\n t = (str(timedelta(hours=delta_hours, minutes=delta_mins)))[:-3] # This calculates the time difference between the time increments in the list \n c = int(t.replace(\":\",\"\")) # Eliminates the colon and turns the time into a integer so that the largest time can be determined \n if c >= max: # If the time value is larger than the previous values of c, this becomes the new value of c\n max = c \n result = t\n\n if i[0] == (len(new_list)-1): \n loop_hrs = int((i[1])[:2:]) - int((new_list[0])[:2:]) + 24 # This determienes the hour differnece between alarms in different days (PM->AM)\n loop_mins = int((i[1])[2::]) - int((new_list[0])[2::]) - 1 # This determienes the minute differnece between alarms in different days (PM->AM)\n d = (str(timedelta(hours=loop_hrs, minutes=loop_mins)))[:-3]\n c = int(d.replace(\":\",\"\"))\n if c >= max: # If this time interval is greater than the previous time intervals, it becomes the new c value\n result = d\n \n if len(result) == 4: # Time delta may only have one hour value, if this is the case, add 0 to the interval string to ensure a 5 character time interval\n result = \"0\"+result\n return(result) # Return the result\n \n else:\n return(\"23:59\") # In the event that there is only one alarm, this will always be the time interval so return this", "solve=lambda a:(lambda s:'%02d:%02d'%divmod(max((b-a-1)%1440for a,b in zip(s,s[1:]+s)),60))(sorted({60*int(t[:2])+int(t[3:])for t in a}))"] | {"fn_name": "solve", "inputs": [[["14:51"]], [["23:00", "04:22", "18:05", "06:24"]], [["21:14", "15:34", "14:51", "06:25", "15:30"]]], "outputs": [["23:59"], ["11:40"], ["09:10"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 5,063 |
def solve(arr):
|
b6cb8d92dc74f2da52aa9642f5759efb | UNKNOWN | In this Kata, you will implement a function `count` that takes an integer and returns the number of digits in `factorial(n)`.
For example, `count(5) = 3`, because `5! = 120`, and `120` has `3` digits.
More examples in the test cases.
Brute force is not possible. A little research will go a long way, as this is a well known series.
Good luck!
Please also try: | ["from math import *\n\ndef count(n):\n return ceil(lgamma(n+1)/log(10))", "from math import log10, floor, pi, e\n\ndef count(n):\n if n<0: return 0\n if n<=1: return 1\n x = n*log10(n/e)+log10(2*pi*n)/2\n return floor(x)+1\n", "from math import ceil, log10, pi, e\n\ndef count(n):\n return ceil(log10(2*pi*n)/2+n*(log10(n/e)))", "from math import floor, log, pi\n\ndef count(n):\n return floor( ((n+0.5)*log(n) - n + 0.5*log(2*pi))/log(10) ) + 1", "from math import *\n\ndef count(n):\n return int(ceil(log10(2 * pi * n) / 2 + n * log10(n / e)))", "## https://www.johndcook.com/blog/2015/10/06/number-of-digits-in-n/\nfrom scipy.special import gammaln\nfrom math import log, floor\n\ndef count(n):\n return floor( gammaln(n+1)/log(10.0) ) + 1", "from math import ceil, log, pi, e\ncount = lambda n: int(ceil(log(2*pi*n, 10)/2+n*log(n/e, 10)))", "import math\n\ndef count(n):\n if n == 0 or n <= 1:\n return 1\n\n x = ((n * math.log10(n / math.e) + math.log10(2 * math.pi * n) / 2))\n \n return math.floor(x) + 1", "from math import floor, log10 \n \ndef count(n):\n n = n+1\n return floor(sum(map(log10, range(2, n)))) +1"] | {"fn_name": "count", "inputs": [[5], [50], [500], [5000], [50000], [500000], [5000000], [50000000]], "outputs": [[3], [65], [1135], [16326], [213237], [2632342], [31323382], [363233781]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,177 |
def count(n):
|
63bf111906ffda6217e28b1fc41dfef4 | UNKNOWN | See the following triangle:
```
____________________________________
1
2 4 2
3 6 9 6 3
4 8 12 16 12 8 4
5 10 15 20 25 20 15 10 5
___________________________________
```
The total sum of the numbers in the triangle, up to the 5th line included, is ```225```, part of it, ```144```, corresponds to the total sum of the even terms and ```81``` to the total sum of the odd terms.
Create a function that may output an array with three results for each value of n.
```python
triang_mult(n) ----> [total_sum, total_even_sum, total_odd_sum]
```
Our example will be:
```python
triang_mult(5) ----> [225, 144, 81]
```
Features of the random tests:
```
number of tests = 100
49 < n < 5000
```
Enjoy it!
This kata will be translated in another languages soon | ["def mult_triangle(n):\n total = (n * (n + 1) / 2)**2\n odds = ((n + 1) // 2)**4\n return [total, total - odds, odds]\n", "def mult_triangle(n):\n k = n * (n + 1) // 2\n p = ((n + 1) // 2)**4\n return [k*k, k*k - p, p]", "def get_totals_for_row(n):\n total = n**3\n if n % 2 == 0:\n return [total, total, 0]\n else:\n even_total = n * (n**2 // 2)\n odd_total = total - even_total\n return [total, even_total, odd_total]\n\ndef mult_triangle(n):\n total = 0\n even_total = 0\n odd_total = 0\n for level in range(1, n+1):\n t, e, o = get_totals_for_row(level)\n total += t\n even_total += e\n odd_total += o\n return [total, even_total, odd_total]\n\n# Slow approach (1st attempt!)\n# def make_row(n):\n# row = range(1,n+1) + range(n-1, 0, -1)\n# return [n * element for element in row]\n\n\n# def mult_triangle(n):\n# odd_total = 0\n# even_total = 0\n# for level in range(1, n+1):\n# for element in make_row(level): \n# if element % 2 == 0:\n# even_total += element\n# else:\n# odd_total += element\n# return [odd_total + even_total, even_total, odd_total]\n", "from math import ceil\ndef mult_triangle(n):\n s = (n*(n+1)/2)**2\n odd = ceil(n/2)**4\n return [s,s-odd,odd] #lol", "def mult_triangle(n):\n total = (n * (n+1) // 2) ** 2\n odd = ((n + 1) // 2) ** 4\n return [total, total - odd, odd]", "def mult_triangle(n):\n total = (n * (n + 1) // 2) ** 2\n odd = ((n + 1) // 2) ** 4\n even = total - odd\n return [total, even, odd]", "def mult_triangle(n):\n even,sum,i=0,0,1\n while i<=n:\n sum+=i*i*i\n even+=i*(i-1)*(i+1)/2 if i%2 else i*i*i\n i+=1\n return [sum,even,sum-even]", "def mult_triangle(n):\n n2 = n - 1 | 1\n total_sum = ((n+1) * n // 2)**2\n total_odd_sum = ((n2+1) * (n2+1) // 4)**2\n return [total_sum, total_sum - total_odd_sum, total_odd_sum]", "def mult_triangle(n):\n s = n*(n + 1)//2\n s *= s\n d = (n + 1)//2\n d *= d\n return [s, s - d*d, d*d]", "def mult_triangle(n):\n c,o=0,0\n for i in range(1,n+1): \n v=i**2\n c+=i*v\n if i&1: o+=i*(v+1>>1)\n return [c,c-o,o]"] | {"fn_name": "mult_triangle", "inputs": [[1], [2], [3], [4], [5], [10], [50]], "outputs": [[[1, 0, 1]], [[9, 8, 1]], [[36, 20, 16]], [[100, 84, 16]], [[225, 144, 81]], [[3025, 2400, 625]], [[1625625, 1235000, 390625]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,283 |
def mult_triangle(n):
|
c3809b6150f5d28e863b037cafcfc335 | UNKNOWN | # Fix the Bugs (Syntax) - My First Kata
## Overview
Hello, this is my first Kata so forgive me if it is of poor quality.
In this Kata you should fix/create a program that ```return```s the following values:
- ```false/False``` if either a or b (or both) are not numbers
- ```a % b``` plus ```b % a``` if both arguments are numbers
You may assume the following:
1. If ```a``` and ```b``` are both numbers, neither of ```a``` or ```b``` will be ```0```.
## Language-Specific Instructions
### Javascript and PHP
In this Kata you should try to fix all the syntax errors found in the code.
Once you think all the bugs are fixed run the code to see if it works. A correct solution should return the values specified in the overview.
**Extension: Once you have fixed all the syntax errors present in the code (basic requirement), you may attempt to optimise the code or try a different approach by coding it from scratch.** | ["def my_first_kata(a,b):\n #your code here\n if type(a) == int and type(b) == int:\n return a % b + b % a\n else:\n return False", "def my_first_kata(a, b):\n try:\n return a % b + b % a\n except (TypeError, ZeroDivisionError):\n return False", "def my_first_kata(a,b):\n if type(a) == int and type(b) == int: return a%b + b%a\n return False", "def my_first_kata(a,b):\n return a % b + b % a if type(a) is int and type(b) is int else False", "def my_first_kata(a,b):\n return type(a) == type(b) == int and a % b + b % a", "my_first_kata = lambda a,b: ((a%b)+(b%a)) if type(a) is type(b) is int else False", "def my_first_kata(a,b):\n return a % b ++ b % a if type(a) == int and type(b) == int else False", "def my_first_kata(a,b):\n return set(map(type, (a,b))) == {int} and a % b + b % a", "def my_first_kata(a,b):\n return all(type(x)==int for x in (a,b)) and (a%b)+(b%a)", "def my_first_kata(a,b):\n return a % b + b % a if type(a) == type(b) == int else False", "def my_first_kata(a,b):\n return a % b + b % a if (type(a), type(b)) == (int, int) else False", "def my_first_kata(a,b):\n if bool(type(a) == int and type(b) == int): return (a%b+b%a)\n else: return False", "def my_first_kata(a,b):\n return a%b+b%a if type(a) == int and type(b) == int else False ", "def my_first_kata(a,b):\n try:\n return a%b + b%a\n except: return False", "def my_first_kata(a,b):\n if type(a) == type(b) == int: \n return a % b ++ b % a\n else:\n return False", "def my_first_kata(a,b):\n if type(a) in (int,float) and type(b) in (int,float): return a % b + b % a\n return False", "def my_first_kata(a,b):\n return a % b + b % a if int == type(a) == type(b) else False", "from typing import Union\n\ndef my_first_kata(a: Union[int, str], b: Union[int, str]) -> Union[bool, int]:\n \"\"\"\n Get a value based on types passed as the arguments:\n - `False` if either a or b (or both) are not numbers\n - `a % b + b % a` if both arguments are numbers\n \"\"\"\n return False if not all(map(lambda _: type(_) in (int, float), [a, b])) else (a % b) + (b % a)", "my_first_kata=lambda a,b:int==type(a)==type(b)and a%b+b%a", "def my_first_kata(a,b):\n if type(a)== int and type(b) == int: \n return (b % a + a % b)\n else:\n return False", "def my_first_kata(a,b):\n if str(a).isnumeric() is False or str(b).isnumeric() is False: return False\n else: return int(a)%int(b) + int(b)%int(a)", "def my_first_kata(a,b):\n print(a)\n print(b)\n valid_a = isinstance(a, int) and type(a) == type(0)\n valid_b = isinstance(b, int) and type(b) == type(0)\n if valid_a and valid_b:\n return a % b + b % a\n else:\n return False", "def my_first_kata(a, b):\n if not type(a) in (int, float) or not type(b) in (int, float):\n return False\n return a % b + b % a\n", "def my_first_kata(a,b):\n if type(a) == type(b) == \"number\":\n return False\n try:\n return a % b + b % a\n except:\n return False", "def my_first_kata(a,b):\n if type(a) != int or type(b) != int:\n return False\n elif a == 0 or b == 0:\n return False\n else:\n return a % b + b % a", "def my_first_kata(a,b):\n if isinstance(a,int) and isinstance(b,int) and a*b!=0:\n return a%b+b%a\n else:\n return False", "def my_first_kata(a,b):\n try:\n if str(a).isdigit() and str(b).isdigit(): return (a % b) + (b % a)\n else:\n return False\n except:\n return False", "def my_first_kata(a,b):\n print(type(a))\n print(type(b))\n print(a)\n print(b)\n try:\n print((a % b) + (b % a))\n return (a % b) + (b % a)\n except(TypeError, ZeroDivisionError):\n return False", "def my_first_kata(a,b):\n if type(a) != int or type(b) != int:\n return False\n if type(a) == int and type(b)== int:\n return a%b + b%a\n", "def my_first_kata(a,b):\n if str(a).isdigit() and str(b).isdigit(): \n res = (a % b) + (b % a) \n return res\n else:\n return False", "def my_first_kata(a,b):\n if type(a) == int and type(b) == int: # both must be stated as int \n return a % b + b % a\n else:\n return False", "def my_first_kata(a,b):\n if not isinstance(a, int) or not isinstance(b, int):\n return False\n try:\n sum = (a % b) + (b % a)\n return sum\n except ZeroDivisionError:\n return False", "def my_first_kata(a,b):\n if type(a)!= int or type(b) != int:\n return False\n elif type(a)!= int and type(b) != int:\n return False\n else:\n return a % b + b % a", "def my_first_kata(a,b):\n try:\n if type(a) == str or type(b) == str:\n return False\n if type(a) == dict or type(b) == dict:\n return False\n else:\n return (a % b + b % a)\n except ZeroDivisionError:\n pass", "def my_first_kata(a, b):\n try:\n return a % b + b % a if all(map(lambda x: type(x) == int, (a, b))) else False\n except ZeroDivisionError:\n return False", "def my_first_kata(a,b):\n if 'int' in str(type(a)) and 'int' in str(type(b)):\n return a%b + b%a\n else:\n return False", "def my_first_kata(a,b):\n print(a,b)\n if not isinstance(a, int) and not isinstance(b, int): \n return False\n else:\n try:\n return a % b + b % a\n except:\n return False", "def my_first_kata(a,b):\n if (type(a)== int) and (type(b) == int):\n return a % b + b % a\n else: \n return 0", "def my_first_kata(a,b):\n if type(a) != float and type(a) != int or type(b) != float and type(b) != int:\n return False\n else:\n return a % b + b % a", "def my_first_kata(a,b):\n if type(a) == str:\n return False\n if type(b) == str: \n return False\n else:\n return a % b ++ b % a", "def my_first_kata(a,b):\n if type(a) is type(b):\n return a % b + b % a\n else:\n return False", "def my_first_kata(a,b):\n if isinstance(a, bool) or isinstance(b, bool):\n return False\n if isinstance(a, int) and isinstance(b, int) : \n #print (a,b)\n return (a % b) + (b % a)\n return False\n", "def my_first_kata(a,b):\n msg = False\n if isinstance(a,int) and isinstance(b,int) and a != 0 and b != 0:\n msg = a % b + b % a\n return msg", "def my_first_kata(a,b):\n print(a,b)\n if isinstance(a,int) and isinstance(b,int) and not isinstance(a,bool) and not isinstance(b,bool):\n return a%b + b%a\n else:\n return False", "def my_first_kata(a,b):\n numbers = [int, float, complex]\n if type(a) in numbers and type(b) in numbers:\n return a % b + b % a\n return False", "def my_first_kata(a,b):\n if not isinstance(a, int) or not isinstance(b, int):\n return False\n if a == 0 or b == 0:\n return False\n return a % b + b % a", "from contextlib import suppress\n\ndef my_first_kata(a, b):\n if type(a) == type(b) == int: \n with suppress(ZeroDivisionError):\n return a % b + b % a\n return False", "def my_first_kata(a,b):\n if (isinstance(a, int) or isinstance(a, float)) and (isinstance(b, int) or isinstance(b, float)): \n return a % b + b % a\n else:\n return False", "def my_first_kata(a,b):\n if any([t not in ['int', 'float'] for t in (type(a).__name__, type(b).__name__)]):\n return False\n else:\n return a % b + b % a", "def my_first_kata(a,b):\n print(a,b) \n if type(a) in [int, float, complex] and type(b) in [int, float, complex]:\n return a % b + b % a\n else:\n return False", "def my_first_kata(a,b):\n try:\n x = a % b + b % a\n return x\n except:\n return False", "def my_first_kata(a,b):\n if isinstance(a, int) and isinstance(b, int): return a % b ++ b % a if a and b else False\n return False", "# def my_first_kata(a,b):\n# if type(a) and type(b) == \"number\": return a % b + b % a\n# else:\n# return False\n \ndef my_first_kata(a,b):\n #your code here\n if type(a) == int and type(b) == int:\n return a % b + b % a\n else:\n return False", "def my_first_kata(a,b):\n if a == None or b == None:\n return False\n if a == [] or b == []:\n return False\n try:\n if a != 0 and b != 0:\n return a % b + b % a \n except TypeError:\n return False\n", "def my_first_kata(a,b):\n try: \n return a % b + b % a\n except Exception:\n return False", "def my_first_kata(a,b):\n x = isinstance(a, int)\n y = isinstance(b, int)\n if x and y == True:\n if a and b > 0:\n return (a % b) + (b % a)\n else: return False\n else:\n return False\n", "def my_first_kata(a,b):\n if isinstance(a, int) and isinstance(b, int) and not isinstance(b, bool) and not isinstance(a, bool): \n return (a % b) + (b % a)\n else:\n return False\n", "def my_first_kata(a,b):\n try:\n if abs(float(a/2 + b/2)) >0:\n return a % b ++ b % a\n else:\n return False\n except:\n return False\n", "def my_first_kata(a,b):\n if isinstance(a, int) and isinstance(b, int) :\n try: return a % b + b % a\n except :\n return False\n else : return False", "def my_first_kata(a, b):\n if type(a) == type(b) == int: \n try:\n return a % b + b % a\n except ZeroDivisionError:\n return False\n else:\n return False", "def my_first_kata(a,b):\n return False if not type(a) == int or not type(b) == int else a % b ++ b % a", "def my_first_kata(a,b): \n if type(a)!= int or type(b)!= int:\n return False\n else:\n if a < b:\n return (a % b) + (b % a)\n else:\n return (b % a) + (a % b)\n \n \n\n \n", "def my_first_kata(a,b):\n try:\n if type(a) is bool or type(b) is bool:\n raise TypeError('why')\n return a % b + b % a\n except TypeError:\n return False", "def my_first_kata(a,b):\n for item in (a,b):\n if type(item) != int: return False\n return a % b ++ b % a", "def my_first_kata(a,b):\n if isinstance(a,int) and isinstance(b,int): \n if a == 0 or b == 0: return False \n if a is None or b is None: return False\n else: return (a%b + b%a)\n else: return False\n", "def my_first_kata(a,b):\n print(a,b)\n if not all(isinstance(x,int) for x in [a,b]): \n return False\n elif int(a) == 0 or int(b) == 0:\n return False\n else:\n return a % b + b % a ", "def my_first_kata(a,b):\n if isinstance(a,int) and isinstance(b,int) and b != 0 and a != 0:\n return (a % b) + (b % a)\n else:\n return False", "def my_first_kata(a,b):\n if type(a) != type(5) or type(b) != type(5): return False\n else:\n return a % b + b % a", "def my_first_kata(a,b):\n if type(a) == int == type(b): \n return a % b + b % a\n else:\n return False", "def my_first_kata(a,b):\n return False if isinstance(a, (str, bool, dict)) or isinstance(b, (str, bool, dict)) else a % b + b % a \n", "def my_first_kata(a,b):\n if type(a) == type(b) == type(1): \n return (a % b) +(b % a)\n else:\n return False", "def my_first_kata(a,b):\n try:\n float(a)\n float(b)\n return a % b + b % a if a and b else False\n except:\n return False", "def my_first_kata(a,b):\n if isinstance(a, bool) or isinstance(b, bool):\n return False\n if isinstance(a, int) and isinstance(b, int) and a != 0 and b != 0: \n return a % b + b % a\n else:\n return False", "def my_first_kata(a,b):\n if type(a) == type(b):\n return a % b + b % a\n else:\n return False", "def my_first_kata(a,b):\n return a%b + b%a if type(a)==type(b) and type(a)==int else False\n if type(a) or type(b) == \"number\": return False\n else:\n return a % b ++ b % a", "def my_first_kata(a,b):\n # Tricky \n if type(a) != type(b):\n return False\n else:\n return int(b % a) + int(a % b)\n \n", "def my_first_kata(a,b):\n if isinstance(a, int) & isinstance(b, int):\n return a % b ++ b % a\n else:\n return False", "def my_first_kata(a,b):\n if (isinstance (a or b, str) or (a==0 or b==0)):\n return False\n elif (isinstance (a and b, int)):\n if(str(a)==\"True\" or str(b)==\"True\" or int(a%b+b%a)==0 or a==True and b==True):\n return False \n else: \n return int(a%b+b%a)\n else:\n return False \n \n \n \n", "def my_first_kata(a,b):\n if type(a) == int:\n if type(b) == int: \n return a % b + b % a \n return False", "def my_first_kata(a,b):\n if isinstance(a,int) and isinstance(b, int) and a and b: \n return a % b ++ b % a\n else:\n return False", "def my_first_kata(a,b):\n return a % b ++ b % a if isinstance(a, int) and isinstance(b, int) and a and b else False", "def my_first_kata(a,b):\n if isinstance(a, int) and isinstance(b, int) and a != 0 and b != 0:\n return a % b ++ b % a\n else:\n return False", "def my_first_kata(a,b):\n if a == 0 or b == 0:\n return False\n elif isinstance(a, int) and isinstance(b, int):\n a = int(a)\n b = int(b)\n return a % b ++ b % a\n else:\n return False", "def my_first_kata(a,b):\n if not ((isinstance(a,int) and isinstance(b,int))):\n return False \n elif a != 0 and b != 0:\n return a % b + b % a\n else:\n return False", "def my_first_kata(a,b):\n if not isinstance(a, int) or not isinstance(b, int): return False\n if a is 0 or b is 0:\n return False\n else:\n return a % b ++ b % a", "import math\ndef my_first_kata(a,b):\n is_number = bool\n if_is_number = 1\n if type(a) != int or type(b) != int: \n is_number = False\n else:\n if_is_number = int(a) % int(b) ++ int(b) % int(a)\n \n if is_number == False:\n return is_number\n else:\n return if_is_number", "def my_first_kata(a,b):\n if isinstance(a,int)==False or isinstance(b,int)==False : return False\n else:\n return a % b ++ b % a", "def my_first_kata(a,b):\n return a % b + b % a if (isinstance(a, int) and isinstance(b, int) and a and b) else False\n", "def my_first_kata(a,b):\n try:\n if complex(a) and complex(b):\n return a % b + b % a\n else: \n return False\n except:\n return False", "def my_first_kata(a, b):\n print(a, b)\n try:\n return a % b + b % a\n except:\n return False", "def my_first_kata(a,b):\n if type(a) != type(1) or type(b) != type(1):\n return False\n elif type(a) == type(1) or type(b) == type(1):\n return (a % b)+ (b % a)", "def my_first_kata(a,b):\n \n if isinstance(a,bool) or isinstance(b,bool):\n return False\n if (not isinstance(a,int)) or (not isinstance(b, int)): \n return False\n elif a==0 or b==0:\n return False\n \n else:\n return a % b ++ b % a", "def my_first_kata(a, b):\n if (type(a) is not int) or (type(b) is not int): \n return False\n else:\n try:\n return a % b + b % a\n except ZeroDivisionError:\n return False", "def my_first_kata(a,b):\n print(a, b)\n if str(a).isdigit() and str(b).isdigit():\n return int(a) % int(b) + int(b) % int(a)\n else:\n return False", "def my_first_kata(a,b):\n if not isinstance(a,int) or not isinstance(b,int): return False\n else:\n if a*b == 0:\n return False\n return a % b + b % a", "def my_first_kata(a, b):\n if not (isinstance(a, (int, float)) and isinstance(b, (int, float))):\n return False\n else:\n return a % b + b % a", "def my_first_kata(a,b):\n print('>>>'+str(a)+'<<< >>>'+str(b)+'<<<')\n if isinstance(a,bool) or isinstance(b,bool):\n return False\n if isinstance(a,int) and isinstance(b,int):\n return a % b + b % a if a!=0 and b!=0 else False\n return False", "def my_first_kata(a,b):\n print((a,b))\n try:\n return a % b + b % a\n except:\n return False\n # Flez\n \n", "def my_first_kata(a,b):\n if a == 0 or b == 0:\n return False\n if isinstance(a, int) and isinstance(b, int): \n return a%b + b%a\n else:\n return False", "def my_first_kata(a, b):\n return False if not isinstance(a, int) or not isinstance(b, int)\\\n or a == 0 or b == 0 else a % b+b % a"] | {"fn_name": "my_first_kata", "inputs": [[3, 5], ["hello", 3], [67, "bye"], [true, true], [314, 107], [1, 32], [-1, -1], [19483, 9], ["hello", {}], [[], "pippi"]], "outputs": [[5], [false], [false], [false], [207], [1], [0], [16], [false], [false]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 17,120 |
def my_first_kata(a,b):
|
576625d9a447a5f8094e98d0173182d2 | UNKNOWN | For every good kata idea there seem to be quite a few bad ones!
In this kata you need to check the provided array (x) for good ideas 'good' and bad ideas 'bad'. If there are one or two good ideas, return 'Publish!', if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is often the case, return 'Fail!'.
~~~if:c
For C: do not dynamically allocate memory,
instead return a string literal
~~~ | ["def well(x):\n c = x.count('good')\n return 'I smell a series!' if c > 2 else 'Publish!' if c else 'Fail!'", "def well(x):\n if x.count(\"good\") == 0:\n return \"Fail!\"\n elif x.count(\"good\") <= 2:\n return \"Publish!\"\n else:\n return \"I smell a series!\"", "def well(x):\n if 'good' in x:\n return 'I smell a series!' if x.count('good') > 2 else 'Publish!'\n else:\n return 'Fail!'", "def well(x):\n good = x.count('good')\n print (good)\n if good == 0:\n return 'Fail!'\n elif good > 2:\n return 'I smell a series!'\n else:\n return 'Publish!'", "def well(ideas):\n good_ideas = ideas.count('good')\n if good_ideas == 0:\n return 'Fail!'\n elif good_ideas < 3:\n return 'Publish!'\n return 'I smell a series!'", "well = lambda x: ('Fail!','Publish!','I smell a series!')[('good' in x) + (x.count('good')>2)]", "def well(x):\n good_ideas = x.count('good')\n if good_ideas == 0:\n return 'Fail!'\n elif good_ideas <= 2:\n return 'Publish!'\n else:\n return 'I smell a series!'", "def well(x):\n results = \"\"\n good_count = x.count(\"good\")\n if good_count == 0:\n results = \"Fail!\"\n elif good_count <= 2:\n results = \"Publish!\"\n else :\n results = \"I smell a series!\"\n return results", "def well(a):c=a.count('good');return['Fail!','Publish!','I smell a series!'][(c>0)+(c>2)]", "def well(x): return ['Fail!', 'Publish!', 'Publish!', 'I smell a series!'][min(3, x.count('good'))]\n", "well=lambda a:[\"Fail!\",\"Publish!\",\"I smell a series!\"][min((a.count(\"good\")+1)//2,2)]\n", "def well(x):\n y=0\n \n for c in x:\n if c==\"good\":\n y=y+1\n \n if y==0:\n return 'Fail!'\n\n if y > 2:\n return 'I smell a series!'\n \n \n return 'Publish!'\n \n # 'Publish!', if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is often the case, return 'Fail!'.\n", "def well(x):\n if x.count('good') >= 3:\n return 'I smell a series!'\n elif x.count('good') >= 1:\n return 'Publish!'\n return 'Fail!'\n", "def well(x):\n if x.count('good') > 2:\n return 'I smell a series!'\n if 'good' in x:\n return 'Publish!'\n return 'Fail!'", "def well(x):\n return (\"I smell a series!\" if x.count(\"good\") > 2\n else \"Fail!\" if x.count(\"good\") < 1\n else \"Publish!\")", "def well(ideas):\n good = 0\n \n for idea in ideas:\n if idea == 'good':\n if good > 1:\n return 'I smell a series!'\n good += 1\n \n return 'Publish!' if good else 'Fail!'", "def well(x):\n return 'Publish!' if 1 <= x.count('good') <= 2 else 'I smell a series!' if x.count('good') > 2 else 'Fail!'", "def well(x):\n return \"I smell a series!\" if x.count(\"good\") > 2 else \"Publish!\" if x.count(\"good\") >= 1 else \"Fail!\"", "well=lambda x:'I smell a series!'if x.count('good')>2 else('Publish!'if x.count('good') else 'Fail!')", "well = lambda x: ('Fail!','Publish!','I smell a series!')[min(int(x.count('good')/2+0.5),2)]", "def well(x):\n count = x.count(\"good\")\n if count <= 2 and count >= 1:\n return \"Publish!\"\n elif count > 2:\n return \"I smell a series!\"\n else:\n return \"Fail!\"\n \n", "def well(x):\n goodIdeas=0\n for k in x:\n if(k==\"good\"):\n goodIdeas+=1\n if goodIdeas>2:\n return \"I smell a series!\"\n elif goodIdeas>=1:\n return \"Publish!\"\n else:\n return 'Fail!'\n", "def well(x):\n n = x.count('good')\n return ('Fail!', 'Publish!', 'I smell a series!')[(n > 0) + (n > 2)]", "def well(x):\n \n return 'Fail!' if x.count('good')==0 else 'Publish!' if x.count('good')<=2 else \"I smell a series!\"", "def well(x):\n g=x.count('good')\n if g>2: return 'I smell a series!'\n if g: return 'Publish!'\n return 'Fail!'", "def well(x):\n return {0: \"Fail!\", 1: \"Publish!\", 2: \"Publish!\"}.get(x.count(\"good\"), \"I smell a series!\")", "def well(x):\n chk = x.count('good')\n return['Fail!','Publish!','I smell a series!'][(chk > 0)+(chk > 2)]", "def well(x):\n '''\n if x.count('good') > 2: \n return 'I smell a series!'\n elif x.count('good') > 0 < 3: \n return 'Publish!'\n else:\n return 'Fail!'\n '''\n chk, l = x.count('good'), ['Fail!','Publish!','I smell a series!']\n return [l[0],l[1],l[1]][chk] if chk < 3 else l[2]", "def well(x):\n if x.count('good') <= 2 and x.count('good') > 0:\n return 'Publish!'\n elif x.count('good') > 0:\n return 'I smell a series!'\n else:\n return 'Fail!'\n", "def well(x):\n goods = x.count('good')\n return ['Fail!', 'Publish!', 'I smell a series!'][(goods > 2) + (goods >= 1)]", "def well(x):\n good_count = 0\n for i in x:\n if i == \"good\":\n good_count+=1\n \n if 0< good_count <=2 :\n return 'Publish!'\n if good_count == 0 :\n return 'Fail!'\n if good_count > 2:\n return 'I smell a series!'\n", "def well(x):\n print(x)\n if 0 < x.count('good') <= 2: return 'Publish!'\n elif x.count('good') > 2: return 'I smell a series!'\n else: return 'Fail!'", "def well(x):\n good_ideas = x.count('good')\n if not good_ideas: return 'Fail!'\n elif good_ideas <= 2: return 'Publish!'\n else: return 'I smell a series!'\n", "def well(x):\n a = sum(1 for i in x if i == \"good\")\n if a == 1 or a == 2:\n return \"Publish!\"\n elif a > 2:\n return \"I smell a series!\"\n else:\n return \"Fail!\"", "def well(x):\n # your code here\n NG=0\n for i in range(len(x)):\n if(x[i]==\"good\"):\n NG+=1 \n if(NG>2):\n return 'I smell a series!'\n elif(NG>=1):\n return 'Publish!'\n else:\n return 'Fail!'", "def well(x):\n if x.count(\"bad\") == len(x):\n return \"Fail!\"\n if x.count('good') == 1 or x.count('good') == 2:\n return \"Publish!\"\n else:\n return 'I smell a series!'", "def well(x):\n count = 0\n for i in x:\n if i == 'good':\n count += 1\n if count > 2:\n return 'I smell a series!'\n elif count != 0:\n return 'Publish!'\n return 'Fail!'\n", "def well(x):\n if not('good' in x):\n return 'Fail!'\n else:\n return 'Publish!' if x.count('good') < 3 else 'I smell a series!' ", "def well(x):\n counter = 0\n for i in x:\n if i.lower() == 'good':\n counter +=1\n if counter == 1 or counter == 2:\n return \"Publish!\"\n elif counter>2:\n return \"I smell a series!\"\n elif counter<1: \n return \"Fail!\"", "def well(x):\n \n c= x.count(\"good\")\n if c < 1:\n return \"Fail!\"\n elif 1 <= c <=2 :\n return \"Publish!\"\n else:\n return \"I smell a series!\"\n \n", "def well(x):\n good_idea_num = x.count('good')\n if good_idea_num < 1:\n return 'Fail!'\n elif good_idea_num < 3:\n return 'Publish!'\n else:\n return 'I smell a series!'", "def well(x):\n v = len([i for i in x if i == 'good'])\n return 'Fail!' if v == 0 else 'I smell a series!' if v > 2 else 'Publish!'", "def well(x):\n num_good = x.count(\"good\")\n if num_good == 0:\n return \"Fail!\"\n elif num_good > 2:\n return \"I smell a series!\"\n return \"Publish!\"", "def well(x):\n temp = x.count(\"good\")\n if 0 < temp < 3:\n return 'Publish!'\n elif temp > 2:\n return 'I smell a series!'\n else:\n return 'Fail!'", "def well(x):\n return \"I smell a series!\" if sum(1 if i == \"good\" else 0 for i in x) > 2 else \"Publish!\" if 3 > sum(1 if i == \"good\" else 0 for i in x) > 0 else \"Fail!\"", "def well(x):\n c = x.count('good')\n return 'Publish!' if c == 1 or c == 2 else 'I smell a series!' if c > 2 else 'Fail!'", "def well(x):\n return 'I smell a series!' if x.count('good') > 2 else 'Publish!' if x.count('good') != 0 else 'Fail!'", "def well(x):\n c=0\n for i in x:\n if i == 'good':\n c+=1\n \n if c==1 or c==2:\n return 'Publish!'\n elif c >2:\n return 'I smell a series!'\n elif c==0:\n return 'Fail!'", "def well(x):\n alfa = ('Fail!', 'Publish!', 'Publish!', 'I smell a series!')\n return alfa[min(3, max(x.count('good'), 0))]", "def well(x):\n goodCount = 0\n for item in x:\n if item == \"good\":\n goodCount += 1\n \n if goodCount > 2:\n return \"I smell a series!\"\n elif goodCount > 0:\n return \"Publish!\"\n else:\n return \"Fail!\"", "def well(x):\n a = 0\n for i in x:\n if i.lower() == 'good':\n a += 1\n if a <= 2 and a != 0:\n return 'Publish!'\n elif a > 2:\n return 'I smell a series!'\n else:\n return 'Fail!'", "def well(x):\n c = x.count('good')\n return ('Publish!' if c <= 2 else 'I smell a series!') if c>0 else 'Fail!'", "def well(x):\n c = len([i for i in x if i == 'good'])\n if c == 0:\n return 'Fail!'\n elif c < 3:\n return 'Publish!'\n else:\n return 'I smell a series!'", "def well(x):\n y = x.count(\"good\") \n if y == 0:\n return \"Fail!\"\n elif y ==1 or y==2:\n return \"Publish!\"\n else:\n return \"I smell a series!\"", "def well(x):\n cnt=x.count('good')\n return \"Fail!\" if cnt==0 else \"Publish!\" if cnt < 3 else \"I smell a series!\"", "def well(x):\n # your code here\n c=0\n for i in x:\n if(i==\"good\"):\n c+=1\n if(0<c<=2):\n return \"Publish!\"\n elif(c>2):\n return \"I smell a series!\"\n else:\n return \"Fail!\"\n", "def well(x):\n counter = 0\n for idea in x:\n if idea == 'good':\n counter += 1\n if counter == 0:\n return 'Fail!'\n elif counter <= 2:\n return 'Publish!'\n else:\n return 'I smell a series!'", "def well(x):\n if \"good\" in x: return \"I smell a series!\" if x.count(\"good\") > 2 else \"Publish!\"\n return \"Fail!\"", "def well(x):\n i = x.count(\"good\")\n if i > 2:\n return \"I smell a series!\"\n elif i == 0:\n return \"Fail!\"\n else:\n return \"Publish!\"", "def well(x):\n\n return 'Publish!' if x.count('good') in [1,2] else 'I smell a series!' if x.count('good') > 2 else 'Fail!'", "def well(x):\n n = x.count('good')\n return 'Fail!' if n < 1 else 'Publish!' if n < 3 else 'I smell a series!'", "def well(x):\n counter = 0 \n for i in x:\n if i == \"good\":\n counter += 1\n if counter < 1:\n return \"Fail!\" \n elif counter <= 2:\n return \"Publish!\"\n elif counter >2:\n return \"I smell a series!\"", "def well(x):\n score = 0\n for count in range(len(x)):\n if x[count] == \"good\":\n score += 1\n else:\n continue\n if score > 0 and score < 3:\n return \"Publish!\"\n elif score > 2: \n return \"I smell a series!\"\n else:\n return \"Fail!\"\n \n", "def well(x):\n # your code here\n return 'Publish!' if x.count('good')==2 or x.count('good')==1 else 'I smell a series!' if x.count('good')>2 else 'Fail!'", "def well(x):\n good_count = x.count('good')\n return 'I smell a series!' if good_count > 2 else ('Publish!' if good_count else 'Fail!')", "def well(x):\n good_ideas = 0\n \n for idea in x:\n if idea == \"good\":\n good_ideas +=1 \n \n if 0 < good_ideas <=2: \n return \"Publish!\"\n elif 2 < good_ideas: \n return \"I smell a series!\"\n else:\n return \"Fail!\"\n", "def well(x):\n d = {i:x.count(i) for i in x}\n if not d.get('good'):\n return 'Fail!'\n elif 1 <= d.get('good') <=2:\n return 'Publish!'\n else:\n return 'I smell a series!'", "def well(x):\n l=x.count('good')\n return 'I smell a series!' if l>2 else 'Publish!' if l>0 else 'Fail!'", "def well(x):\n if x.count('good') == 0: return \"Fail!\"\n return 'Publish!' if x.count('good') == 1 or x.count('good') == 2 else \"I smell a series!\"", "def well(x):\n return [\"Fail!\",\"Publish!\",\"Publish!\",\"I smell a series!\"][x.count(\"good\") if x.count(\"good\") < 3 else 3]", "def well(x):\n y=\"good\"\n count=0\n cw=0\n while len(x) > cw:\n if x[cw] == y:\n count=count+1\n cw=cw+1\n else:\n cw=cw+1\n if count == 1 or count == 2:\n return \"Publish!\"\n elif count > 2:\n return \"I smell a series!\"\n else:\n return \"Fail!\"", "def well(x):\n g = sum([1 for item in x if item == 'good'])\n if g > 2: return 'I smell a series!'\n elif g > 0: return 'Publish!'\n else: return 'Fail!'", "def well(x):\n \n if x.count(\"good\") in [1,2]:\n return \"Publish!\"\n elif x.count(\"good\") == 0:\n return \"Fail!\"\n elif len(x) > 2:\n return \"I smell a series!\"\n else:\n return \"?\"\n", "def well(x):\n cnt = 0\n for idea in x:\n cnt += 1 if idea == 'good' else 0\n return 'Fail!' if cnt == 0 else 'Publish!' if cnt <=2 else 'I smell a series!'", "def well(x):\n c = x.count('good')\n if 2 >= c >= 1:\n return 'Publish!'\n if c > 2:\n return 'I smell a series!'\n return 'Fail!'", "def well(x):\n \"\"\"(^-__-^)\"\"\"\n if x.count('good') > 2: return 'I smell a series!'\n if x.count('good') == 0: return 'Fail!'\n if 3 > x.count('good') >= 1 : return 'Publish!'", "def well(x):\n return 'Publish!' if 1 <= x.count('good') <= 2 else 'I smell a series!' if \\\n x.count('good') > 2 else 'Fail!'", "def well(x):\n if 'good' not in x:\n return 'Fail!'\n good = 0\n for i in x:\n if i == 'good':\n good += 1\n if good > 2:\n return 'I smell a series!'\n return 'Publish!'", "def well(x):\n res = \"\"\n if x.count(\"good\") == 1 or x.count(\"good\") == 2:\n res = \"Publish!\"\n elif x.count(\"good\") > 2:\n res = \"I smell a series!\"\n else:\n res = \"Fail!\"\n return res", "def well(x):\n count_ = x.count('good')\n return 'Fail!' if count_ == 0 else ('Publish!' if count_ <= 2 else ('I smell a series!'))", "\ndef well(x):\n good_count = 0\n for idea in x:\n if idea == 'good':\n good_count += 1\n if good_count == 0:\n return 'Fail!'\n elif good_count < 3:\n return 'Publish!'\n else:\n return 'I smell a series!'", "def well(x):\n c = x.count('good')\n a = ''\n if c == 0:\n a = 'Fail!'\n elif c < 3:\n a = 'Publish!'\n else:\n a = 'I smell a series!'\n return a", "def well(x):\n k = 0\n for i in x:\n if i == \"good\":\n k += 1\n if k == 0:\n return 'Fail!'\n if k == 1 or k == 2:\n return 'Publish!'\n if k > 2:\n return 'I smell a series!'", "def well(x):\n a = x.count('good')\n if 1 <= a <= 2:\n return 'Publish!'\n if 3 <= a:\n return 'I smell a series!'\n else: \n return 'Fail!'", "def well(x):\n count = x.count('good')\n \n return 'Fail!' if count == 0 else 'Publish!' if count <= 2 else 'I smell a series!'", "def well(x):\n count = 0\n \n for idea in x:\n if idea == 'good': count += 1\n \n return 'Fail!' if count == 0 else 'Publish!' if count <= 2 else 'I smell a series!'", "def well(x):\n y = x.count('good')\n if y is 0:\n return \"Fail!\"\n if y == 1 or y ==2:\n return \"Publish!\"\n return 'I smell a series!'", "def well(x):\n good_ideas = sum(1 for word in x if word == \"good\")\n if good_ideas > 2:\n return \"I smell a series!\"\n elif good_ideas > 0:\n return \"Publish!\"\n return \"Fail!\"", "def well(x):\n c = x.count('good')\n if 0 < c <= 2:\n return 'Publish!'\n elif c > 2:\n return 'I smell a series!'\n else:\n return 'Fail!'", "def well(x):\n res = 0\n for i in x:\n if i == 'good': res += 1\n if res <= 2 and res > 0: return 'Publish!'\n elif res > 2: return 'I smell a series!'\n else: return 'Fail!'", "def well(x): \n good = x.count('good')\n if good> 2:\n return 'I smell a series!'\n elif good == 0:\n return 'Fail!'\n else:\n return 'Publish!'", "def well(x):\n good_counter = 0\n for i in x:\n if i == 'good':\n good_counter += 1\n if 1<=good_counter<=2:\n return 'Publish!'\n elif good_counter>2:\n return 'I smell a series!'\n else:\n return 'Fail!'", "def well(x):\n count_good = x.count('good')\n if count_good > 0 and count_good <= 2:\n return 'Publish!'\n elif count_good > 2:\n return 'I smell a series!'\n return 'Fail!'", "def well(x):\n count_good = x.count('good')\n if count_good ==1 or count_good ==2 :\n return 'Publish!'\n elif count_good > 2:\n return 'I smell a series!'\n else:\n return 'Fail!'", "def well(x):\n return ['Fail!', 'Publish!', 'Publish!', 'I smell a series!', 'I smell a series!', 'I smell a series!', 'I smell a series!'].__getitem__(x.count('good'))", "def well(x):\n for i in x:\n if x.count('good') >= 3:\n return 'I smell a series!'\n elif 0 < x.count('good') <= 2:\n return 'Publish!'\n elif x.count:\n return 'Fail!'\n", "def well(x):\n goodCounter = 0\n for i in range(len(x)): \n if x[i] == 'good': \n goodCounter += 1 \n if goodCounter == 1 or goodCounter ==2 : return 'Publish!'\n elif goodCounter > 2: return 'I smell a series!'\n \n return 'Fail!'", "def well(x):\n if str(x.count('good')) in '12':\n return 'Publish!'\n elif x.count('good') > 2:\n return 'I smell a series!'\n else:\n return 'Fail!'", "def well(x):\n y = x.count('good')\n if 2 >= y >= 1:\n return 'Publish!'\n elif y >= 3 :\n return 'I smell a series!'\n if y == 0:\n return 'Fail!'", "def well(x):\n if not 'good' in x:\n return 'Fail!'\n else:\n if len([i for i in x if i==\"good\"])>2:\n return 'I smell a series!'\n else:\n return 'Publish!'", "def well(x):\n # your code here\n if 'good' not in x:\n return 'Fail!'\n elif 3>x.count('good')>0:\n return 'Publish!'\n else:\n return 'I smell a series!'", "def well(x):\n pos = x.count('good')\n if pos == 1 or pos == 2:\n return 'Publish!'\n elif pos > 2:\n return 'I smell a series!'\n else:\n return 'Fail!'"] | {"fn_name": "well", "inputs": [[["bad", "bad", "bad"]], [["good", "bad", "bad", "bad", "bad"]], [["good", "bad", "bad", "bad", "bad", "good", "bad", "bad", "good"]]], "outputs": [["Fail!"], ["Publish!"], ["I smell a series!"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 19,176 |
def well(x):
|
635bba503401e1bc4bbd4122e1fc81b7 | UNKNOWN | You're given a string containing a sequence of words separated with whitespaces. Let's say it is a sequence of patterns: a name and a corresponding number - like this:
```"red 1 yellow 2 black 3 white 4"```
You want to turn it into a different **string** of objects you plan to work with later on - like this:
```"[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}, {name : 'black', id : '3'}, {name : 'white', id : '4'}]"```
Doing this manually is a pain. So you've decided to write a short function that would make the computer do the job for you. Keep in mind, the pattern isn't necessarily a word and a number. Consider anything separeted by a whitespace, just don't forget: an array of objects with two elements: name and id.
As a result you'll have a string you may just copy-paste whenever you feel like defining a list of objects - now without the need to put in names, IDs, curly brackets, colon signs, screw up everything, fail searching for a typo and begin anew. This might come in handy with large lists. | ["import re\n\ndef words_to_object(s):\n return \"[\" + re.sub(\"([^ ]+) ([^ ]+)\", r\"{name : '\\1', id : '\\2'},\", s).strip(',') + \"]\"", "def words_to_object(s):\n return '[' + ', '.join(\"{name : '%s', id : '%s'}\" % (n, i) for n, i in zip(s.split()[::2], s.split()[1::2])) + ']'", "def words_to_object(s):\n words = s.split()\n \n res = []\n \n for key in range(0, len(words) - 1, 2):\n value = key + 1\n \n res.append(\"{name : \" + \"'\" + words[key] + \"'\" + \", \" + \"id : \" + \"'\" + words[value] + \"'}\")\n \n return \"[\" + \", \".join(res) + \"]\"", "def words_to_object(s):\n return '[' + ', '.join(f\"{{name : '{a}', id : '{b}'}}\" for a, b in zip(s.split()[::2], s.split()[1::2])) + ']'", "def words_to_object(s):\n xs = s.split()\n return '[{}]'.format(', '.join(f\"{{name : {name!r}, id : {id_!r}}}\" for name, id_ in zip(xs[::2], xs[1::2])))", "import collections\nimport json\nimport re\ndef words_to_object(s):\n if s == \"\" :\n return '[]'\n d = collections.namedtuple('d', 'name ,id')\n words = s.split(\" \")\n names = [ x for x in words[::2]]\n ids = [x for x in words [1::2]]\n result =\"\"\n i = 0\n for i in range(0,int( len(words) /2)):\n a = d(name= names[i], id=ids[i])\n r=(json.dumps(a._asdict()).replace('\"', '\\''))\n r= r.replace('\"','').replace(\"'name':\", \"name :\").replace(\"'id':\", \"id :\")\n r= re.sub(\"}\",\"}, \",r,flags=re.UNICODE)\n result +=r\n return '[' +result[0:-2] +\"]\"\n", "objectify = \"{{name : '{}', id : '{}'}}\".format\n\ndef words_to_object(s):\n pairs = zip(*[iter(s.split())]*2)\n obj_list = ', '.join(objectify(*pair) for pair in pairs)\n return '[{}]'.format(obj_list)", "words_to_object = lambda s: \"[\" + \", \".join(\"{name : '%s', id : '%s'}\" % t for t in zip(*[iter(s.split())]*2)) + \"]\"", "def words_to_object(s):\n if not s:\n return \"[]\"\n s = s.split()\n s = [(s[i], s[i+1]) for i in range(0, len(s), 2)]\n s = [\"{{name : '{}', id : '{}'}}\".format(i[0], i[1]) for i in s]\n return '[' + ', '.join(s) + ']'", "import re\n\ndef words_to_object(s):\n matches = re.findall(r'(.+?)\\s(.+?)\\s', s + ' ')\n return \"[\" + \", \".join([\"{{name : '{}', id : '{}'}}\".format(x[0], x[1]) for x in matches]) + \"]\"", "def words_to_object(s):\n if s == '': return '[]'\n for iii in range(s.count(' ')):\n s = s.replace(' ',chr(9),1)\n s = s.replace(' ',chr(10),1)\n s_list_a = s.split(chr(10))\n retval_list = []\n for val in s_list_a:\n zname, zid = val.split(chr(9))\n retval_list.append('''{name : '''+chr(39)+zname+chr(39)+''', id : '''+chr(39)+ zid+chr(39))\n retval = '''[''' + '}, '.join(retval_list)+'''}]'''\n return retval", "def words_to_object(s):\n s=s.split()\n return str([{'name': s[i], 'id': s[i+1]} for i in range(0,len(s),2)]).replace(\"'name'\",\"name \").replace(\"'id'\",\"id \")", "def words_to_object(s):\n s = s.split()\n return \"[\"+\", \".join(f\"{{name : '{s[i]}', id : '{s[i+1]}'}}\" for i in range(0,len(s),2))+\"]\"", "def words_to_object(s):\n return'['+', '.join(f\"{{name : '{a}', id : '{b}'}}\"for a,b in zip(*[iter(s.split())]*2))+']'", "def words_to_object(s):\n nis = s.split()\n dicts_list = [{'name': name, 'id': id} for name, id in zip(nis[::2], nis[1::2])]\n return f\"{dicts_list}\".replace(\"'name'\", \"name \").replace(\"'id'\", \"id \")", "def words_to_object(s):\n ss = s.split()\n return '[' + ', '.join(['{'+'name : \\'{0}\\', id : \\'{1}\\''.format(ss[i*2], ss[i*2+1])+'}' for i in range(len(ss)//2)]) + ']'", "def words_to_object(s):\n s = s.split()\n arr = [{'name':i,'id':j} for i,j in zip(s[::2], s[1::2])]\n return str(arr).replace(\"'name':\",'name :').replace(\"'id':\",'id :')", "def words_to_object(s):\n a=s.split(' ')\n r=[]\n for name,_id in zip(a[::2],a[1::2]):\n r.append(\"{{name : '{}', id : '{}'}}\".format(name,_id))\n return '[{}]'.format(', '.join(r))", "def words_to_object(s):\n if s:\n s=s.split(\" \")\n return \"[\"+', '.join(\"{\"+\"name : '{}', id : '{}'\".format(s[i],s[i+1])+\"}\" for i in range(0,len(s),2))+\"]\"\n else:\n return '[]'", "def words_to_object(s):\n s = s.split()\n return \"[\" + ', '.join([\"{name : '%s', id : '%s'}\"%(i,j) for i,j in zip(s[::2], s[1::2])]) + \"]\""] | {"fn_name": "words_to_object", "inputs": [["red 1 yellow 2 black 3 white 4"], ["1 red 2 white 3 violet 4 green"], ["1 1 2 2 3 3 4 4"], ["#@&fhds 123F3f 2vn2# 2%y6D @%fd3 @!#4fs W@R^g WE56h%"], [""]], "outputs": [["[{name : 'red', id : '1'}, {name : 'yellow', id : '2'}, {name : 'black', id : '3'}, {name : 'white', id : '4'}]"], ["[{name : '1', id : 'red'}, {name : '2', id : 'white'}, {name : '3', id : 'violet'}, {name : '4', id : 'green'}]"], ["[{name : '1', id : '1'}, {name : '2', id : '2'}, {name : '3', id : '3'}, {name : '4', id : '4'}]"], ["[{name : '#@&fhds', id : '123F3f'}, {name : '2vn2#', id : '2%y6D'}, {name : '@%fd3', id : '@!#4fs'}, {name : 'W@R^g', id : 'WE56h%'}]"], ["[]"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 4,451 |
def words_to_object(s):
|
bd829ab8e4a0a160a1b05ec5d2fddba1 | UNKNOWN | You are the best freelancer in the city. Everybody knows you, but what they don't know, is that you are actually offloading your work to other freelancers and and you rarely need to do any work. You're living the life!
To make this process easier you need to write a method called workNeeded to figure out how much time you need to contribute to a project.
Giving the amount of time in `minutes` needed to complete the project and an array of pair values representing other freelancers' time in `[Hours, Minutes]` format ie. `[[2, 33], [3, 44]]` calculate how much time **you** will need to contribute to the project (if at all) and return a string depending on the case.
* If we need to contribute time to the project then return `"I need to work x hour(s) and y minute(s)"`
* If we don't have to contribute any time to the project then return `"Easy Money!"` | ["def work_needed(project_minutes, freelancers):\n available_minutes = sum(hours * 60 + minutes for hours, minutes in freelancers)\n workload_minutes = project_minutes - available_minutes\n if workload_minutes <= 0:\n return 'Easy Money!'\n else:\n hours, minutes = divmod(workload_minutes, 60)\n return 'I need to work {} hour(s) and {} minute(s)'.format(hours, minutes)", "def work_needed(projectMinutes, freeLancers):\n time = projectMinutes - sum(fl[0]*60+fl[1] for fl in freeLancers)\n if time <= 0: return \"Easy Money!\"\n else: return \"I need to work {} hour(s) and {} minute(s)\".format(time//60, time%60)", "def work_needed(projMin, others):\n h, m = map(sum, zip(*others))\n needed = projMin - sum(t*c for t,c in zip((h,m),(60,1)) )\n return \"Easy Money!\" if needed <= 0 else f\"I need to work {needed//60} hour(s) and {needed%60} minute(s)\"", "def work_needed(projectMinutes, freeLancers):\n x = projectMinutes \n for flance in freeLancers:\n x -= (flance[0]*60 + flance[1])\n if(x > 0):\n return(\"I need to work \" + str(int (x / 60)) + \" hour(s) and \" + str(x%60) + \" minute(s)\")\n return(\"Easy Money!\")", "def work_needed(project, freelancers):\n to_work = project - sum(h*60 + m for h, m in freelancers)\n return \"I need to work {} hour(s) and {} minute(s)\".format(*divmod(to_work, 60)) if to_work > 0 else \"Easy Money!\"", "def work_needed(projectMinutes, freeLancers):\n s = projectMinutes - sum(h * 60 + m for h, m in freeLancers)\n return 'Easy Money!' if s <= 0 else 'I need to work {} hour(s) and {} minute(s)'.format(*divmod(s, 60))", "def work_needed(pm, fls):\n pm -= sum(60 * h + m for h, m in fls)\n return f'I need to work {pm // 60} hour(s) and {pm % 60} minute(s)' if pm > 0 else \"Easy Money!\"", "def work_needed(mins, free):\n w = mins - sum(60 * h + m for h, m in free) \n return f'I need to work {w//60} hour(s) and {w%60} minute(s)' if w > 0 else 'Easy Money!' ", "def work_needed(projectMinutes, freeLancers):\n req = projectMinutes - sum( 60*f[0] + f[1] for f in freeLancers )\n if req <= 0: return 'Easy Money!'\n return f\"I need to work {req//60} hour(s) and {req%60} minute(s)\"", "def work_needed(projectMinutes, freeLancers):\n diff = projectMinutes - sum(h*60 + m for h, m in freeLancers)\n return \"Easy Money!\" if diff <= 0 else \"I need to work {} hour(s) and {} minute(s)\".format(diff//60, diff%60)"] | {"fn_name": "work_needed", "inputs": [[60, [[1, 0]]], [60, [[0, 0]]]], "outputs": [["Easy Money!"], ["I need to work 1 hour(s) and 0 minute(s)"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,497 |
def work_needed(projectMinutes, freeLancers):
|
ef47391e60e819611a76e7bfd82f0906 | UNKNOWN | The pair of integer numbers `(m, n)`, such that `10 > m > n > 0`, (below 10), that its sum, `(m + n)`, and rest, `(m - n)`, are perfect squares, is (5, 4).
Let's see what we have explained with numbers.
```
5 + 4 = 9 = 3²
5 - 4 = 1 = 1²
(10 > 5 > 4 > 0)
```
The pair of numbers `(m, n)`, closest to and below 50, having the property described above is `(45, 36)`.
```
45 + 36 = 81 = 9²
45 - 36 = 9 = 3²
(50 > 45 > 36 > 0)
```
With the function `closest_pair_tonum()`, that receives a number `upper_limit`, as an upper limit, we should be able to obtain the closest pair to `upper_limit`, that fulfills the property described above.
The function should return the largest pair of numbers `(m, n)`, satisfying `upper_limit > m > n > 0`. Note that we say pair A `(a0, a1)` is larger than pair B `(b0, b1)` when `a0 > b0` or `a0 == b0 and
a1 > b1`.
Let's see some cases:
```python
closest_pair_tonum(10) == (5, 4) # (m = 5, n = 4)
closest_pair_tonum(30) == (29, 20)
closest_pair_tonum(50) == (45, 36)
```
Happy coding and enjoy it!!
(We will be having a second part of a similar exercise (in some days) that will need a faster algorithm for values of `upper_limit` < 1000) | ["def closest_pair_tonum(uLim):\n return next( (a,b) for a in reversed(range(1,uLim)) for b in reversed(range(1,a))\n if not (a+b)**.5%1 and not (a-b)**.5%1 )", "from itertools import combinations\ndef closest_pair_tonum(upper_lim):\n return next((x, y) for x, y in combinations(range(upper_lim - 1, 0, -1), 2) if ((x + y) ** 0.5).is_integer() and ((x - y) ** 0.5).is_integer())", "from math import sqrt\n\ndef is_square(n):\n return round(sqrt(n)) ** 2 == n\n\ndef closest_pair_tonum(lim):\n for i in range(lim-1, 0, -1):\n for j in range(i-1, 0, -1):\n if is_square(i + j) and is_square(i - j):\n return i, j", "def closest_pair_tonum(lim):\n return next((m, n) for m in range(lim-1, 0, -1) for n in range(m-1, 0, -1) if not ((m+n)**0.5%1 or (m-n)**0.5%1))\n", "from math import sqrt\n\ndef is_sqrt(x):\n y = sqrt(x)\n return y == round(y)\n\ndef closest_pair_tonum(x):\n for i in range(x-1, 1, -1):\n for j in range(i-1, 0, -1):\n if is_sqrt(i+j) and is_sqrt(i-j):\n return(i, j)\n", "import itertools\n\nsquares = {i*i for i in range(1, 2000+1)}\n\n\ndef closest_pair_tonum(upper_lim):\n return next((a, b)\n for a, b in itertools.combinations(range(upper_lim-1, 0, -1), 2)\n if a + b in squares and a - b in squares\n )", "def closest_pair_tonum(upper_lim):\n sq = lambda x: int(x ** 0.5) == x ** 0.5\n for i in range(upper_lim - 1, 1, -1):\n for j in range(i - 1, 1, -1):\n if sq(i + j) * sq(i - j):\n return (i, j)"] | {"fn_name": "closest_pair_tonum", "inputs": [[10], [30], [50], [100], [150], [200]], "outputs": [[[5, 4]], [[29, 20]], [[45, 36]], [[97, 72]], [[149, 140]], [[197, 28]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,594 |
def closest_pair_tonum(upper_lim):
|
2d9e46fda41d52d4a78b325a7de2b326 | UNKNOWN | We want an array, but not just any old array, an array with contents!
Write a function that produces an array with the numbers `0` to `N-1` in it.
For example, the following code will result in an array containing the numbers `0` to `4`:
```
arr(5) // => [0,1,2,3,4]
``` | ["def arr(n=0): \n return list(range(n))", "def arr(n=0): \n return [i for i in range(n)]", "def arr(n=0): \n return [*range(n)]", "def arr(n=0): \n # [ the numbers 0 to N-1 ]\n aux = []\n for x in range(n):\n aux.append(x)\n return aux\n", "def arr(n=int()): return list(range(int(),n))", "arr = lambda n=0: list(range(n))", "def arr(n=0): \n lst = [i for i in range(n)]\n return lst", "def arr(n=0): \n return [ x for x in range(n)] if n>0 else []", "def arr(n = ''): \n # [ the numbers 0 to N-1 ]\n n = str(n)\n if len(n) == 0:\n return []\n n = int(n)\n array = []\n for i in range(n):\n array.append(i)\n return(array)\n", "def arr(n = None):\n \n if n is None:\n return []\n \n result = []\n for i in range(0, n):\n result.append(i)\n return result\n\n\n # [ the numbers 0 to N-1 ]\n", "arr = lambda n=0: [i for i in range(n)]", "def arr(n=0): #To handle a call without an argument, e.g. arr(), default arg to 0\n if n==0:\n return []\n else:\n return [i for i in range(n)]\n#end function arr\n", "def arr(n = 0):\n arrey = []\n num = 0\n for i in range(n):\n arrey.append(num)\n num+=1\n return arrey\n", "arr=lambda a=0:[*range(a)]", "from typing import List, Tuple, Optional\n\ndef arr(*args: Optional[Tuple[int]]) -> List[int]:\n \"\"\" Get an array with the numbers 0 to N-1 in it. \"\"\"\n return list(range(0, *args))", "arr\\\n=\\\nlambda\\\nn\\\n=\\\n0\\\n:\\\n[\n*\nrange\n(\nn\n)\n]", "arr = lambda _=0: [*range(_)]", "def arr(n=0):\n arr = list()\n if n>0:\n for i in range(0,n):\n arr.append(i)\n else:\n return []\n return arr", "def arr(n=0): \n if n == None: return []\n if n == 0: return []\n if n == 1: return [0]\n else: return arr(n-1) + [n-1]", "def arr(*n):\n try:\n return [*range(n[0])]\n except:\n return []", "arr=lambda a=0:list(range(a))", "def arr(n=0):\n arrays = []\n for x in range(n):\n arrays.append(x)\n return arrays", "def arr(n=0):\n array = []\n for num in range(0, n):\n array.append(num)\n return array", "def arr(n=0): \n # [ the numbers 0 to N-1 ]\n myarray = []\n for i in range(0,n): myarray.append(i)\n \n return myarray", "def arr(n = 0):\n count = []\n for i in range(n):\n count.append(i)\n return(count)\n \n", "def arr(n = 0): \n list = []\n \n if n:\n for x in range(n):\n list.append(x)\n \n return list", "def arr(n=0): \n tmp=[]\n if n>0:\n for j in range(0,n):\n tmp.append(j)\n return(tmp)", "def arr(n=0): \n lst = list(range(n))\n return lst\n\n \n", "def arr(n = None):\n if n is None:\n return []\n new_arr = []\n for x in range(0,n):\n new_arr.append(x)\n return new_arr\n\n\n", "def arr(*n): \n # [ the numbers 0 to N-1 ]\n if len(n) == 0:\n x = 0\n else:\n x = n[0]\n return list(range(0, x))", "def arr(n=None):\n\n if n == 0 or n == None:\n array = []\n else:\n array = [i for i in range(n)]\n return array", "def arr(n=None):\n if n is None:\n return []\n L = []\n for i in range(n):\n L.append(i)\n return L", "def arr(n = 0): \n i = 0\n tab = []\n \n while i < n:\n tab.append(i)\n i += 1\n return tab\n", "def arr(n=None):\n if not n:\n return []\n else:\n return [n for n in range(n)]", "def arr(n = None):\n res = []\n \n if n == None:\n return res\n else:\n for i in range(n):\n res.append(i)\n return res\n\n\n # [ the numbers 0 to N-1 ]\n", "def arr(n = None): \n array = []\n if n is None:\n return array\n elif n >= 0:\n for i in range(n):\n array.append(i)\n return array", "def arr(n=0): \n solution = []\n x = -1\n if n == 0:\n return []\n else:\n while len(solution) < n:\n x += 1\n solution.append(x)\n return solution\n", "def arr(n=0): \n solution = []\n x = -1\n if n == 0:\n return []\n else:\n while len(solution) < n:\n x += 1\n solution.append(x)\n return solution", "def arr(n=None): # None for if no arguments passed\n # [ the numbers 0 to N-1 ]\n a = []\n if n is None:\n return a\n else:\n for i in range(n):\n a.append(i)\n return a", "import numpy\ndef arr(n=0):\n return list(range(n))\n", "def arr(n=None): \n s = []\n if n == None:\n return s\n else:\n for i in range(n):\n s.append(i)\n return s", "def arr(n=0):\n\n array = []\n for i in range(n):\n array.append(i)\n i += 1\n return array", "def arr(n=-1):\n if n == -1:\n return []\n else:\n return [num for num in range(n)]", "def arr(n=0): \n # [ the numbers 0 to N-1 ]\n lst = []\n for num in range(0, n) :\n if num not in lst : \n lst.append(num)\n else :\n return ''\n \n return lst ", "def arr(n = 0):\n lis = []\n if not n:\n return lis\n else:\n for i in range (0, n):\n lis.append(i)\n return lis", "def arr(n = []):\n if n == []:\n return []\n a = range(0, n)\n return list(a) if n > 0 else []", "def arr(n): \n return(list(range(n)))\ndef arr(n=0): \n return(list(range(n)))\n # [ the numbers 0 to N-1 ]\n", "def arr(n = 0): \n if n is None: \n return n\n return list(range(n))", "def arr(n=0):\n n = list(range(0, n))\n return n# [ the numbers 0 to N-1 ]", "def arr(n = -1): \n if n != -1:\n return [i for i in range(n)]\n else:\n return list()", "def arr(*n): \n return list(range(n[0])) if len(n) > 0 else []", "def arr(n=0): \n test = []\n if (n > 0):\n for i in range(n):\n test.append(i)\n return test \n", "def arr(n=0): \n i = 0\n a = [i for i in range(0, n)]\n return a", "def arr(*n): \n # [ the numbers 0 to N-1 ]\n print(*n)\n res = []\n if(n == () or n == 0):\n return []\n else:\n for i in range((*n)):\n res.append(i)\n return res", "def arr(n=0): \n list = []\n for n in range(0,n):\n list.append(n)\n \n return list", "def arr(n=0):\n a = [] \n for i in range(n):\n a.append(i)\n return a\n\nprint(arr(4))\nprint(arr(0))\nprint(arr())", "def arr(n=0): \n if n == 0:\n lst = []\n return lst\n else:\n return [x for x in range(n)]", "def arr(*n):\n for m in n:\n return [i for i in range(0,m)]\n return []", "def arr(n=0): \n list = []\n while n != 0:\n list.append(n-1)\n n -= 1\n list.sort()\n return list\n", "def arr(n=0): \n \n i = 0;\n ergebnis = [];\n \n if n == ():\n return ergebnis;\n else:\n \n while i < n:\n ergebnis.append(i);\n i = i + 1;\n return ergebnis;", "def arr(*args): \n return [i for i in range(args[0])] if args else []", "def arr(n=0): \n \n return [*list(range(0,n,1))]\n", "def arr(n=0):\n range(n)\n return list(range(n))", "def arr(n=0): \n if n == 0 or n is None: \n return []\n else:\n return list(range(n))\n", "def arr(n=0): \n if n == 0:\n return []\n else:\n if n == '' in arr(n):\n return list(print(-1))\n else:\n return list(range(n))\n", "def arr(n=''):\n if n == '':\n return []\n else:\n lista = []\n n = int(n)\n for i in range(n):\n caracter =int(i)\n lista.append(caracter)\n return lista", "def arr(n: int = 0) -> list:\n return [*list(range(n))] if n > 0 else []\n", "def arr(n = 0): \n # [ the numbers 0 to N-1 ]\n array = []\n counter = 0\n while counter < n:\n array.append(counter)\n counter += 1 \n return array", "\ndef arr(n = 0):\n if n > 0:\n x = []\n for i in range(n):\n x.append(i)\n return x\n else:\n return []\n", "\n\ndef arr(n=None): \n # [ the numbers 0 to N-1 ]\n lst = []\n if n is None:\n return lst\n else:\n while n > 0:\n lst.append(n-1)\n n -= 1\n return sorted(lst)\n", "def arr(n=0): \n lst = []\n if n > 0:\n for n in range(n):\n lst.append(n)\n print(lst)\n return lst\n else:\n return lst\n \nprint(arr())", "\n\ndef arr(n=[]):\n if not n:\n return []\n else:\n return list(range(0,n))", "def arr(n=0):\n list = []\n if n == 0:\n return list\n for i in range(0, n):\n list.append(i)\n return list", "def arr(n = None):\n l_1 = []\n if n is not None:\n for i in range(0,n):\n l_1.append(i)\n else:\n l_1 = []\n return l_1\n", "def arr(*args): \n return [number for number in range(0,*args)]", "def arr(n=None):\n if n is not None:\n return list(range(n))\n else:\n return []", "def arr(n=0):\n if n==0:\n return []\n else:\n return [i for i in range(n)]", "def arr(n=0): \n arr =[]\n if n == 0:\n return arr\n for i in range(n):\n arr.append(i)\n return arr", "def arr(n = 0): \n # [ the numbers 0 to N-1 ]\n array = []\n x = 0\n while x < n:\n array.append(x)\n x+= 1\n return array", "def arr(n=0): \n # [ the numbers 0 to N-1 ]\n num_list = []\n \n if n < 1:\n return num_list \n else:\n for i in range(n):\n if i < n:\n num_list.append(i) \n return num_list", "def arr(n=None): \n if n:\n return [i for i in range(n)]\n else:\n return []", "arr = lambda n = 0: [x for x in range(0, n)]", "def arr(n = 0): \n List = []\n for x in range(n):\n List.append(x)\n return List", "def arr(n=[]):\n if n==[]:\n answer=[]\n else:\n answer=[n for n in range(n)]\n return answer", "def arr(*n): \n try:\n return [i for i in range(n[0]) if n !=0]\n except IndexError: \n return []", "def arr(n=None): \n # [ the numbers 0 to N-1 ]\n array = []\n if(n is not None and n>=0):\n for i in range(n):\n array.append(i)\n return array", "def arr(n = 0): \n if n == 0:\n return []\n return list(range(0,n))", "def arr(n = 0):\n content = []\n if(n > 0):\n for i in range(n):\n content.append(i)\n return content", "def arr(n = 0):\n xyu = []\n while n > 0:\n n -= 1\n xyu.append (n)\n xyu.sort ()\n return xyu", "def arr(n=0):\n print(type(n))\n array = []\n for x in range(n):\n array.append(x)\n print (type(array[x]))\n return array", "def arr(n = 0): \n lst = []\n if n == 0:\n return []\n else:\n for i in range(n):\n lst.append(i)\n return lst", "def arr(n = 0): \n # [ the numbers 0 to N-1 ]\n i = 0;\n a = []\n if n == 0:\n return []\n while(i < n):\n a.append(i)\n i+=1\n return a", "def arr(n = 0):\n a = []\n i = 0\n while i < n:\n a.append(i)\n i = i + 1\n return a", "def arr(n=None):\n l = []\n if (n==None or n==0): return l\n for i in range(n):\n l.append(i)\n return l", "def arr(n=0):\n # [ the numbers 0 to N-1 ]\n tomb = []\n for i in range(n):\n tomb.append(i)\n return tomb\n", "def arr(n=0):\n if not arr:\n return []\n new_list = []\n for element in range(n):\n new_list.append(element)\n return new_list", "def arr(n=0): \n c=[]\n for i in range(n):\n c.append(i)\n return c\n\n", "def arr(n=None): \n if n is None:\n return []\n else:\n return list(range(n))", "def arr(*args): \n array = []\n if args:\n for i in range(args[0]):\n array.append(i)\n \n return array", "def arr(n=0): \n # [ the numbers 0 to N-1 ]\n if(n):\n return list(range(0,n))\n else:\n return []"] | {"fn_name": "arr", "inputs": [[4], [0]], "outputs": [[[0, 1, 2, 3]], [[]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 12,505 |
def arr(n=0):
|
ee6cc1a5371f705ba7a883395094156c | UNKNOWN | ## Find Mean
Find the mean (average) of a list of numbers in an array.
## Information
To find the mean (average) of a set of numbers add all of the numbers together and divide by the number of values in the list.
For an example list of `1, 3, 5, 7`
1. Add all of the numbers
```
1+3+5+7 = 16
```
2. Divide by the number of values in the list. In this example there are 4 numbers in the list.
```
16/4 = 4
```
3. The mean (or average) of this list is 4 | ["def find_average(nums):\n return float(sum(nums)) / len(nums) if len(nums) !=0 else 0", "def find_average(nums):\n return sum(nums) / float(len(nums)) if nums else 0", "def find_average(nums):\n return sum(nums) / len(nums) if nums else 0", "import numpy\n\ndef find_average(nums):\n return numpy.mean(nums) if nums else 0", "def find_average(nums):\n try:\n return sum(nums) * 1.0 / len(nums)\n except:\n return 0", "from numpy import mean\n\ndef find_average(nums):\n return mean(nums or [0])", "import numpy as np\n\nfind_average = lambda x: np.mean(x or 0)", "import numpy as np\ndef find_average(N):\n return 0 if len(N)<1 else np.mean(N)\n", "find_average = lambda n: sum(n) / float(len(n)) if len(n) > 0 else 0", "def find_average(N):\n return 0 if not N else sum(N)/float(len(N)) \n", "find_average = lambda n: float(sum(n)) / len(n) if n else 0", "find_average = lambda nums: 0 if not nums else sum(nums) / (len(nums) + .0)", "def find_average(nums):\n return sum(nums) / len(nums) if len(nums) else 0", "from numpy import mean\ndef find_average(N):\n return 0 if len(N)<1 else mean(N)\n", "from numpy import mean \ndef find_average(nums):\n if nums:\n return mean(nums)\n return 0", "from numpy import mean\n\ndef find_average(nums):\n return mean(nums) if nums else 0", "find_average = lambda nums: sum(nums) / float(len(nums) or 1)", "find_average=lambda nums: 1.0*sum(nums)/len(nums) if len(nums) else 0", "def find_average(nums):\n return int(nums != []) and float(sum(nums))/len(nums)", "def find_average(nums):\n return __import__('statistics').mean(nums) if nums else 0", "find_average = lambda a: __import__(\"numpy\").mean(a) if a else 0", "from typing import List, Union\n\ndef find_average(nums: List[int]) -> Union[int, float]:\n \"\"\" Get the mean (average) of a list of numbers in an array. \"\"\"\n return sum(nums) / len(nums) if nums else 0", "def find_average(nums):\n return 0 if len(nums) < 1 else sum(nums) / len(nums) ", "def find_average(nums):\n try:\n return float(sum(nums)) / len(nums)\n except ZeroDivisionError:\n return 0", "def find_average(nums):\n return nums!=[] and sum(nums) / len(nums)", "def find_average(nums):\n return sum(nums) / (len(nums) + 0. or 1.)", "def find_average(nums):\n return sum(nums)/float(max(1,len(nums)))", "def find_average(nums):\n if len(nums) == 0:\n return 0\n return float(sum(nums)) / float(len(nums))\n #your code here\n", "def find_average(nums):\n items = 0\n total = 0.0\n for a in nums:\n items += 1\n total += a\n return 0 if items == 0 else total / items\n\n\n# def find_average(nums):\n # length = len(nums)\n # return sum(nums) / float(length) if length > 0 else 0\n", "def find_average(nums):\n a = sum(nums)\n b = len(nums)\n \n if (a == 0) or (b == 0):\n return 0\n else:\n return(a/b)", "def find_average(nums):\n return 0 if not len(nums) else sum(nums)/len(nums)", "def find_average(nums):\n #your code here\n total = 0\n if len(nums) > 0:\n for i in nums:\n total += i \n le = len(nums)\n print((total/le))\n return total/le\n else: \n return 0\n", "find_average = lambda a: sum(a)/len(a) if a else 0 ", "def find_average(nums):\n nb = len(nums)\n return nb != 0 and sum(nums) / nb ", "from statistics import mean\n\ndef find_average(nums):\n return mean(nums) if len(nums) > 0 else 0", "def find_average(nums):\n sum = 0\n for num in nums:\n sum += num\n \n print(len(nums))\n try:\n avg = sum/len(nums)\n except:\n avg = sum\n \n return avg", "def find_average(nums):\n if len(nums) == 0: return 0\n sum = 0\n for val in nums:\n sum += val\n return sum / len(nums)", "def find_average(nums):\n x = sum(nums)\n y = len(nums)\n if y == 0:\n return 0\n return x / y", "def find_average(nums):\n if nums == 0:\n return 0\n elif len(nums)==0:\n return 0\n else:\n return sum(nums)/len(nums)\n #your code here\n", "def find_average(nums): \n n = 0\n if nums == []:\n return n\n \n else:\n return sum(nums)/len(nums)\n", "import statistics\n\ndef find_average(data):\n return statistics.mean(data) if data else 0", "def find_average(nums):\n total = 0\n for i in range(len(nums)):\n total += nums[i]\n try:\n per = total / len(nums)\n return per\n except ZeroDivisionError:\n return 0", "def find_average(nums):\n #your code here\n total = 0\n for num in nums:\n total += num\n return total / (len(nums) if len(nums) > 0 else 1)", "def find_average(nums):\n sum = 0\n if not nums:\n return sum\n else:\n for num in nums:\n sum = sum +num\n average = sum / len(nums)\n return average", "def find_average(nums):\n if nums == []: \n return 0\n sum = 0\n for i in range(len(nums)): \n sum = sum + nums[i]\n return sum/len(nums)", "def find_average(nums):\n total = 0\n for i in nums:\n total += i\n if nums:\n return total / len(nums)\n else: \n return 0\n", "def find_average(nums):\n sum = 0\n if len(nums) >0:\n for i in nums:\n sum += i\n return sum/len(nums)\n else:\n return 0", "def find_average(nums):\n s = 0\n if nums == []:\n return 0\n else:\n for i in range(len(nums)):\n s = s + nums[i]\n return s/len(nums)", "def find_average(nums):\n if len(nums) < 1:\n return 0\n else:\n return sum(nums) / len(nums)", "import statistics\ndef find_average(nums):\n if len(nums)==0:\n return 0\n else:\n return statistics.mean(nums)", "from numpy import mean\ndef find_average(nums):\n return mean(nums or 0)", "def find_average(nums: list) -> float:\n return 0 if len(nums) == 0 else sum(nums) / len(nums)", "from numpy import mean\ndef find_average(nums):\n return mean(nums) if nums != [] else 0", "def find_average(nums):\n try:\n a = len(nums)\n b = sum(nums)\n c = b/a\n except:\n return 0\n return c", "def find_average(nums):\n if len(nums) == 0:\n return 0\n sum=0\n for num in nums:\n sum+=num\n return sum/len(nums)", "def find_average(nums):\n return sum(nums) / len(nums) if sum(nums) > 0 else 0", "def find_average(nums):\n if len(nums) == 0 or nums == []:\n return 0\n else:\n return sum(nums)/len(nums)\n", "from statistics import mean\ndef find_average(nums):\n if nums:\n return mean(nums)\n return 0", "from statistics import mean\ndef find_average(nums):\n #your code here\n return mean(nums) if len(nums) != 0 else 0", "def find_average(s):\n return sum(s)/len(s) if len(s)>0 else 0", "def find_average(n):\n return sum(n)/len(n) if len(n)>0 else 0", "def find_average(nums):\n a = sum(nums)\n return 0 if not nums else a / len(nums)", "def find_average(nums):\n sum = 0\n for n in nums:\n sum += n\n if len(nums) == 0:\n return 0\n sum /= len(nums)\n return sum", "def find_average(n):\n return sum(n)/len(n) if n else 0", "import statistics\ndef find_average(nums):\n try:\n return statistics.mean(nums)\n except:\n return 0", "def find_average(nums):\n sum = 0\n if len(nums) == 0:\n return 0\n else:\n for i in nums:\n sum += i\n return sum / len(nums)", "def find_average(nums):\n try:\n accumulator = 0\n for eachnumber in nums:\n accumulator = accumulator + eachnumber\n return accumulator / len(nums)\n except ZeroDivisionError as zero_error:\n return 0", "import statistics\ndef find_average(nums):\n if len(nums) > 0:\n return statistics.mean(nums)\n return 0", "def find_average(nums):\n #your code here\n if len(nums)==0:\n return 0\n sums=sum(nums)\n avg=sums/len(nums)\n return avg", "def find_average(nums):\n if nums == []:\n return 0\n else:\n x = 0\n for i in nums:\n x = i +x\n y = x / len(nums)\n\n return y", "def find_average(nums):\n total = sum(nums)\n if len(nums) > 0:\n return total / len(nums)\n return 0", "def find_average(nums):\n return nums and sum(nums)/len(nums) or 0", "def find_average(nums):\n #your code here\n sum = 0\n for n in nums:\n sum += n\n if len(nums) == 0:\n avg = 0\n else:\n avg = sum / len(nums)\n return avg", "import numpy as np\ndef find_average(nums):\n if len(nums) ==0: return 0\n return np.mean(nums)", "def find_average(l):\n return sum(l) / len(l) if l else 0", "def find_average(nums):\n sum = 0\n n = 0\n for i in nums:\n sum += i\n n += 1\n if n > 0:\n return sum / n\n else:\n return 0", "def find_average(nums):\n tot = 0\n mean = 0\n \n if len(nums) == 0:\n return 0 \n \n for i, number in enumerate(nums):\n tot += number\n \n mean = tot/len(nums) \n return mean\n #your code here\n", "import numpy as np\n\ndef find_average(nums):\n return np.mean(nums) if len(nums) > 0 else 0", "def find_average(nums):\n sum = 0\n if (len(nums) == 0):\n return 0\n for i in range(len(nums)):\n sum = sum + nums[i]\n return sum/len(nums)", "def find_average(nums):\n return sum(nums)/len(nums) if len(nums)>=1 else 0", "def find_average(nums):\n #your code here\n if nums == []: #or len(nums)==0:\n return 0\n else:\n b=len(nums)\n print(b)\n a=sum(nums)\n c=a/b\n return c\n", "def find_average(nums):\n if len(nums) == 0:\n return 0\n\n total = 0\n \n for num in nums:\n total+= num\n \n return total/len(nums)", "def find_average(nums):\n if len(nums) == 0:\n return 0\n s = sum(nums)\n n = s/len(nums)\n return n", "def find_average(nums):\n if not nums:\n return 0\n else:\n return sum(nums)/len(nums)", "def find_average(nums):\n average = 0\n sum_nums = 0\n count_nums = 0\n for num in nums:\n sum_nums += num\n count_nums += 1\n average = (sum_nums / count_nums)\n return average", "def find_average(nums):\n try:\n return sum(nums)/len(nums)\n except (ZeroDivisionError):\n return False", "def find_average(nums):\n if (not nums): return 0\n sum = 0\n quantity = 0\n for value in nums:\n sum = sum + value\n quantity += 1\n return sum/quantity\n", "def find_average(nums):\n #your code here\n n = 0\n for n in nums:\n n = sum(nums)/len(nums)\n if len(nums) == 0:\n print('Error')\n else:\n print(n)\n return n\n", "def find_average(nums):\n print(nums)\n #return [sum(nums)/len(nums) if len(nums)>0 else 0]\n items = 0\n total = 0.0\n for a in nums:\n items += 1\n total += a\n return 0 if items == 0 else total / items\n", "def find_average(nums):\n return sum(i for i in nums)/len(nums) if nums!=[] else 0", "def find_average(nums):\n try:\n return sum(nums)/len(nums)\n except ZeroDivisionError as ak:\n return 0\n", "def find_average(nums):\n \n length = len(nums)\n if length == 0:\n return 0\n \n total = sum(nums)\n \n mean = total / length\n \n return mean", "def find_average(nums):\n if len(nums) >= 1:\n return sum(nums) / len(nums)\n else:\n return 0", "def find_average(nums):\n if len(nums):\n return sum(nums)/len(nums)\n return 0", "def find_average(nums):\n if nums:\n average = sum(nums)/len(nums)\n else:\n average = 0\n return average", "def find_average(nums):\n if len(nums) == 0:\n return 0\n else:\n total = sum(nums)\n avg = total / len(nums)\n return avg", "def find_average(nums):\n if nums == []:\n return 0\n else:\n a=sum(nums)/len(nums)\n return a", "def find_average(nums):\n if len(nums)==0:\n return 0\n a=0\n for i in nums: a+=i\n return a/len(nums)", "def find_average(nums):\n #your code here\n if nums != []:\n return sum(nums)/len(nums)\n else:\n return 0"] | {"fn_name": "find_average", "inputs": [[[1]], [[1, 3, 5, 7]], [[-1, 3, 5, -7]], [[5, 7, 3, 7]], [[]]], "outputs": [[1], [4], [0], [5.5], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 12,583 |
def find_average(nums):
|
5cfec5ef61b642de7df6175430df0cb3 | UNKNOWN | In this Kata, two players, Alice and Bob, are playing a palindrome game. Alice starts with `string1`, Bob starts with `string2`, and the board starts out as an empty string. Alice and Bob take turns; during a turn, a player selects a letter from his or her string, removes it from the string, and appends it to the board; if the board becomes a palindrome (of length >= 2), the player wins. Alice makes the first move. Since Bob has the disadvantage of playing second, then he wins automatically if letters run out or the board is never a palindrome. Note also that each player can see the other player's letters.
The problem will be presented as `solve(string1,string2)`. Return 1 if Alice wins and 2 it Bob wins.
For example:
```Haskell
solve("abc","baxy") = 2 -- There is no way for Alice to win. If she starts with 'a', Bob wins by playing 'a'. The same case with 'b'. If Alice starts with 'c', Bob still wins because a palindrome is not possible. Return 2.
solve("eyfjy","ooigvo") = 1 -- Alice plays 'y' and whatever Bob plays, Alice wins by playing another 'y'. Return 1.
solve("abc","xyz") = 2 -- No palindrome is possible, so Bob wins; return 2
solve("gzyqsczkctutjves","hpaqrfwkdntfwnvgs") = 1 -- If Alice plays 'g', Bob wins by playing 'g'. Alice must be clever. She starts with 'z'. She knows that since she has two 'z', the win is guaranteed. Note that she also has two 's'. But she cannot play that. Can you see why?
solve("rmevmtw","uavtyft") = 1 -- Alice wins by playing 'm'. Can you see why?
```
Palindrome lengths should be at least `2` characters. More examples in the test cases.
Good luck! | ["from collections import Counter\n\ndef solve(*args):\n c1, c2 = map(Counter, args)\n return 2 - any(c1[k]-c2[k] >= 2 and k not in c2 for k in c1)", "def solve(str1, str2):\n return 2 - any(str1.count(c) > 1 and c not in str2 for c in str1)", "def solve(a, b):\n return [2, 1][any(a.count(e) > 1 for e in a if e not in b)]", "from collections import Counter\n\ndef solve(str1, str2):\n C, S = Counter(str1), set(str2)\n return all(v == 1 or k in S for k,v in C.items()) + 1", "def solve(str1, str2):\n s = set(str1) - set(str2)\n return 1 if any(c for c in s if str1.count(c) > 1) else 2 ", "def solve(str1,str2):\n for i in range(len(str1)):\n if str1[i] not in str2 and str1.count(str1[i]) > 1: return 1\n return 2\n", "solve=lambda s,s1:any(s.count(i)>=2 and i not in s1 for i in s) or 2", "solve=lambda Q,S:1 if any(V in Q[1+F:] and V not in S for F,V in enumerate(Q)) else 2", "from collections import Counter\ndef solve(str1,str2):\n c1=Counter(str1)\n for k,v in c1.items():\n if v>=2 and k not in str2:\n return 1\n return 2", "def solve(str1,str2):\n a=set(str1)\n return 1 if any(str1.count(i)>1 and i not in str2 for i in a) else 2"] | {"fn_name": "solve", "inputs": [["abc", "xyz"], ["abc", "axy"], ["abc", "bax"], ["btzgd", "svjyb"], ["eyfjy", "ooigv"], ["mctimp", "eyqbnh"], ["qtkxttl", "utvohqk"]], "outputs": [[2], [2], [2], [2], [1], [1], [2]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,215 |
def solve(str1, str2):
|
44b2e398d7cb9518ade1255b79567a6c | UNKNOWN | In this Kata, you will be given a string and your task will be to return the length of the longest prefix that is also a suffix. A prefix is the start of a string while the suffix is the end of a string. For instance, the prefixes of the string `"abcd"` are `["a","ab","abc"]`. The suffixes are `["bcd", "cd", "d"]`. You should not overlap the prefix and suffix.
```Haskell
for example:
solve("abcd") = 0, because no prefix == suffix.
solve("abcda") = 1, because the longest prefix which == suffix is "a".
solve("abcdabc") = 3. Longest prefix which == suffix is "abc".
solve("aaaa") = 2. Longest prefix which == suffix is "aa". You should not overlap the prefix and suffix
solve("aa") = 1. You should not overlap the prefix and suffix.
solve("a") = 0. You should not overlap the prefix and suffix.
```
All strings will be lowercase and string lengths are `1 <= length <= 500`
More examples in test cases. Good luck! | ["def solve(st):\n return next((n for n in range(len(st)//2, 0, -1) if st[:n] == st[-n:]), 0)\n", "def solve(s):\n for i in range(len(s) // 2, 0, -1):\n if s[:i] == s[-i:]:\n return i\n return 0", "solve=lambda s:len(__import__('re').match(r'^(.*).*\\1$',s).group(1))", "def solve(st):\n i = len(st)//2\n while i and not st.endswith(st[0:i]): i -= 1\n return i;\n", "def solve(st):\n attempts = len(st) // 2\n for i in range(attempts, 0, -1):\n if st[:i] == st[-i:]:\n return i\n return 0", "def solve(s):\n return max(i for i in range(len(s)//2+1) if s[:i]==s[len(s)-i:])", "import math\n\n# The function that will check a prefix and a suffix\ndef prefix_suffix_check(string, indexIn):\n return string[:indexIn] == string[(indexIn) * -1 : ]\n\ndef solve(initial_string):\n \n # Halves and floors the array size\n half_array_size = int(math.floor(len(initial_string) / 2))\n \n # A revese for loop for checking the middle to outer\n for x in range(half_array_size, 0, -1):\n # If the suffix and prefix are equal return the x\n if (prefix_suffix_check(initial_string, x) == True):\n return x\n \n # Else return 0\n return 0\n", "def solve(st):\n prefixes = set()\n sufixes = set()\n pref = ''\n suff = st[1:]\n for i in st[:-1]:\n sufixes.add(suff)\n suff = suff[1:]\n pref += i\n prefixes.add(pref)\n \n for i in sorted(sufixes.intersection(prefixes))[::-1]:\n if len(i) * 2 <= len(st):\n return len(i)\n return 0\n", "def solve(st):\n return max((i for i in range(1, len(st)//2+1) if st[:i] == st[-i:]), default=0)", "def solve(st):\n for i in range(len(st)-1,0,-1):\n if not i or len(st) >= 2 * i and st[0:i] == st[-i:]: return i\n return 0"] | {"fn_name": "solve", "inputs": [["abcd"], ["abcda"], ["abcdabc"], ["abcabc"], ["abcabca"], ["abcdabcc"], ["aaaaa"], ["aaaa"], ["aaa"], ["aa"], ["a"], ["acbacc"]], "outputs": [[0], [1], [3], [3], [1], [0], [2], [2], [1], [1], [0], [0]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,851 |
def solve(st):
|
bdb0683b762e4d242fe36e4aa6aa0544 | UNKNOWN | *It seemed a good idea at the time...*
# Why I did it?
After a year on **Codewars** I really needed a holiday...
But not wanting to drift backwards in the honour rankings while I was away, I hatched a cunning plan!
# The Cunning Plan
So I borrowed my friend's "Clone Machine" and cloned myself :-)
Now my clone can do my Kata solutions for me and I can relax!
Brilliant!!
Furthermore, at the end of the day my clone can re-clone herself...
Double brilliant!!
I wonder why I didn't think to do this earlier?
So as I left for the airport I gave my clone instructions to:
* do my Kata solutions for me
* feed the cat
* try to keep the house tidy and not eat too much
* sleep
* clone yourself
* repeat same next day
# The Flaw
Well, how was I supposed to know that cloned DNA is faulty?
:-(
Every time they sleep they wake up with decreased ability - they get slower... they get dumber... they are only able to solve 1 less Kata than they could the previous day.
For example, if they can solve 10 Kata today, then tomorrow they can solve only 9 Kata, then 8, 7, 6... Eventually they can't do much more than sit around all day playing video games.
And (unlike me), when the clone cannot solve any more Kata they are no longer clever enough to operate the clone machine either!
# The Return Home
I suspected something was wrong when I noticed my **Codewars** honour had stopped rising.
I made a hasty return home...
...and found 100s of clones scattered through the house. Mostly they sit harmlessly mumbling to themselves. The largest group have made a kind of nest in my loungeroom where they sit catatonic in front of the PlayStation.
The whole place needs fumigating.
The fridge and pantry are empty.
And I can't find the cat.
# Kata Task
Write a method to predict the final outcome where:
Input:
* `kata-per-day` is the number of Kata I can solve per day
Output:
* ```[number-of-clones, number-of-kata-solved-by-clones]``` | ["def clonewars(k):\n return [2**max(k-1,0),2**(k+1)-k-2]", "clonewars=lambda n:[-~2**n//2,2**-~n-n-2]", "def clonewars(n):\n return [2**max(n-1,0), 2**(n+1)-(n+2)]", "def clonewars(n):\n return [max(1,2**(n-1)), 2**(n+1)-n-2]", "def clonewars(n):\n if n == 0: return [1,0]\n return [2**(n-1), 2**(n+1) - (n+1) - 1]", "def clonewars(n):\n return [2**max(0, n - 1), sum((n - i) * 2**i for i in range(0, n))]", "clonewars = lambda k: [2**max(0, k-1), sum(2**max(0, i) * (k - i) for i in range(k))]", "def clonewars(kata):\n return [2**(kata-1),sum(2**i*(kata-i) for i in range(kata))] if kata else [1,0]", "def clonewars(kata_per_day):\n x = max(1,2 ** (kata_per_day-1))\n y = 0\n for i in range(0,kata_per_day):\n y += (kata_per_day-i) * (2**(i))\n return [x,y]"] | {"fn_name": "clonewars", "inputs": [[0], [1], [5], [10]], "outputs": [[[1, 0]], [[1, 1]], [[16, 57]], [[512, 2036]]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 802 |
def clonewars(n):
|
058572ecc6245ed0c58f1b745c78d459 | UNKNOWN | Jenny is 9 years old. She is the youngest detective in North America. Jenny is a 3rd grader student, so when a new mission comes up, she gets a code to decipher in a form of a sticker (with numbers) in her math notebook and a comment (a sentence) in her writing notebook. All she needs to do is to figure out one word, from there she already knows what to do.
And here comes your role - you can help Jenny find out what the word is!
In order to find out what the word is, you should use the sticker (array of 3 numbers) to retrive 3 letters from the comment (string) that create the word.
- Each of the numbers in the array refers to the position of a letter in the string, in increasing order.
- Spaces are not places, you need the actual letters. No spaces.
- The returned word should be all lowercase letters.
- if you can't find one of the letters using the index numbers, return "No mission today". Jenny would be very sad, but that's life... :(
Example:
input: [5, 0, 3], "I Love You"
output: "ivy"
(0 = "i", 3 = "v", 5 = "y") | ["def missing(nums, s):\n ans = []\n s = s.replace(' ','')\n try:\n for i in sorted(nums):\n ans.append(s[i])\n return ''.join(ans).lower()\n except IndexError:\n return (\"No mission today\")", "def missing(nums, str):\n str=str.replace(' ','').lower()\n try:\n return ''.join(str[i] for i in sorted(nums))\n except:\n return \"No mission today\"", "def missing(nums, s):\n s = s.lower().replace(\" \",\"\")\n nums = sorted(nums)\n return \"No mission today\" if any(i>= len(s) for i in nums) else ''.join(s[i] for i in nums)", "def missing(nums, str):\n str = str.replace(' ', '').lower()\n if max(nums) >= len(str):\n return \"No mission today\"\n return ''.join( str[c] for c in sorted(nums) )", "def missing(nums, s):\n try:\n return ''.join(s.replace(' ', '')[i] for i in sorted(nums)).lower()\n except IndexError:\n return 'No mission today'", "def missing(nums, str):\n s = str.replace(' ', '')\n arr = sorted(nums)\n return 'No mission today' if arr[-1] >= len(s) else ''.join(s[a] for a in arr).lower()", "def missing(nums, stri):\n nums = sorted(nums)\n stri = stri.replace(\" \",\"\")\n return \"\".join([stri[i].lower() for i in nums]) if max(nums)< len(stri) else \"No mission today\"\n", "def missing(nums, str):\n try:\n return ''.join([str.replace(' ', '')[i] for i in sorted(nums)]).lower()\n except:\n return \"No mission today\"", "def missing(nums, str):\n return ''.join([str.replace(\" \",\"\").lower()[i] for i in sorted(nums)]) if max(nums) < len(str.replace(\" \",\"\")) else \"No mission today\"", "def missing(nums, str):\n try:\n return ''.join(str.replace(' ','')[i].lower() for i in sorted(nums))\n except:\n return \"No mission today\""] | {"fn_name": "missing", "inputs": [[[0, 3, 5], "I love you"], [[7, 10, 1], "see you later"], [[29, 31, 8], "The quick brown fox jumps over the lazy dog"], [[12, 4, 6], "Good Morning"], [[1, 16, 21], "A purple pig and a green donkey flew a kite in the middle of the night"], [[35, 8, 20], "A song can make or ruin your day if you let it get to you"], [[20, 3, 27], "I love eating toasted cheese and tuna"], [[50, 4, 6], "Hi everybody"], [[8, 31, 28], "If I do not like something I will stay away from it"], [[12, 22, 28], "Where do random thoughts come from"], [[41, 7, 18], "The tape got stuck on my lips so I could not talk anymore"], [[33, 8, 12], "My turtle Jim got out of his cage and ate a banana"], [[18, 25, 45], "are you going to have a funnel birthday cake for your next birthday"], [[5, 25, 31], "all moms and dads sat around drinking coffee"], [[24, 36, 8], "My pen broke and now I have blue ink all over my dress"]], "outputs": [["ivy"], ["ear"], ["bay"], ["No mission today"], ["pen"], ["mug"], ["vet"], ["No mission today"], ["law"], ["mom"], ["gym"], ["job"], ["fix"], ["mic"], ["key"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,842 |
def missing(nums, str):
|
814f536bccafc15bdecf33c592a94ef9 | UNKNOWN | You have to create a function which receives 3 arguments: 2 numbers, and the result of an unknown operation performed on them (also a number).
Based on those 3 values you have to return a string, that describes which operation was used to get the given result.
The possible return strings are:
`"addition"`,
`"subtraction"`,
`"multiplication"`,
`"division"`.
## Example:
```
calcType(1, 2, 3) --> 1 ? 2 = 3 --> "addition"
```
## Notes
* In case of division you should expect that the result of the operation is obtained by using `/` operator on the input values - no manual data type conversion or rounding should be performed.
* Cases with just one possible answers are generated.
* Only valid arguments will be passed to the function. | ["def calc_type(a, b, res):\n return {a + b: \"addition\", a - b: \"subtraction\", a * b: \"multiplication\", a / b: \"division\"}[res]\n", "from operator import add, sub, mul, truediv\n\nOPS = ((\"addition\", add),\n (\"subtraction\", sub),\n (\"multiplication\", mul),\n (\"division\", truediv))\n\ndef calc_type(a, b, res):\n return next(kind for kind,f in OPS if f(a,b)==res)", "calc_type=lambda a,b,c:{a+b:'addit',a-b:'subtract',a*b:'multiplicat',a/b:'divis'}[c]+'ion'", "from operator import add as addition, sub as subtraction, mul as multiplication, truediv as division\n\ndef calc_type(a, b, res):\n return next(\n name for name in ['addition', 'subtraction', 'multiplication', 'division']\n if globals()[name](a, b) == res\n )", "def calc_type(a, b, res):\n dict = {a+b:'addition',a-b:'subtraction',a*b:'multiplication',a/b:'division'}\n return dict[res]", "def calc_type(a, b, res):\n if a + b == res: return 'addition'\n if a - b == res: return 'subtraction'\n return 'multiplication' if a * b == res else 'division'", "def calc_type(a, b, res):\n if a + b == res:\n return \"addition\"\n elif a - b == res:\n return \"subtraction\"\n elif a * b == res:\n return \"multiplication\"\n else:\n return \"division\"", "def calc_type(a, b, res):\n if a+b == res:\n return \"addition\"\n elif a-b == res:\n return \"subtraction\"\n elif a*b == res:\n return \"multiplication\"\n elif a/b == res:\n return \"division\"", "def calc_type(a, b, res):\n if res == a + b: return \"addition\"\n if res == a * b: return \"multiplication\"\n if res == a - b: return \"subtraction\"\n if res == a / b: return \"division\"", "def calc_type(a, b, res):\n if a-b == res: return \"subtraction\"\n if a+b == res: return \"addition\"\n if a*b == res: return \"multiplication\"\n if a/b == res: return \"division\"\n return \"no operation\""] | {"fn_name": "calc_type", "inputs": [[1, 2, 3], [10, 5, 5], [10, 4, 40], [9, 5, 1.8]], "outputs": [["addition"], ["subtraction"], ["multiplication"], ["division"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,973 |
def calc_type(a, b, res):
|
3a08442de0d142525519985b43b6e86b | UNKNOWN | Given a string that includes alphanumeric characters ('3a4B2d') return the expansion of that string: The numeric values represent the occurrence of each letter preceding that numeric value. There should be no numeric characters in the final string. Empty strings should return an empty string.
The first occurrence of a numeric value should be the number of times each character behind it is repeated, until the next numeric value appears.
```python
string_expansion('3D2a5d2f') == 'DDDaadddddff'
```
```python
string_expansion('3abc') == 'aaabbbccc' # correct
string_expansion('3abc') != 'aaabc' # wrong
string_expansion('3abc') != 'abcabcabc' # wrong
```
If there are two consecutive numeric characters the first one is ignored.
```python
string_expansion('3d332f2a') == 'dddffaa'
```
If there are two consecutive alphabetic characters then the first character has no effect on the one after it.
```python
string_expansion('abcde') == 'abcde'
```
Your code should be able to work for both lower and capital case letters.
```python
string_expansion('') == ''
``` | ["def string_expansion(s):\n m,n = '',1\n for j in s:\n if j.isdigit():\n n = int(j)\n else:\n m += j*n\n return m", "import re\n\ndef string_expansion(s):\n return ''.join(''.join(int(n or '1')*c for c in cc) for n,cc in re.findall(r'(\\d?)(\\D+)', s))\n", "def string_expansion(s):\n def f():\n repeat = 1\n for c in s:\n if c.isdigit():\n repeat = int(c)\n else:\n yield c * repeat\n return ''.join(f())", "import re\n\ndef string_expansion(s):\n return re.sub('(\\d)+([a-zA-Z]*)', lambda m: ''.join(ch * int(m.group(1)) for ch in m.group(2)), s)", "import re\n\ndef string_expansion(s):\n return re.sub('\\d*?(\\d?)(\\D*)', lambda m: ''.join(int(m.group(1) or 1) * c for c in m.group(2)), s)", "def string_expansion(s):\n strin = []\n multiplier = 1\n result = \"\"\n for letter in s:\n try:\n strin.append(int(letter))\n except ValueError:\n strin.append(letter)\n for i in strin:\n if isinstance(i, int):\n multiplier = i\n elif isinstance(i, str):\n result += multiplier * i\n return result", "import re\n\ndef string_expansion(s):\n out = []\n for n,chars in re.findall(r'([0-9]?)([a-z]+)', s, re.I):\n out.append(''.join(x*int(n or 1) for x in chars))\n return ''.join(out)\n", "import re\n\ndef string_expansion(stg):\n result = \"\"\n for match in re.finditer(r\"\\d*(^|\\d)([^\\d]+)\", stg):\n count = int(match.group(1) or 1) \n for char in match.group(2):\n result = f\"{result}{count * char}\"\n return result\n\n\n# one-liner\n#string_expansion = lambda s: \"\".join(f\"{int(m.group(1) or 1) * c}\" for m in re.finditer(r\"\\d*(^|\\d)([^\\d]+)\", s) for c in m.group(2))\n", "def string_expansion(s):\n dec = 1\n ret = ''\n for e in s:\n dec = { 0:dec , 1:e }[e.isdigit()]\n ret += ['',e*int(dec)][e.isalpha()]\n return ret", "def string_expansion(s):\n from re import findall\n result = findall('^[a-zA-Z]*', s)[0]\n for i in findall('(\\d)([a-zA-Z]+)', s):\n for j in i[1]:\n result += j*int(i[0])\n return result"] | {"fn_name": "string_expansion", "inputs": [["3D2a5d2f"], ["4D1a8d4j3k"], ["4D2a8d4j2f"], ["3n6s7f3n"], ["0d4n8d2b"], ["0c3b1n7m"], ["7m3j4ik2a"], ["3A5m3B3Y"], ["5M0L8P1"], ["2B"], ["7M1n3K"], ["A4g1b4d"], ["111111"], ["4d324n2"], ["5919nf3u"], ["2n1k523n4i"], ["6o23M32d"], ["1B44n3r"], ["M21d1r32"], ["23M31r2r2"], ["8494mM25K2A"], ["4A46D6B3C"], ["23D42B3A"], ["143D36C1A"], ["asdf"], ["23jbjl1eb"], ["43ibadsr3"], ["123p9cdbjs"], ["2309ew7eh"], ["312987rfebd"], ["126cgec"], ["1chwq3rfb"], ["389fg21c"], ["239vbsac"], ["davhb327vuc"], ["cvyb239bved2dv"], [""]], "outputs": [["DDDaadddddff"], ["DDDDaddddddddjjjjkkk"], ["DDDDaaddddddddjjjjff"], ["nnnssssssfffffffnnn"], ["nnnnddddddddbb"], ["bbbnmmmmmmm"], ["mmmmmmmjjjiiiikkkkaa"], ["AAAmmmmmBBBYYY"], ["MMMMMPPPPPPPP"], ["BB"], ["MMMMMMMnKKK"], ["Aggggbdddd"], [""], ["ddddnnnn"], ["nnnnnnnnnfffffffffuuu"], ["nnknnniiii"], ["ooooooMMMdd"], ["Bnnnnrrr"], ["Mdr"], ["MMMrrr"], ["mmmmMMMMKKKKKAA"], ["AAAADDDDDDBBBBBBCCC"], ["DDDBBAAA"], ["DDDCCCCCCA"], ["asdf"], ["jjjbbbjjjllleb"], ["iiibbbaaadddsssrrr"], ["pppcccccccccdddddddddbbbbbbbbbjjjjjjjjjsssssssss"], ["eeeeeeeeewwwwwwwwweeeeeeehhhhhhh"], ["rrrrrrrfffffffeeeeeeebbbbbbbddddddd"], ["ccccccggggggeeeeeecccccc"], ["chwqrrrfffbbb"], ["fffffffffgggggggggc"], ["vvvvvvvvvbbbbbbbbbsssssssssaaaaaaaaaccccccccc"], ["davhbvvvvvvvuuuuuuuccccccc"], ["cvybbbbbbbbbbvvvvvvvvveeeeeeeeedddddddddddvv"], [""]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 2,255 |
def string_expansion(s):
|
ad4102436386e050df6b70774c1641e2 | UNKNOWN | Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (`HH:MM:SS`)
* `HH` = hours, padded to 2 digits, range: 00 - 99
* `MM` = minutes, padded to 2 digits, range: 00 - 59
* `SS` = seconds, padded to 2 digits, range: 00 - 59
The maximum time never exceeds 359999 (`99:59:59`)
You can find some examples in the test fixtures. | ["def make_readable(s):\n return '{:02}:{:02}:{:02}'.format(s // 3600, s // 60 % 60, s % 60)\n", "def make_readable(seconds):\n hours, seconds = divmod(seconds, 60 ** 2)\n minutes, seconds = divmod(seconds, 60)\n return '{:02}:{:02}:{:02}'.format(hours, minutes, seconds)", "def make_readable(seconds):\n hours = seconds // 3600\n mins = (seconds - hours*3600) // 60\n secs = seconds - (hours*3600 + mins*60)\n\n h_str = str(hours)\n m_str = str(mins)\n s_str = str(secs) \n\n if len(h_str) < 2:\n h_str = '0' + h_str\n\n if len(m_str) < 2:\n m_str = '0' + m_str \n\n if len(s_str) < 2:\n s_str = '0' + s_str \n\n return(f'{h_str}:{m_str}:{s_str}')\n", "def make_readable(seconds):\n h= seconds/60**2\n m= (seconds%60**2)/60\n s= (seconds%60**2%60)\n return \"%02d:%02d:%02d\" % (h, m, s)\n # Do something\n", "def make_readable(seconds):\n m, s = divmod(seconds, 60)\n h, m = divmod(m, 60)\n return \"%02d:%02d:%02d\" % (h, m, s)", "def make_readable(n):\n return f'{n//3600:02d}:{(n%3600)//60:02d}:{n%60:02d}'\n", "import math\ndef make_readable(seconds):\n hours = math.floor(seconds/(60*60))\n seconds-=hours*60*60\n minutes = math.floor(seconds/(60))\n seconds-=minutes*60\n out=\"\"\n if(hours<10): \n out+=\"0\"\n out+=str(int(hours))+\":\"\n if(minutes<10): \n out+=\"0\"\n out+=str(int(minutes))+\":\"\n if(seconds<10): \n out+=\"0\"\n out+=str(int(seconds))\n return out\n", "def make_readable(seconds):\n '''Returns the time in `seconds` as a human-readable format (HH:MM:SS).\n '''\n minute, hour = 60, 60 ** 2 \n return \"%02d:%02d:%02d\" % (\n seconds / hour,\n seconds % hour / minute,\n seconds % hour % minute\n )"] | {"fn_name": "make_readable", "inputs": [[0], [59], [60], [3599], [3600], [86399], [86400], [359999]], "outputs": [["00:00:00"], ["00:00:59"], ["00:01:00"], ["00:59:59"], ["01:00:00"], ["23:59:59"], ["24:00:00"], ["99:59:59"]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,822 |
def make_readable(seconds):
|
9308a1daa81d890bf0ebe3ab0e2255ae | UNKNOWN | _Friday 13th or Black Friday is considered as unlucky day. Calculate how many unlucky days are in the given year._
Find the number of Friday 13th in the given year.
__Input:__ Year as an integer.
__Output:__ Number of Black Fridays in the year as an integer.
__Examples:__
unluckyDays(2015) == 3
unluckyDays(1986) == 1
***Note:*** In Ruby years will start from 1593. | ["from datetime import date\n\ndef unlucky_days(year):\n return sum(date(year, m, 13).weekday() == 4 for m in range(1, 13))", "from calendar import weekday\n\ndef unlucky_days(year):\n return sum(1 for i in range(1, 13) if weekday(year, i, 13) == 4)\n", "from datetime import datetime\n\ndef unlucky_days(year):\n return sum(datetime(year, month, 13).weekday() == 4 for month in range(1,13))", "from datetime import date\ndef unlucky_days(year): \n counter = 0 \n for months in range(1,13):\n if date(year, months, 13).weekday()==4:\n counter +=1 \n return counter\n\n", "from datetime import date\n\ndef unlucky_days(year):\n return sum( 1 for month in range(1,13) if date(year,month,13).weekday()==4 )", "import datetime as d\nimport calendar\ndef unlucky_days(year):\n l = []\n for i in range(1,13):\n l.append(calendar.monthrange(year,i)[1])\n count = 0\n for i in range(0,12):\n if l[i]>=28 and d.date(year,i+1,13).weekday() == 4:\n count+=1\n return count\n", "import datetime\n\ndef unlucky_days(year):\n friday13 = 0\n months = range(1,13)\n for month in months:\n if datetime.date(year,month, 13).weekday() == 4:\n friday13 += 1\n return friday13", "unlucky_days = lambda y: sum(__import__(\"datetime\").date(y, m, 13).weekday() == 4 for m in range(1, 13))", "def unlucky_days(y): \n count = 0 # Clean & Pure Math Example \n for m in range(3,15):\n if m == 13: y-=1 \n if (y%100+(y%100//4)+(y//100)//4-2*(y//100)+26*(m+1)//10+12)%7==5:\n count += 1\n return count", "import calendar \ndef unlucky_days(year):\n return [calendar.weekday(year, m, 13) for m in range(1,13)].count(4)", "from datetime import date\n\nunlucky_days = lambda year: sum(date(year, month, 13).weekday() == 4 for month in range(1, 13))", "def unlucky_days(year):\n x=0\n import datetime\n for i in range(1, 13):\n if datetime.date(year, i, 13).weekday()==4:\n x=x+1\n return x", "def unlucky_days(year):\n import calendar\n fridays = 0\n for i in range(1,13):\n if calendar.weekday(year,i,13) == 4:\n fridays += 1\n return fridays", "def unlucky_days(year):\n import datetime\n \n # setting variables\n i, count = 1, 0\n \n # loop for each month\n while i <= 12:\n\n # checks if there is an unlucky day in the month\n if (datetime.datetime(year, i, 13).strftime('%w') == '5'): count += 1\n \n i += 1\n \n return count ", "from datetime import date\ndef unlucky_days(year):\n black_fridays = 0\n for month in range(1,13):\n if date(year,month,13).isoweekday() == 5:\n black_fridays+=1\n return black_fridays", "def unlucky_days(year):\n from datetime import date\n black_Fri = 0\n for i in range(1,13):\n if date(year, i, 13).weekday() == 4:\n black_Fri += 1\n return black_Fri", "from datetime import date\n\ndef unlucky_days(year):\n count = 0\n for i in range(1, 13):\n if date(year, i, 13).weekday() == 4:\n count += 1\n return count\n", "import calendar\n\n\ndef unlucky_days(year):\n answer = 0\n\n for month in range(1, 13):\n for day in calendar.Calendar().itermonthdays2(year, month):\n if day[0] == 13 and day[1] == 4:\n answer += 1\n\n return answer\n", "import datetime\ndef unlucky_days(y): #(year,month,day)\n return len([i for i in range(12) if datetime.date(y,i+1,13).weekday() == 4])\n #for month the range of 12 months,\n #if the weekday == friday 13th in y year, i+1 month,\n #return the number of months that have friday the 13th in them as a list.\n #find the length of it.\n", "import datetime\ndef unlucky_days(y):\n return len([i for i in range(12) if datetime.date(y,i+1,13).weekday() == 4])", "from datetime import datetime\n\ndef unlucky_days(year):\n return sum(True for month in range(1, 13) if datetime(year=year, month=month, day=13).weekday() == 4)", "from datetime import datetime\n\n\ndef unlucky_days(year):\n return sum(datetime(year, a, 13).weekday() == 4 for a in range(1, 13))\n", "def unlucky_days(year):\n c=year//100\n y=year-100*c\n c1=(year-1)//100\n y1=year-1-100*c1\n return (1 if (y1+y1//4+c1//4-2*c1+26*(13+1)//10+12)%7==5 else 0)+(1 if (y1+y1//4+c1//4-2*c1+26*(14+1)//10+12)%7==5 else 0)+sum(1 for m in range(3,13) if (y+y//4+c//4-2*c+26*(m+1)//10+12)%7==5)", "import calendar\n\ndef unlucky_days(year):\n f13=0\n for i in range(1,13):\n c=calendar.monthcalendar(year,i)\n for f in [c[0],c[1],c[2],c[3]]:\n if f[calendar.FRIDAY]==13:\n f13+=1\n return f13\n", "import time\ndef unlucky_days(y):\n return sum([time.strptime('%s-%d-13' % (y,x+1),'%Y-%m-%d').tm_wday == 4 for x in range(12)])", "import datetime\n\n\ndef unlucky_days(year):\n return sum(map(lambda x: datetime.datetime(year, x, 13).weekday() == 4, range(1, 13)))", "import calendar\nc=calendar.Calendar()\n\ndef unlucky_days(year):\n cont=0\n for mes in range(1,13):\n for i in c.monthdayscalendar(year,mes):\n if i[4]==13:\n cont=cont+1\n return cont ", "from datetime import datetime \ndef unlucky_days(year):\n return sum(1 for x in range(1, 13) if datetime(year, x, 13).strftime('%a') == 'Fri')", "import datetime\ndef unlucky_days(n):\n\n t=0\n initial_date = datetime.date(n,1,1)\n for e in range(1,365): # \u043f\u0440\u0438\u0431\u0430\u0432\u043b\u044f\u0442\u044c \u043f\u043e \u0434\u043d\u044e \u0438 \u0441\u0447\u0435\u0442\u0447\u0438\u043a \u0435\u0441\u043b\u0438\n my_date = initial_date + datetime.timedelta(days=e)\n if my_date.isoweekday() == 5 and my_date.day == 13:\n t+=1\n return t", "from calendar import weekday\n\ndef unlucky_days(year):\n \n c = 0\n \n for m in range(1,13):\n \n u = weekday(year,m,13)\n \n if u==4:\n \n c+= 1\n \n return c\n\n", "import datetime as dt\n\ndef unlucky_days(y):\n return sum(dt.datetime(y, i+1, 13).weekday() == 4 for i in range(12))\n\n", "from datetime import date, timedelta\n\ndef unlucky_days(year):\n d = date(year, 1, 1)\n d += timedelta(days=4 - d.weekday())\n counter = 0\n \n while d.year != year + 1:\n if d.weekday() == 4 and d.day == 13:\n counter += 1\n d += timedelta(days=7)\n \n return counter", "import datetime\ndef unlucky_days(year):\n sum = 0\n for month in range(1,13):\n date = datetime.datetime(year,month,13).strftime(\"%w\")\n if date == '5':\n sum += 1\n return sum", "import datetime\ndef unlucky_days(year):\n sum = 0\n for month in range(1,13):\n date = datetime.datetime(year,month,13).strftime(\"%w\")\n if date == '5':\n sum += 1\n return sum\nprint(unlucky_days(2015))", "from datetime import datetime\n\ndef unlucky_days(year):\n return sum(map(lambda i: datetime(year, i, 13).weekday() == 4, [i for i in range(1, 13)]))", "import datetime\ndef unlucky_days(year):\n howmany=0\n for i in range(1,13):\n day=datetime.datetime(year,i,13)\n if day.weekday()==4:\n howmany+=1 \n return howmany", "from datetime import date, timedelta\n\n\ndef unlucky_days(year):\n count = 0\n start_day = date(year, 1, 1)\n end_day = date(year, 12, 31)\n\n while start_day <= end_day:\n if (start_day.weekday() == 4) and (start_day.day == 13):\n # print(start_day)\n count += 1\n else:\n pass\n start_day += timedelta(days=1)\n\n return count", "import datetime\ndef unlucky_days(year):\n return sum(1 for month in range(1,13) if datetime.date(year, month, 13).isoweekday() == 5)\n", "import datetime\ndef unlucky_days(year):\n cnt = 0\n for i in range(1, 13):\n d = datetime.datetime(year, i, 13)\n if d.weekday() == 4:\n cnt += 1\n return cnt", "import datetime\n\ndef unlucky_days(year):\n sm=0\n for i in range(1,13):\n dt=datetime.datetime(year,i,13)\n if dt.strftime(\"%A\")==\"Friday\":\n sm+=1\n \n return sm", "from datetime import date, timedelta \n\ndef calc(y):\n\n st = date(y, 1, 1)\n fin = date(y, 12, 31)\n numday = timedelta(days=1)\n while st < fin:\n if st.weekday() == 4 and st.day == 13:\n yield st\n st = st + numday\n \n \ndef unlucky_days(year):\n count = 0\n res = [str(i) for y in range(year - 1,year + 1) for i in calc(y)]\n for x in range(len(res)):\n if str(year) in res[x]:\n count = count + 1\n return count\n", "import datetime\n\ndef unlucky_days(year):\n i = 0\n for item in range(1, 13):\n day = datetime.date(year, item, 13).isoweekday()\n if day == 5:\n i += 1\n return i", "unlucky_days = lambda y: len([m for m in range(1, 13) if __import__('datetime').date(y, m, 13).weekday() == 4])", "import calendar\n\ndef unlucky_days(year):\n res_date = calendar.Calendar()\n res_days = 0\n for month in range(1, 13):\n for day in res_date.itermonthdays2(year, month):\n if day[0] == 13 and day[1] == 4:\n res_days += 1\n return res_days\n", "import calendar\nimport datetime\n\n\ndef unlucky_days(year):\n start_date = datetime.date(year, 1, 1)\n end_date = datetime.date(year, 12, 31)\n delta = datetime.timedelta(days=1)\n counter = 0\n while start_date <= end_date:\n year = int(str(start_date)[:4])\n month = int(str(start_date)[5:7])\n day = int(str(start_date)[8:10])\n if day == 13 and calendar.weekday(year, month, day) == 4:\n counter += 1\n start_date += delta\n \n return counter\n", "import datetime\ndef unlucky_days(year):\n return sum([1 for m in range(1,13) if datetime.date(year,m,13).weekday()==4])", "import datetime\n\ndef unlucky_days(n):\n\n c=0\n \n d=datetime.timedelta(days=1)\n t = datetime.date(n, 1, 1)\n while t != datetime.date(n,12,31):\n\n \n if t.day==13 and t.strftime(\"%A\")=='Friday':\n c=c+1\n t=t+d\n\n return c\n", "import datetime\ndef unlucky_days(y):\n return sum(datetime.date(y,i,13).weekday() == 4 for i in range(1,13))", "def unlucky_days(year):\n \n from datetime import datetime as dt\n \n count = 0\n \n for i in range(1,13):\n if dt(year, i, 13).weekday() == 4:\n count += 1\n \n return count", "import datetime\n\ndef unlucky_days(year):\n counter = 0\n for i in range(1, 13):\n d = datetime.date(year, i, 13)\n if d.weekday() == 4:\n counter += 1\n return counter", "import datetime\n\ndef unlucky_days(year):\n dates_13 = [datetime.datetime.strptime (f'{year}-{i}-13', '%Y-%m-%d').date () for i in range (1, 13)]\n\n res = [mon for mon in dates_13 if mon.isoweekday() == 5]\n\n return len(res)", "import datetime\ndef unlucky_days(year):\n ans = 0\n for i in range(1, 13):\n day = datetime.date(year, i, 13)\n ans += (day.weekday() == 4)\n \n return(ans)", "from datetime import date\n\ndef unlucky_days(year):\n return sum(date(year, month, 13).isoweekday() == 5 for month in range(1, 13))\n\n\ndef __starting_point():\n #These \"asserts\" using only for self-checking and not necessary for auto-testing\n assert unlucky_days(2015) == 3, \"First - 2015\"\n assert unlucky_days(1986) == 1, \"Second - 1986\"\n__starting_point()", "import datetime\ndef unlucky_days(year):\n count = 0\n for i in range(1, 13):\n a = datetime.datetime(year, i, 13)\n if a.strftime(\"%A\") == 'Friday':\n count += 1\n return count", "def unlucky_days(year):\n from datetime import datetime\n \n fridays = 0\n \n for i in range(1, 13):\n if datetime(year, i, 13).weekday() == 4:\n fridays += 1\n \n return fridays", "import calendar\n\n\ndef unlucky_days(year):\n c = calendar.Calendar()\n counter = 0\n for month in range(1,13):\n print(f\"Months is {month}\")\n for day in c.itermonthdays2(year, month):\n print(f\"Day is {day}\")\n if day[0] == 13 and day[1] == 4:\n print(f\"This is Friday 13th {day}\")\n counter += 1\n return counter", "def unlucky_days(year):\n from datetime import datetime as dt\n from datetime import timedelta\n \n cnt = 0\n x = dt(year,1,1)\n while x.year == year:\n x = x + timedelta(days = 1)\n if x.day == 13 and x.weekday() == 4:\n cnt = cnt + 1\n return cnt", "from calendar import Calendar\ndef unlucky_days(year):\n x = Calendar()\n lst = []\n for month in range(1, 13):\n for days in x.itermonthdays2(year, month):\n if days[0] == 13 and days[1] == 4:\n lst.append(days)\n return len(lst)", "import calendar\n\n\ndef unlucky_days(year):\n return sum([calendar.weekday(year, month, 13) == 4 for month in range(1,13)])", "from datetime import date\n\ndef unlucky_days(year,count=0):\n d1 = date.toordinal(date(year,1,1))\n d2 = date.toordinal(date(year,12,31))\n for i in range(d1, d2+1):\n if date.weekday(date.fromordinal(i)) == 4 and date.fromordinal(i).day == 13:\n count += 1\n return count", "from datetime import date\n\ndef unlucky_days(year,count=0):\n d1 = date.toordinal(date(year,1,1))\n d2 = date.toordinal(date(year,12,31))\n for i in range(d1, d2+1):\n #print(date.weekday(date.fromordinal(i)), date.fromordinal(i).day)\n if date.weekday(date.fromordinal(i)) == 4 and date.fromordinal(i).day == 13:\n count += 1\n return count", "from datetime import date\ndef unlucky_days(year):\n NumDays=0\n for i in range(1,12+1):\n if date(year,i,13).weekday()==4:\n NumDays+=1\n return NumDays\n", "from datetime import datetime\nfrom functools import reduce\n\ndef unlucky_days(year):\n return reduce(lambda r, month: r + int(datetime.strptime(f'{year}-{month:02}-13', '%Y-%m-%d').weekday() == 4), range(1,13), 0)", "import pandas as pd\nfrom datetime import datetime, timedelta\n\ndef unlucky_days(year):\n unlucky = 0\n start_date = datetime(year, 1, 1)\n end_date = datetime(year+1, 1, 1)\n delta = end_date - start_date\n for i in range(delta.days + 1):\n day = start_date + timedelta(days=i)\n if ((day.strftime('%A') == \"Friday\") and (day.strftime('%d') == \"13\")):\n unlucky += 1\n return unlucky\n \n", "import calendar\n\ndef unlucky_days(year):\n return [calendar.weekday(year, x+1, 13) for x in range(12)].count(4)", "from datetime import date\ndef unlucky_days(year):\n thirteenths=[]\n for m in range(1,13):\n if date(year,m,13).weekday()==4:\n thirteenths.append(m)\n else:\n continue\n return len(thirteenths)", "def unlucky_days(year):\n from datetime import date\n unluckyday = 0\n for month in range(1,13):\n if date(year,month,13).weekday() == 4:\n unluckyday +=1\n return unluckyday", "import datetime\ndef unlucky_days(year):\n friday_13 = 0\n months = range(1, 13)\n for i in months:\n if datetime.date(year, i, 13).weekday() == 4:\n friday_13 += 1\n return friday_13", "import datetime\n\ndef unlucky_days(year):\n return sum(datetime.datetime(year, m + 1, 13).weekday() == 4 for m in range(12))\n", "import calendar\n\ndef unlucky_days(year):\n n = 0\n for i in range (1,13):\n if calendar.weekday(year, i, 13) == 4:\n n += 1\n return n", "import datetime\ndef unlucky_days(year):\n unlucky = 0\n for month in range(1,13):\n if datetime.datetime(year,month, 13).weekday() == 4:\n unlucky += 1\n return unlucky", "import datetime\n\n\ndef unlucky_days(year):\n\n counter = 0\n for i in range(1,13):\n thirteenth = datetime.date(year, i, 13)\n if thirteenth.weekday() == 4:\n counter += 1\n\n return counter", "import datetime\n\n\ndef unlucky_days(year):\n black_fridays = 0\n for i in range(1, 13):\n d = datetime.date(year, i, 13)\n if (d.weekday() == 4):\n black_fridays += 1\n\n return black_fridays", "from calendar import weekday\ndef unlucky_days(year):\n return sum(weekday(year,i,13) == 4 for i in range(1, 13))", "from functools import reduce\nimport datetime\n\ndef unlucky_days(year):\n return reduce(\n lambda a, b: a + (1 if datetime.datetime(year, b + 1, 13).weekday() == 4 else 0)\n , range(12), 0)", "import calendar\n\ncal = calendar.Calendar()\n\ndef unlucky_days(input):\n count = 0\n for month in range(1, 13):\n results = cal.monthdays2calendar(input, month)\n for result in results:\n if (13, 4) in result:\n count += 1\n return count\n", "import datetime\n\ndef unlucky_days(year):\n total = 0\n for x in range(1,13):\n if datetime.date(year,x,13).isoweekday() == 5:\n total += 1\n return total", "from datetime import datetime as dt\ndef unlucky_days(year):\n return sum(int(dt(year,x,13).weekday()==4) for x in range(1,13))", "from datetime import date\ndef unlucky_days(year):\n contador = 0\n for i in range(1,13):\n dato = date(year,i,13)\n if dato.weekday() == 4:\n contador+=1\n\n return contador", "import datetime\ndef unlucky_days(year):\n total = 0\n month = 1\n while month < 13:\n test = datetime.datetime(year, month, 13)\n if datetime.datetime.weekday(test) == 4:\n total += 1\n month += 1\n else:\n month +=1\n continue\n return total", "\nimport datetime\n\ndef unlucky_days(year):\n date_=datetime.date(year,1,1)\n \n while date_.weekday() != 4: \n date_+=datetime.timedelta(days=1)\n \n bad_days=0\n \n while date_.year==year:\n if date_.day==13:\n bad_days+=1\n date_+=datetime.timedelta(days=7)\n return bad_days", "from datetime import datetime\n\n\ndef unlucky_days(year):\n \"\"\"returns the numbers of Fridays 13th found in a given year.\n \n example:\n >> print('%s unlucky days found in year 2020.' % unlucky_days(2020))\n \"\"\"\n spooky_days = 0\n if (isinstance(year, int) and (0 < year < 10000)):\n months = ('01', '02', '03', '04', '05', '06', \n '07','08', '09', '10', '11', '12')\n for m in months:\n date_to_check = str(year) + '-' + m + '-13'\n day = datetime.strptime(date_to_check, '%Y-%m-%d').weekday()\n if day == 4:\n spooky_days += 1\n return spooky_days", "from datetime import date\ndef unlucky_days(year): \n return sum(date(year,months,13).weekday()==4 for months in range(1,13))\n\n", "from datetime import datetime\ndef unlucky_days(year: int) -> sum:\n return sum(datetime(year, month, 13).weekday() == 4 for month in range(1, 13))", "from calendar import Calendar, MONDAY, FRIDAY\n\ndef unlucky_days(year):\n c = Calendar(firstweekday=MONDAY)\n return sum(1 for x in [[1 for d, wd in c.itermonthdays2(year, m) if wd == FRIDAY and d == 13] for m in range(1,13)] if x)\n", "from datetime import datetime\ndef unlucky_days(year):\n return sum(map(lambda x: datetime(year, x, 13).weekday() == 4, range(1,13)))", "from datetime import date\n\ndef unlucky_days(year):\n # Only need to check the 13th of each month\n day = 13\n \n # Counter for unlucky days\n unlucky_days_count = 0\n \n # Loop through the months (1 to 12)\n for x in range(1, 13):\n # Create date object for each month\n date_obj = date(year=year, month=x, day=day)\n \n # Check if the 13th of current month is Friday\n # Weekdays range from 0 (Monday) to 6 (Sunday)\n if date_obj.weekday() == 4:\n # Increment unlucky days counter if current 13th is Friday\n unlucky_days_count += 1\n \n # Return the unlucky days counter\n return unlucky_days_count", "from datetime import date, timedelta\ndef unlucky_days(year):\n start_date = date(year,1,1)\n end_date = date(year,12,31)\n delta_days = (end_date - start_date).days\n count = 0\n \n for n in range(delta_days):\n if(start_date.strftime(\"%a %d\") == \"Fri 13\"):\n count=count+1\n start_date=start_date+(timedelta(days=1))\n return count", "import calendar\n\ndef unlucky_days(year):\n c = calendar.Calendar()\n return sum(sum(sum(list(c.yeardays2calendar(year,width=12)), []), []), []).count((13,4))", "import datetime\n\ndef unlucky_days(year):\n number = 0\n for month in range(1, 13):\n d = datetime.date(year, month, 13)\n if (d.strftime(\"%A\") == \"Friday\"):\n number += 1\n return number", "import datetime\n\ndef unlucky_days(year):\n \n count = 0 \n \n for month in range(12):\n if datetime.date(year,month+1,13).weekday() == 4:\n count += 1\n \n return count\n", "from calendar import weekday as wd\ndef unlucky_days(year):\n day=13;k=0\n for month in range(1,13):\n if wd(year,month,day)==4:\n k+=1\n return k", "from datetime import timedelta, date\n\ndef unlucky_days(year):\n day_td = timedelta(days=1)\n date_i = date(year,1,1)\n \n unlucky_counter = 0\n \n for i in range(366):\n date_i = date_i + day_td\n if date_i.day == 13 and date_i.weekday() == 4:\n unlucky_counter += 1\n return unlucky_counter", "from datetime import datetime\n\ndef unlucky_days(year):\n bfriday = 0\n for i in range(1, 13):\n if datetime(year, i, 13).strftime(\"%a\") == \"Fri\":\n bfriday+=1\n return bfriday", "from datetime import datetime\n\nFRIDAY = 4\n\ndef unlucky_days(year):\n bad_days_counter = 0\n for month in range(1, 13):\n if datetime(year, month, 13).weekday() == FRIDAY:\n bad_days_counter += 1\n \n return bad_days_counter\n", "import datetime\ndef unlucky_days(year):\n total=0\n for i in range(12):\n date=datetime.datetime(year,i+1,13)\n if date.weekday()==4:total+=1 \n return total\n\n", "def unlucky_days(year):\n import datetime\n weekdays_13 = [ datetime.date(year,mm,13).weekday() for mm in range(1,13) ]\n return weekdays_13.count(4)", "import calendar\ndef unlucky_days(year):\n c=0\n cal=calendar.Calendar()\n for i in range(1,13):\n for d,w in cal.itermonthdays2(year,i):\n if d==13 and w==4:\n c=c+1\n return c", "from datetime import datetime\n\ndef unlucky_days(year):\n days = 0\n date_string = \"13/{}/{}\"\n for i in range(1,13):\n date_obj = datetime.strptime(date_string.format(str(i).zfill(2),str(year)),'%d/%m/%Y').weekday()\n if date_obj==4:\n days+=1\n return days"] | {"fn_name": "unlucky_days", "inputs": [[1634], [2873], [1586]], "outputs": [[2], [2], [1]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 23,493 |
def unlucky_days(year):
|
759762d4b40c3151008e669570341a0a | UNKNOWN | Lot of museum allow you to be a member, for a certain amount `amount_by_year` you can have unlimitted acces to the museum.
In this kata you should complete a function in order to know after how many visit it will be better to take an annual pass. The function take 2 arguments `annual_price` and `individual_price`. | ["from math import ceil\nfrom operator import truediv\n\n\ndef how_many_times(annual_price, individual_price):\n return int(ceil(truediv(annual_price, individual_price)))", "from math import ceil\ndef how_many_times(ap, ip):\n return ceil(ap/ip)\n", "def how_many_times(annual_price, individual_price):\n count = 0\n totalCost = 0\n while totalCost < annual_price:\n totalCost += individual_price\n count += 1\n return count", "import math\nhow_many_times = lambda year,ind: math.ceil(year/ind)\n", "import math\nhow_many_times = lambda ap, ip: math.ceil(ap / ip)", "def how_many_times(annual_price, individual_price):\n result = 1\n while (result*individual_price) < annual_price:\n result += 1\n return result", "from math import ceil\ndef how_many_times(a, i):\n return ceil(a/i)", "from math import ceil\n\ndef how_many_times(annual, individual):\n return ceil(annual / individual)"] | {"fn_name": "how_many_times", "inputs": [[40, 15], [30, 10], [80, 15]], "outputs": [[3], [3], [6]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 941 |
def how_many_times(annual_price, individual_price):
|
4bd5a50e7d9d3f1576b3c11a64eb72f4 | UNKNOWN | Each floating-point number should be formatted that only the first two decimal places are returned. You don't need to check whether the input is a valid number because only valid numbers are used in the tests.
Don't round the numbers! Just cut them after two decimal places!
```
Right examples:
32.8493 is 32.84
14.3286 is 14.32
Incorrect examples (e.g. if you round the numbers):
32.8493 is 32.85
14.3286 is 14.33
``` | ["def two_decimal_places(number):\n \n return int (number * 100) / 100.0", "from math import trunc\n\n\ndef two_decimal_places(number):\n factor = float(10 ** 2)\n return trunc(number * factor) / factor\n", "def two_decimal_places(number):\n number = str(number)\n return float(number[:number.index('.') + 3])", "import math\n\n\ndef two_decimal_places(number):\n return math.trunc(number * 100.0) / 100.0\n", "def two_decimal_places(number):\n a = int(number*100)\n b = float(a)\n c = b/100\n return c", "from decimal import *\n\ndef two_decimal_places(number):\n return float(Decimal(str(number)).quantize(Decimal('.01'), rounding=ROUND_DOWN))", "def two_decimal_places(number):\n return int(100*number)/100.0", "from math import floor, ceil\ndef two_decimal_places(number):\n if number >= 0:\n return(floor(number*100)/100)\n else:\n return(ceil(number*100)/100)", "import math\n\ndef two_decimal_places(number):\n if number >= 0:\n return math.floor(number * 100)/100\n else:\n return math.ceil(number * 100)/100", "def two_decimal_places(number):\n string = str(number)\n n = string.find('.')\n return float(string[0:n+3])"] | {"fn_name": "two_decimal_places", "inputs": [[10.1289767789], [-7488.83485834983], [4.653725356]], "outputs": [[10.12], [-7488.83], [4.65]]} | INTRODUCTORY | PYTHON3 | CODEWARS | 1,217 |
def two_decimal_places(number):
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.