Datasets:

inputs
stringlengths
50
14k
targets
stringlengths
4
655k
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
from itertools import takewhile,count def get_diagonale_code(grid): grid = grid.replace(' ','').split('\n') rail = len(grid)-1 return grid[0] if not rail else ''.join(takewhile(bool, genRail(grid,rail))) def genRail(grid,rail): for i in count(): n,x = divmod(i,rail) row = rail-x if n&1 else x yield '' if i>=len(grid[row]) else grid[row][i]
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid: str) -> str: grid = grid.split('\n') ret = '' l , i, s = 0, 0 , 1 while 1: try: ret += grid[l][i] except: return ret i += 2 l += s if l == len(grid)-1 or l==0: s = -s
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(s): out, m = [], s.splitlines() d, i, j = -1, 0, 0 while i < len(m) and j < len(m[i]): out.append(m[i][j]) j += 2 if i in (0, len(m) - 1): d = -d i += d return ''.join(out)
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid: str) -> str: if not grid: return "" lines = [l.split() for l in grid.split('\n')] row, col, word = (0, 0, "") while col < len(lines[row]): word += lines[row][col] if row == 0: down = True if row+1 == len(lines): down = False row = row+1 if down else row-1 col += 1 return word
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid: str) -> str: i, j, res, move, M = 0, 0, [], 1, [line.split() for line in grid.split('\n')] while i < len(M) and j < len(M[i]): res.append(M[i][j]) move = 1 if i==0 else -1 if i==len(M)-1 else move i, j = i+move, j+1 return ''.join(res)
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid): grid = [line.split() for line in grid.splitlines()] d, word, N = -1, "", len(grid) x, y = 0, 0 while x < N and y < len(grid[x]): if x == 0 or x == N - 1: d *= -1 word += grid[x][y] x, y = x + d, y + 1 return word
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
from itertools import count, cycle, takewhile def get_diagonale_code(grid: str) -> str: rows = grid.splitlines() it = zip(cycle(rows + rows[-2:0:-1]), count(0, 2)) chars = (row[c] if c < len(row) else None for row, c in it) return ''.join(takewhile(lambda c: c, chars))
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def generator(strings: list): while True: for q in strings: yield q for q in strings[-2: 0: -1]: yield q def get_diagonale_code(grid: str) -> str: strings = [q.replace(' ', '') for q in grid.split('\n')] result = [] for index, row in enumerate(generator(strings)): if index < len(row): result.append(row[index]) else: return ''.join(result)
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid: str) -> str: ans=[] if grid: grid = [k.strip().split(" ") for k in grid.split("\n")] i=j=0 dir = True while j <len(grid[i]): ans.append(grid[i][j]) if i == len(grid) - 1:dir = False if (i == 0): dir = True i = 0 if len(grid) == 1 else i +1 if dir else i - 1 j+=1 return "".join(ans)
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(s): S=[x.split()for x in s.split('\n')] i,z,L=0,'',list(range(len(S))) while 1: try: for j in L+L[1:-1][::-1]:z,i=z+S[j][i],i+1 except:return z
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid: str) -> str: flag=True temp=grid.split("\n") for i,j in enumerate(temp): temp[i]=j.split() res="" x=0 y=0 while True: try: res+=temp[y][x] if y==len(temp)-1: flag=False elif y==0 and not flag: flag=True y+=1 if flag else -1 x+=1 except: return res
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid: str) -> str: matrix = [i.split() for i in grid.split('\n')] x, y, flag = 0, 0, 1 result = '' while x < len(matrix) and y < len(matrix[x]) : result += matrix[x][y] x, y = x + flag, y + 1 flag = flag if 1 < x + 1 < len(matrix) else -flag return result
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid: str) -> str: matrix = [i.split() for i in grid.split('\n')] x, y = 0, 0 flag = True result = '' while x < len(matrix) and y < len(matrix[x]) : result += matrix[x][y] y += 1 x = x + 1 if flag else x - 1 flag = flag if 1 < x + 1 < len(matrix) else not flag return result
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid: str) -> str: g = (grid.replace(" ","").split("\n")) i, j, d, word = 0, 0, 1, "" while 0 <= i < len(g) and j < len(g[i]): if 0 <= j < len(g[i]): word += g[i][j] i, j = i + d, j + 1 else: i += d if i == 0 or i == len(g) - 1: d = -d return word
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid: str) -> str: grid = grid.replace(' ','').split('\n') x,y = 0,0 s=1 res='' try: while True: print((x,y,s,grid[x][y])) res+=grid[x][y] y+=1 x+= 1 if s==1 else -1 if not 0<=x<len(grid): s*=-1 x+=s*2 except: return res
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid: str) -> str: grid = grid.split('\n') ret = '' l , i, s = 0, 0 , 1 while 1: try: ret += grid[l][i] except: return ret i += 2 l += s if l == len(grid)-1: s = -1 elif l <= 0: s = 1
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid: str) -> str: res, grid = '', [x.split() for x in grid.splitlines()] r, c, x, rows = 0, 0, 1, len(grid) while -1 < r < rows and c < len(grid[r]): res += grid[r][c] if r + 1 == rows: x = -1 elif r == 0: x = 1 r += x c += 1 return res
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `β†˜` and diagonally up right `β†—` if you can't go further). The message ends when there is no space at the right up or down diagonal. To make things even clearer: the same example, but in a simplified view ``` H _ _ _ _ _ I _ _ _ _ _ ! _ _ T _ _ _ E _ _ _ H _ R _ _ _ _ _ E ```
def get_diagonale_code(grid: str) -> str: grid = [x.split() for x in grid.splitlines()] res, rows, x = '', len(grid), 1 r = c = 0 while -1 < r < rows and c < len(grid[r]): res += grid[r][c] if r + 1 == rows: x = -1 elif r == 0: x = 1 r += x c += 1 return res
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once. Find all the combinations of n elements of the array that their sum are 0. ```python arr = [1, -1, 2, 3, -2] n = 3 find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0 ``` The function should ouput every combination or group in increasing order. We may have more than one group: ```python arr = [1, -1, 2, 3, -2, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` In the case above the function should output a sorted 2D array. The function will not give a group twice, or more, only once. ```python arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` If there are no combinations with sum equals to 0, the function will output an alerting message. ```python arr = [1, 1, 2, 3] n = 2 find_zero_sum_groups(arr, n) == "No combinations" ``` If the function receives an empty array will output an specific alert: ```python arr = [] n = 2 find_zero_sum_groups(arr, n) == "No elements to combine" ``` As you have seen the solutions may have a value occurring only once. Enjoy it!
from itertools import combinations def find_zero_sum_groups(arr, n): combos = sorted(sorted(c) for c in combinations(set(arr), n) if sum(c) == 0) return combos if len(combos) > 1 else combos[0] if combos else "No combinations" if arr else "No elements to combine"
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once. Find all the combinations of n elements of the array that their sum are 0. ```python arr = [1, -1, 2, 3, -2] n = 3 find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0 ``` The function should ouput every combination or group in increasing order. We may have more than one group: ```python arr = [1, -1, 2, 3, -2, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` In the case above the function should output a sorted 2D array. The function will not give a group twice, or more, only once. ```python arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` If there are no combinations with sum equals to 0, the function will output an alerting message. ```python arr = [1, 1, 2, 3] n = 2 find_zero_sum_groups(arr, n) == "No combinations" ``` If the function receives an empty array will output an specific alert: ```python arr = [] n = 2 find_zero_sum_groups(arr, n) == "No elements to combine" ``` As you have seen the solutions may have a value occurring only once. Enjoy it!
from itertools import combinations as comb def find_zero_sum_groups(arr, n): if not arr: return "No elements to combine" arr = list(set(arr)) result = sorted(sorted(x) for x in set(comb(arr, n)) if sum(x) == 0) result = sorted(list(x) for x in set(map(tuple, result))) if not result: return "No combinations" return result[0] if len(result) == 1 else result
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once. Find all the combinations of n elements of the array that their sum are 0. ```python arr = [1, -1, 2, 3, -2] n = 3 find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0 ``` The function should ouput every combination or group in increasing order. We may have more than one group: ```python arr = [1, -1, 2, 3, -2, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` In the case above the function should output a sorted 2D array. The function will not give a group twice, or more, only once. ```python arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` If there are no combinations with sum equals to 0, the function will output an alerting message. ```python arr = [1, 1, 2, 3] n = 2 find_zero_sum_groups(arr, n) == "No combinations" ``` If the function receives an empty array will output an specific alert: ```python arr = [] n = 2 find_zero_sum_groups(arr, n) == "No elements to combine" ``` As you have seen the solutions may have a value occurring only once. Enjoy it!
from itertools import combinations def find_zero_sum_groups(lst, n): if not lst: return "No elements to combine" result = [list(c) for c in combinations(sorted(set(lst)), n) if sum(c) == 0] return (result[0] if len(result) == 1 else result) or "No combinations"
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once. Find all the combinations of n elements of the array that their sum are 0. ```python arr = [1, -1, 2, 3, -2] n = 3 find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0 ``` The function should ouput every combination or group in increasing order. We may have more than one group: ```python arr = [1, -1, 2, 3, -2, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` In the case above the function should output a sorted 2D array. The function will not give a group twice, or more, only once. ```python arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` If there are no combinations with sum equals to 0, the function will output an alerting message. ```python arr = [1, 1, 2, 3] n = 2 find_zero_sum_groups(arr, n) == "No combinations" ``` If the function receives an empty array will output an specific alert: ```python arr = [] n = 2 find_zero_sum_groups(arr, n) == "No elements to combine" ``` As you have seen the solutions may have a value occurring only once. Enjoy it!
from itertools import combinations def find_zero_sum_groups(a, n): li = sorted(map(sorted,filter(lambda x:sum(x)==0,combinations(set(a),n)))) return li if len(li)>1 else li[0] if li else "No combinations" if a else "No elements to combine"
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once. Find all the combinations of n elements of the array that their sum are 0. ```python arr = [1, -1, 2, 3, -2] n = 3 find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0 ``` The function should ouput every combination or group in increasing order. We may have more than one group: ```python arr = [1, -1, 2, 3, -2, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` In the case above the function should output a sorted 2D array. The function will not give a group twice, or more, only once. ```python arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` If there are no combinations with sum equals to 0, the function will output an alerting message. ```python arr = [1, 1, 2, 3] n = 2 find_zero_sum_groups(arr, n) == "No combinations" ``` If the function receives an empty array will output an specific alert: ```python arr = [] n = 2 find_zero_sum_groups(arr, n) == "No elements to combine" ``` As you have seen the solutions may have a value occurring only once. Enjoy it!
from itertools import combinations as c def find_zero_sum_groups(a,n): if not len(a):return 'No elements to combine' r=[sorted(x) for x in c(sorted(set(a)),n) if sum(x)==0] return sorted(r) if len(r)>1 else r[0] if len(r) else 'No combinations'
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once. Find all the combinations of n elements of the array that their sum are 0. ```python arr = [1, -1, 2, 3, -2] n = 3 find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0 ``` The function should ouput every combination or group in increasing order. We may have more than one group: ```python arr = [1, -1, 2, 3, -2, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` In the case above the function should output a sorted 2D array. The function will not give a group twice, or more, only once. ```python arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` If there are no combinations with sum equals to 0, the function will output an alerting message. ```python arr = [1, 1, 2, 3] n = 2 find_zero_sum_groups(arr, n) == "No combinations" ``` If the function receives an empty array will output an specific alert: ```python arr = [] n = 2 find_zero_sum_groups(arr, n) == "No elements to combine" ``` As you have seen the solutions may have a value occurring only once. Enjoy it!
from itertools import combinations def find_zero_sum_groups(arr, n): if not arr: return "No elements to combine" res = [list(c) for c in combinations(sorted(set(arr)), n) if not sum(c)] if not res: return "No combinations" if not res[1:]: return res[0] return res
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once. Find all the combinations of n elements of the array that their sum are 0. ```python arr = [1, -1, 2, 3, -2] n = 3 find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0 ``` The function should ouput every combination or group in increasing order. We may have more than one group: ```python arr = [1, -1, 2, 3, -2, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` In the case above the function should output a sorted 2D array. The function will not give a group twice, or more, only once. ```python arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` If there are no combinations with sum equals to 0, the function will output an alerting message. ```python arr = [1, 1, 2, 3] n = 2 find_zero_sum_groups(arr, n) == "No combinations" ``` If the function receives an empty array will output an specific alert: ```python arr = [] n = 2 find_zero_sum_groups(arr, n) == "No elements to combine" ``` As you have seen the solutions may have a value occurring only once. Enjoy it!
from itertools import combinations def find_zero_sum_groups(arr, n): if not arr: return "No elements to combine" res = {c for c in combinations(set(arr), n) if not sum(c)} if len(res) == 1: return sorted(res.pop()) return sorted(map(sorted, res)) if res else "No combinations"
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once. Find all the combinations of n elements of the array that their sum are 0. ```python arr = [1, -1, 2, 3, -2] n = 3 find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0 ``` The function should ouput every combination or group in increasing order. We may have more than one group: ```python arr = [1, -1, 2, 3, -2, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` In the case above the function should output a sorted 2D array. The function will not give a group twice, or more, only once. ```python arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` If there are no combinations with sum equals to 0, the function will output an alerting message. ```python arr = [1, 1, 2, 3] n = 2 find_zero_sum_groups(arr, n) == "No combinations" ``` If the function receives an empty array will output an specific alert: ```python arr = [] n = 2 find_zero_sum_groups(arr, n) == "No elements to combine" ``` As you have seen the solutions may have a value occurring only once. Enjoy it!
from itertools import combinations def find_zero_sum_groups(arr, n): if not arr: return "No elements to combine" else: results = [list(x) for x in combinations(sorted(set(arr)), n) if sum(x)==0] if not results: return "No combinations" elif len(results)==1: return results[0] else: return results
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once. Find all the combinations of n elements of the array that their sum are 0. ```python arr = [1, -1, 2, 3, -2] n = 3 find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0 ``` The function should ouput every combination or group in increasing order. We may have more than one group: ```python arr = [1, -1, 2, 3, -2, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` In the case above the function should output a sorted 2D array. The function will not give a group twice, or more, only once. ```python arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` If there are no combinations with sum equals to 0, the function will output an alerting message. ```python arr = [1, 1, 2, 3] n = 2 find_zero_sum_groups(arr, n) == "No combinations" ``` If the function receives an empty array will output an specific alert: ```python arr = [] n = 2 find_zero_sum_groups(arr, n) == "No elements to combine" ``` As you have seen the solutions may have a value occurring only once. Enjoy it!
from itertools import combinations def find_zero_sum_groups(my_list,n): my_list=list(set(my_list)) if len(my_list)==0: return "No elements to combine" subs = [] sumsubs=[] for i in range(n, n+1): # print(list(combinations(my_list, i))) temp = [list(x) for x in combinations(my_list, i)] if len(temp)>0: subs.extend(temp) subs.sort() for x in subs: x.sort() # x.sort(key=lambda x: x[0]) # print(x) if sum(x)==0 and x not in sumsubs: sumsubs.append(x) for x in sumsubs: x.sort() sumsubs.sort(key=lambda x: x[0]) sumsubs.sort() if len(sumsubs)==1: return (sumsubs[0]) if len(sumsubs)>1: return (sumsubs) else: return 'No combinations'
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once. Find all the combinations of n elements of the array that their sum are 0. ```python arr = [1, -1, 2, 3, -2] n = 3 find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0 ``` The function should ouput every combination or group in increasing order. We may have more than one group: ```python arr = [1, -1, 2, 3, -2, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` In the case above the function should output a sorted 2D array. The function will not give a group twice, or more, only once. ```python arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` If there are no combinations with sum equals to 0, the function will output an alerting message. ```python arr = [1, 1, 2, 3] n = 2 find_zero_sum_groups(arr, n) == "No combinations" ``` If the function receives an empty array will output an specific alert: ```python arr = [] n = 2 find_zero_sum_groups(arr, n) == "No elements to combine" ``` As you have seen the solutions may have a value occurring only once. Enjoy it!
from itertools import combinations as c def find_zero_sum_groups(arr, n): a=sorted(set(arr)) ans=[] for i in c(a,n): if sum(i)==0: ans.append(list(i)) if not arr: return 'No elements to combine' if not ans: return 'No combinations' if len(ans)==1: return ans[0] return ans
# Task Given a rectangular matrix containing only digits, calculate the number of different `2 Γ— 2` squares in it. # Example For ``` matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] ``` the output should be `6`. Here are all 6 different 2 Γ— 2 squares: ``` 1 2 2 2 2 1 2 2 2 2 2 2 2 2 1 2 2 2 2 3 2 3 2 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≀ matrix.length ≀ 100,` `1 ≀ matrix[i].length ≀ 100,` `0 ≀ matrix[i][j] ≀ 9.` - `[output]` an integer The number of different `2 Γ— 2` squares in matrix.
def different_squares(matrix): s = set() rows, cols = len(matrix), len(matrix[0]) for row in range(rows - 1): for col in range(cols - 1): s.add((matrix[row][col], matrix[row][col + 1], matrix[row + 1][col], matrix[row + 1][col + 1])) return len(s)
# Task Given a rectangular matrix containing only digits, calculate the number of different `2 Γ— 2` squares in it. # Example For ``` matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] ``` the output should be `6`. Here are all 6 different 2 Γ— 2 squares: ``` 1 2 2 2 2 1 2 2 2 2 2 2 2 2 1 2 2 2 2 3 2 3 2 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≀ matrix.length ≀ 100,` `1 ≀ matrix[i].length ≀ 100,` `0 ≀ matrix[i][j] ≀ 9.` - `[output]` an integer The number of different `2 Γ— 2` squares in matrix.
def different_squares(matrix): squares = [] for r in range(len(matrix)-1): for c in range(len(matrix[0])-1): squares.append((matrix[r][c],matrix[r][c+1],matrix[r+1][c],matrix[r+1][c+1])) return len(set(squares))
# Task Given a rectangular matrix containing only digits, calculate the number of different `2 Γ— 2` squares in it. # Example For ``` matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] ``` the output should be `6`. Here are all 6 different 2 Γ— 2 squares: ``` 1 2 2 2 2 1 2 2 2 2 2 2 2 2 1 2 2 2 2 3 2 3 2 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≀ matrix.length ≀ 100,` `1 ≀ matrix[i].length ≀ 100,` `0 ≀ matrix[i][j] ≀ 9.` - `[output]` an integer The number of different `2 Γ— 2` squares in matrix.
different_squares = lambda m: len({(m[i][j], m[i][j+1], m[i+1][j], m[i+1][j+1]) for i in range(len(m)-1) for j in range(len(m[0])-1)})
# Task Given a rectangular matrix containing only digits, calculate the number of different `2 Γ— 2` squares in it. # Example For ``` matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] ``` the output should be `6`. Here are all 6 different 2 Γ— 2 squares: ``` 1 2 2 2 2 1 2 2 2 2 2 2 2 2 1 2 2 2 2 3 2 3 2 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≀ matrix.length ≀ 100,` `1 ≀ matrix[i].length ≀ 100,` `0 ≀ matrix[i][j] ≀ 9.` - `[output]` an integer The number of different `2 Γ— 2` squares in matrix.
def different_squares(matrix): result = [] for i in range(len(matrix) - 1): for j in range(len(matrix[0]) - 1): one = [ matrix[i][j:j + 2], matrix[i + 1][j:j + 2] ] if one not in result: result.append(one) return len(result)
# Task Given a rectangular matrix containing only digits, calculate the number of different `2 Γ— 2` squares in it. # Example For ``` matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] ``` the output should be `6`. Here are all 6 different 2 Γ— 2 squares: ``` 1 2 2 2 2 1 2 2 2 2 2 2 2 2 1 2 2 2 2 3 2 3 2 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≀ matrix.length ≀ 100,` `1 ≀ matrix[i].length ≀ 100,` `0 ≀ matrix[i][j] ≀ 9.` - `[output]` an integer The number of different `2 Γ— 2` squares in matrix.
def different_squares(matrix): m, n = len(matrix), len(matrix[0]) return len({tuple(matrix[i][j:j+2] + matrix[i+1][j:j+2]) for i in range(m-1) for j in range(n-1)})
# Task Given a rectangular matrix containing only digits, calculate the number of different `2 Γ— 2` squares in it. # Example For ``` matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] ``` the output should be `6`. Here are all 6 different 2 Γ— 2 squares: ``` 1 2 2 2 2 1 2 2 2 2 2 2 2 2 1 2 2 2 2 3 2 3 2 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≀ matrix.length ≀ 100,` `1 ≀ matrix[i].length ≀ 100,` `0 ≀ matrix[i][j] ≀ 9.` - `[output]` an integer The number of different `2 Γ— 2` squares in matrix.
from itertools import chain pairwise = lambda a: list(zip(a, a[1:])) transpose = lambda a: list(zip(*a)) def different_squares(matrix): if 1 in (len(matrix), len(matrix[0])): return 0 all_squares = chain.from_iterable(map(pairwise, map(transpose, pairwise(matrix)))) unique_squares = set(all_squares) return len(unique_squares)
# Task Given a rectangular matrix containing only digits, calculate the number of different `2 Γ— 2` squares in it. # Example For ``` matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] ``` the output should be `6`. Here are all 6 different 2 Γ— 2 squares: ``` 1 2 2 2 2 1 2 2 2 2 2 2 2 2 1 2 2 2 2 3 2 3 2 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≀ matrix.length ≀ 100,` `1 ≀ matrix[i].length ≀ 100,` `0 ≀ matrix[i][j] ≀ 9.` - `[output]` an integer The number of different `2 Γ— 2` squares in matrix.
def different_squares(matrix): squares = [] for r in range(len(matrix)-1): for c in range(len(matrix[0])-1): squares.append((matrix[r][c], matrix[r][c+1], matrix[r+1][c], matrix[r+1][c+1])) unique = set(squares) return len(unique)
# Task Given a rectangular matrix containing only digits, calculate the number of different `2 Γ— 2` squares in it. # Example For ``` matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] ``` the output should be `6`. Here are all 6 different 2 Γ— 2 squares: ``` 1 2 2 2 2 1 2 2 2 2 2 2 2 2 1 2 2 2 2 3 2 3 2 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≀ matrix.length ≀ 100,` `1 ≀ matrix[i].length ≀ 100,` `0 ≀ matrix[i][j] ≀ 9.` - `[output]` an integer The number of different `2 Γ— 2` squares in matrix.
def different_squares(matrix): h, w = len(matrix), len(matrix[0]) if matrix else 0 return len(set(((matrix[i][j], matrix[i][j+1]), (matrix[i+1][j], matrix[i+1][j+1])) for i in range(h-1) for j in range(w-1)))
# Task Given a rectangular matrix containing only digits, calculate the number of different `2 Γ— 2` squares in it. # Example For ``` matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] ``` the output should be `6`. Here are all 6 different 2 Γ— 2 squares: ``` 1 2 2 2 2 1 2 2 2 2 2 2 2 2 1 2 2 2 2 3 2 3 2 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≀ matrix.length ≀ 100,` `1 ≀ matrix[i].length ≀ 100,` `0 ≀ matrix[i][j] ≀ 9.` - `[output]` an integer The number of different `2 Γ— 2` squares in matrix.
def different_squares(matrix): return len(set(tuple(tuple(row[j:j+2]) for row in matrix[i:i+2]) for i in range(len(matrix)-1) for j in range(len(matrix[0])-1)))
# Task Given a rectangular matrix containing only digits, calculate the number of different `2 Γ— 2` squares in it. # Example For ``` matrix = [[1, 2, 1], [2, 2, 2], [2, 2, 2], [1, 2, 3], [2, 2, 1]] ``` the output should be `6`. Here are all 6 different 2 Γ— 2 squares: ``` 1 2 2 2 2 1 2 2 2 2 2 2 2 2 1 2 2 2 2 3 2 3 2 1 ``` # Input/Output - `[input]` 2D integer array `matrix` Constraints: `1 ≀ matrix.length ≀ 100,` `1 ≀ matrix[i].length ≀ 100,` `0 ≀ matrix[i][j] ≀ 9.` - `[output]` an integer The number of different `2 Γ— 2` squares in matrix.
def different_squares(mat): v = set() for i in range(len(mat) - 1): for j in range(len(mat[0]) - 1): v.add((mat[i][j], mat[i][j + 1], mat[i + 1][j], mat[i + 1][j+1])) return len(v)
# Toggling Grid You are given a grid (2d array) of 0/1's. All 1's represents a solved puzzle. Your job is to come up with a sequence of toggle moves that will solve a scrambled grid. Solved: ``` [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] ``` "0" (first row) toggle: ``` [ [0, 0, 0], [1, 1, 1], [1, 1, 1] ] ``` then "3" (first column) toggle: ``` [ [1, 0, 0], [0, 1, 1], [0, 1, 1] ] ``` The numbers in quotes are codes for the row/column, and will be explained. ## Your task: findSolution() Your task is to write a function, `findSolution()` (or `find_solution()`), which takes as input a 2d array, and returns an array of "steps" that represent a sequence of toggles to solve the puzzle. For example: ```python solution = find_solution(puzzle) print(solution); > [0, 3] ``` Note that, in the above example, `[1, 2, 4, 5]` is also a valid solution! Any solution will pass the tests. The solution is tested like this, for each number in the solution: ```python if n < puzzle.size: toggleRow(n) else: toggleCol(n - puzzle.size) ``` To elaborate, possible n's for a 3x3 puzzle: - Row numbers = (0 --> size - 1) - Cols numbers = (size --> size * 2 - 1) ### Example of "2" toggle: ### Example of "4" toggle: ## More examples: ```python puzzle = [ [ 0, 1, 0 ], [ 1, 0, 1 ], [ 1, 0, 1 ] ]; solution = find_solution(puzzle) print(solution); > [0, 4] ``` let's try some bigger puzzles: ```python puzzle = [ [ 1, 0, 1, 0, 0 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 0 ] ]; solution = find_solution(puzzle) print(solution); > [ 0, 5, 4, 7 ] ``` ```python puzzle = [ [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 0, 0, 0, 1, 0, 0, 0 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ] ]; solution = find_solution(puzzle) print(solution); > [ 3, 10 ] ``` There are randomized tests with puzzles of up to 100x100 in size. Have fun!
def find_solution(m): return [j for j,r in enumerate(m) if r[0]^m[0][0]] + [len(m)+i for i,b in enumerate(m[0]) if not b]
# Toggling Grid You are given a grid (2d array) of 0/1's. All 1's represents a solved puzzle. Your job is to come up with a sequence of toggle moves that will solve a scrambled grid. Solved: ``` [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] ``` "0" (first row) toggle: ``` [ [0, 0, 0], [1, 1, 1], [1, 1, 1] ] ``` then "3" (first column) toggle: ``` [ [1, 0, 0], [0, 1, 1], [0, 1, 1] ] ``` The numbers in quotes are codes for the row/column, and will be explained. ## Your task: findSolution() Your task is to write a function, `findSolution()` (or `find_solution()`), which takes as input a 2d array, and returns an array of "steps" that represent a sequence of toggles to solve the puzzle. For example: ```python solution = find_solution(puzzle) print(solution); > [0, 3] ``` Note that, in the above example, `[1, 2, 4, 5]` is also a valid solution! Any solution will pass the tests. The solution is tested like this, for each number in the solution: ```python if n < puzzle.size: toggleRow(n) else: toggleCol(n - puzzle.size) ``` To elaborate, possible n's for a 3x3 puzzle: - Row numbers = (0 --> size - 1) - Cols numbers = (size --> size * 2 - 1) ### Example of "2" toggle: ### Example of "4" toggle: ## More examples: ```python puzzle = [ [ 0, 1, 0 ], [ 1, 0, 1 ], [ 1, 0, 1 ] ]; solution = find_solution(puzzle) print(solution); > [0, 4] ``` let's try some bigger puzzles: ```python puzzle = [ [ 1, 0, 1, 0, 0 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 0 ] ]; solution = find_solution(puzzle) print(solution); > [ 0, 5, 4, 7 ] ``` ```python puzzle = [ [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 0, 0, 0, 1, 0, 0, 0 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ] ]; solution = find_solution(puzzle) print(solution); > [ 3, 10 ] ``` There are randomized tests with puzzles of up to 100x100 in size. Have fun!
find_solution = lambda m: [n for n, r in enumerate(m) if r[0]] + [n for n, c in enumerate(m[0],len(m)) if not m[0][0] ^ c]
# Toggling Grid You are given a grid (2d array) of 0/1's. All 1's represents a solved puzzle. Your job is to come up with a sequence of toggle moves that will solve a scrambled grid. Solved: ``` [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] ``` "0" (first row) toggle: ``` [ [0, 0, 0], [1, 1, 1], [1, 1, 1] ] ``` then "3" (first column) toggle: ``` [ [1, 0, 0], [0, 1, 1], [0, 1, 1] ] ``` The numbers in quotes are codes for the row/column, and will be explained. ## Your task: findSolution() Your task is to write a function, `findSolution()` (or `find_solution()`), which takes as input a 2d array, and returns an array of "steps" that represent a sequence of toggles to solve the puzzle. For example: ```python solution = find_solution(puzzle) print(solution); > [0, 3] ``` Note that, in the above example, `[1, 2, 4, 5]` is also a valid solution! Any solution will pass the tests. The solution is tested like this, for each number in the solution: ```python if n < puzzle.size: toggleRow(n) else: toggleCol(n - puzzle.size) ``` To elaborate, possible n's for a 3x3 puzzle: - Row numbers = (0 --> size - 1) - Cols numbers = (size --> size * 2 - 1) ### Example of "2" toggle: ### Example of "4" toggle: ## More examples: ```python puzzle = [ [ 0, 1, 0 ], [ 1, 0, 1 ], [ 1, 0, 1 ] ]; solution = find_solution(puzzle) print(solution); > [0, 4] ``` let's try some bigger puzzles: ```python puzzle = [ [ 1, 0, 1, 0, 0 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 0 ] ]; solution = find_solution(puzzle) print(solution); > [ 0, 5, 4, 7 ] ``` ```python puzzle = [ [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 0, 0, 0, 1, 0, 0, 0 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ] ]; solution = find_solution(puzzle) print(solution); > [ 3, 10 ] ``` There are randomized tests with puzzles of up to 100x100 in size. Have fun!
def find_solution(puzzle): n, sol = len(puzzle), [] for i in range(n): if puzzle[i][0] ^ 1: sol.append(i) for i in range(1, n): if puzzle[0][i] ^ 1 ^ (sol and sol[0] == 0): sol.append(n + i) return sol
# Toggling Grid You are given a grid (2d array) of 0/1's. All 1's represents a solved puzzle. Your job is to come up with a sequence of toggle moves that will solve a scrambled grid. Solved: ``` [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] ``` "0" (first row) toggle: ``` [ [0, 0, 0], [1, 1, 1], [1, 1, 1] ] ``` then "3" (first column) toggle: ``` [ [1, 0, 0], [0, 1, 1], [0, 1, 1] ] ``` The numbers in quotes are codes for the row/column, and will be explained. ## Your task: findSolution() Your task is to write a function, `findSolution()` (or `find_solution()`), which takes as input a 2d array, and returns an array of "steps" that represent a sequence of toggles to solve the puzzle. For example: ```python solution = find_solution(puzzle) print(solution); > [0, 3] ``` Note that, in the above example, `[1, 2, 4, 5]` is also a valid solution! Any solution will pass the tests. The solution is tested like this, for each number in the solution: ```python if n < puzzle.size: toggleRow(n) else: toggleCol(n - puzzle.size) ``` To elaborate, possible n's for a 3x3 puzzle: - Row numbers = (0 --> size - 1) - Cols numbers = (size --> size * 2 - 1) ### Example of "2" toggle: ### Example of "4" toggle: ## More examples: ```python puzzle = [ [ 0, 1, 0 ], [ 1, 0, 1 ], [ 1, 0, 1 ] ]; solution = find_solution(puzzle) print(solution); > [0, 4] ``` let's try some bigger puzzles: ```python puzzle = [ [ 1, 0, 1, 0, 0 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 0 ] ]; solution = find_solution(puzzle) print(solution); > [ 0, 5, 4, 7 ] ``` ```python puzzle = [ [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 0, 0, 0, 1, 0, 0, 0 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ] ]; solution = find_solution(puzzle) print(solution); > [ 3, 10 ] ``` There are randomized tests with puzzles of up to 100x100 in size. Have fun!
import copy def find_solution(puzzle): moveset = [] while(True): # Find first rows with most 0's move_to_exe = 0 max_zeros = 0 for i in range(len(puzzle) * 2): score = count_zeros(i, puzzle) if score > max_zeros: max_zeros = score move_to_exe = i if max_zeros == 0: return moveset moveset.append(move_to_exe) if move_to_exe < len(puzzle): puzzle[move_to_exe] = [0 if y == 1 else 1 for y in puzzle[move_to_exe]] else: index = move_to_exe - len(puzzle) for i in range(len(puzzle)): puzzle[i][index] = 0 if puzzle[i][index] == 1 else 1 def count_zeros(move, puzzle): count = 0 # Row toggle if move < len(puzzle): for i in puzzle[move]: count += 1 if i == 0 else 0 else: index = move - len(puzzle) for row in puzzle: count += 1 if row[index] == 0 else 0 return count # UGH that solution is so BASIC! Greedy execution? Lame. I perfer the BF tree search below. """ # Use BFS? def find_solution(puzzle): fringe = [([], puzzle)] while (True): # We should always find a solution for any configuration? (moveset, current_state) = fringe.pop() # Test if current state is a solution valid = True for x in range(len(current_state)): if 0 in current_state[x]: valid = False break if valid: return moveset # If state is not solution then we generate successor states add to fringe queue successors = generate_successors(moveset, current_state) for s in successors: fringe.insert(0, s) # This function takes a moveset and a puzzle and returns all the possible successors for that puzzle def generate_successors(move_list, puzzle): successors = [] for x in range(len(puzzle) * 2): new_state = copy.deepcopy(puzzle) new_move_list = move_list[:] new_move_list.append(x) # If x < len(puzzle) we toggle a row if x < len(puzzle): new_state[x] = [1 if y == 0 else 0 for y in new_state[x]] successors.append((new_move_list, new_state)) # Else toggle column else: index = x - len(puzzle) for i in range(len(puzzle)): new_state[i][index] = 0 if new_state[i][index] == 1 else 1 successors.append((new_move_list, new_state)) return successors """
# Toggling Grid You are given a grid (2d array) of 0/1's. All 1's represents a solved puzzle. Your job is to come up with a sequence of toggle moves that will solve a scrambled grid. Solved: ``` [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] ``` "0" (first row) toggle: ``` [ [0, 0, 0], [1, 1, 1], [1, 1, 1] ] ``` then "3" (first column) toggle: ``` [ [1, 0, 0], [0, 1, 1], [0, 1, 1] ] ``` The numbers in quotes are codes for the row/column, and will be explained. ## Your task: findSolution() Your task is to write a function, `findSolution()` (or `find_solution()`), which takes as input a 2d array, and returns an array of "steps" that represent a sequence of toggles to solve the puzzle. For example: ```python solution = find_solution(puzzle) print(solution); > [0, 3] ``` Note that, in the above example, `[1, 2, 4, 5]` is also a valid solution! Any solution will pass the tests. The solution is tested like this, for each number in the solution: ```python if n < puzzle.size: toggleRow(n) else: toggleCol(n - puzzle.size) ``` To elaborate, possible n's for a 3x3 puzzle: - Row numbers = (0 --> size - 1) - Cols numbers = (size --> size * 2 - 1) ### Example of "2" toggle: ### Example of "4" toggle: ## More examples: ```python puzzle = [ [ 0, 1, 0 ], [ 1, 0, 1 ], [ 1, 0, 1 ] ]; solution = find_solution(puzzle) print(solution); > [0, 4] ``` let's try some bigger puzzles: ```python puzzle = [ [ 1, 0, 1, 0, 0 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 0 ] ]; solution = find_solution(puzzle) print(solution); > [ 0, 5, 4, 7 ] ``` ```python puzzle = [ [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 0, 0, 0, 1, 0, 0, 0 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ] ]; solution = find_solution(puzzle) print(solution); > [ 3, 10 ] ``` There are randomized tests with puzzles of up to 100x100 in size. Have fun!
def find_solution(puzzle): moves = set() n = len(puzzle) zeros = {(i, n + j) for i, row in enumerate(puzzle) for j, v in enumerate(row) if v == 0} if not zeros: return [] def get(): v = None if len(moves) == 0: return zeros.pop() for r, c in zeros: if r in moves or c in moves: if r in moves and c in moves: continue v = (r, c) zeros.remove(v) return v if v is None: return zeros.pop() while zeros: r, c = get() if r not in moves: moves.add(r) for k in range(n, 2 * n): if k == c: continue if (r, k) in zeros: zeros.remove((r, k)) else: zeros.add((r, k)) elif c not in moves: moves.add(c) for k in range(n): if k == r: continue if (k, c) in zeros: zeros.remove((k, c)) else: zeros.add((k, c)) return list(moves)
# Toggling Grid You are given a grid (2d array) of 0/1's. All 1's represents a solved puzzle. Your job is to come up with a sequence of toggle moves that will solve a scrambled grid. Solved: ``` [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] ``` "0" (first row) toggle: ``` [ [0, 0, 0], [1, 1, 1], [1, 1, 1] ] ``` then "3" (first column) toggle: ``` [ [1, 0, 0], [0, 1, 1], [0, 1, 1] ] ``` The numbers in quotes are codes for the row/column, and will be explained. ## Your task: findSolution() Your task is to write a function, `findSolution()` (or `find_solution()`), which takes as input a 2d array, and returns an array of "steps" that represent a sequence of toggles to solve the puzzle. For example: ```python solution = find_solution(puzzle) print(solution); > [0, 3] ``` Note that, in the above example, `[1, 2, 4, 5]` is also a valid solution! Any solution will pass the tests. The solution is tested like this, for each number in the solution: ```python if n < puzzle.size: toggleRow(n) else: toggleCol(n - puzzle.size) ``` To elaborate, possible n's for a 3x3 puzzle: - Row numbers = (0 --> size - 1) - Cols numbers = (size --> size * 2 - 1) ### Example of "2" toggle: ### Example of "4" toggle: ## More examples: ```python puzzle = [ [ 0, 1, 0 ], [ 1, 0, 1 ], [ 1, 0, 1 ] ]; solution = find_solution(puzzle) print(solution); > [0, 4] ``` let's try some bigger puzzles: ```python puzzle = [ [ 1, 0, 1, 0, 0 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 0 ] ]; solution = find_solution(puzzle) print(solution); > [ 0, 5, 4, 7 ] ``` ```python puzzle = [ [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 0, 0, 0, 1, 0, 0, 0 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ] ]; solution = find_solution(puzzle) print(solution); > [ 3, 10 ] ``` There are randomized tests with puzzles of up to 100x100 in size. Have fun!
# returns a sequence of row/column toggles to solve the puzzle # - Examples: # - [3, 7] # - [0, 5, 4, 7] def find_solution(puzzle): first_column = [i for i in range(len(puzzle)) if puzzle[i][0] == 0] value = 1 if 0 in first_column else 0 first_row = [i + len(puzzle) for i in range(len(puzzle)) if puzzle[0][i] == value] return first_row + first_column
# Toggling Grid You are given a grid (2d array) of 0/1's. All 1's represents a solved puzzle. Your job is to come up with a sequence of toggle moves that will solve a scrambled grid. Solved: ``` [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] ``` "0" (first row) toggle: ``` [ [0, 0, 0], [1, 1, 1], [1, 1, 1] ] ``` then "3" (first column) toggle: ``` [ [1, 0, 0], [0, 1, 1], [0, 1, 1] ] ``` The numbers in quotes are codes for the row/column, and will be explained. ## Your task: findSolution() Your task is to write a function, `findSolution()` (or `find_solution()`), which takes as input a 2d array, and returns an array of "steps" that represent a sequence of toggles to solve the puzzle. For example: ```python solution = find_solution(puzzle) print(solution); > [0, 3] ``` Note that, in the above example, `[1, 2, 4, 5]` is also a valid solution! Any solution will pass the tests. The solution is tested like this, for each number in the solution: ```python if n < puzzle.size: toggleRow(n) else: toggleCol(n - puzzle.size) ``` To elaborate, possible n's for a 3x3 puzzle: - Row numbers = (0 --> size - 1) - Cols numbers = (size --> size * 2 - 1) ### Example of "2" toggle: ### Example of "4" toggle: ## More examples: ```python puzzle = [ [ 0, 1, 0 ], [ 1, 0, 1 ], [ 1, 0, 1 ] ]; solution = find_solution(puzzle) print(solution); > [0, 4] ``` let's try some bigger puzzles: ```python puzzle = [ [ 1, 0, 1, 0, 0 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 0 ] ]; solution = find_solution(puzzle) print(solution); > [ 0, 5, 4, 7 ] ``` ```python puzzle = [ [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 0, 0, 0, 1, 0, 0, 0 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ] ]; solution = find_solution(puzzle) print(solution); > [ 3, 10 ] ``` There are randomized tests with puzzles of up to 100x100 in size. Have fun!
# returns a sequence of row/column toggles to solve the puzzle # - Examples: # - [3, 7] # - [0, 5, 4, 7] def find_solution(puzzle): res = [] first_column = [i for i in range(len(puzzle)) if puzzle[i][0] == 0] first_row = [i + len(puzzle) for i in range(len(puzzle)) if puzzle[0][i] == 1] if 0 in first_column else [i + len(puzzle) for i in range(len(puzzle)) if puzzle[0][i] == 0] return first_row + first_column
# Toggling Grid You are given a grid (2d array) of 0/1's. All 1's represents a solved puzzle. Your job is to come up with a sequence of toggle moves that will solve a scrambled grid. Solved: ``` [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] ``` "0" (first row) toggle: ``` [ [0, 0, 0], [1, 1, 1], [1, 1, 1] ] ``` then "3" (first column) toggle: ``` [ [1, 0, 0], [0, 1, 1], [0, 1, 1] ] ``` The numbers in quotes are codes for the row/column, and will be explained. ## Your task: findSolution() Your task is to write a function, `findSolution()` (or `find_solution()`), which takes as input a 2d array, and returns an array of "steps" that represent a sequence of toggles to solve the puzzle. For example: ```python solution = find_solution(puzzle) print(solution); > [0, 3] ``` Note that, in the above example, `[1, 2, 4, 5]` is also a valid solution! Any solution will pass the tests. The solution is tested like this, for each number in the solution: ```python if n < puzzle.size: toggleRow(n) else: toggleCol(n - puzzle.size) ``` To elaborate, possible n's for a 3x3 puzzle: - Row numbers = (0 --> size - 1) - Cols numbers = (size --> size * 2 - 1) ### Example of "2" toggle: ### Example of "4" toggle: ## More examples: ```python puzzle = [ [ 0, 1, 0 ], [ 1, 0, 1 ], [ 1, 0, 1 ] ]; solution = find_solution(puzzle) print(solution); > [0, 4] ``` let's try some bigger puzzles: ```python puzzle = [ [ 1, 0, 1, 0, 0 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 0, 1, 0, 1, 1 ], [ 1, 0, 1, 0, 0 ] ]; solution = find_solution(puzzle) print(solution); > [ 0, 5, 4, 7 ] ``` ```python puzzle = [ [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 0, 0, 0, 1, 0, 0, 0 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 1, 1 ] ]; solution = find_solution(puzzle) print(solution); > [ 3, 10 ] ``` There are randomized tests with puzzles of up to 100x100 in size. Have fun!
def flip_row(puzzle, i): puzzle[i] = list(map(lambda cell: abs(cell - 1), puzzle[i])) def flip_col(puzzle, i): for row in puzzle: row[i] = abs(row[i] - 1) def find_solution(puzzle): result = [] n = len(puzzle) for i in range(1,n): if puzzle[i] != puzzle[i-1]: flip_row(puzzle, i) result.append(i) for i in range(n): if puzzle[0][i] != 1: flip_col(puzzle, i) result.append(i+n) return result
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python). A few examples: ``` randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt" randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs" ``` Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
import random def random_case(x): return "".join([random.choice([c.lower(), c.upper()]) for c in x])
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python). A few examples: ``` randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt" randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs" ``` Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
In [20]: def random_case(x): return "".join([choice([c.lower(), c.upper()]) for c in x]) # That one In [21]: %timeit random_case(s) 834 ms Β± 6.79 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each) In [22]: def random_case(x): return "".join([choice([str.lower, str.upper])(c) for c in x]) # Mine In [23]: %timeit random_case(s) 860 ms Β± 3.77 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each) In [26]: def random_case(x): return "".join([str.lower, str.upper][randrange(2)](c) for c in x) # Blind4Basics In [27]: %timeit random_case(s) 931 ms Β± 3.77 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python). A few examples: ``` randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt" randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs" ``` Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
In [28]: UP_LOW = (str.upper, str.lower) In [29]: def random_case(x): return ''.join(choice(UP_LOW)(c) for c in x) In [30]: %timeit random_case(s) 723 ms Β± 14 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each)
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python). A few examples: ``` randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt" randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs" ``` Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
from random import choice UP_LOW = (str.upper, str.lower) def random_case(strng): return ''.join(choice(UP_LOW)(a) for a in strng)
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python). A few examples: ``` randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt" randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs" ``` Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
import random def random_case(x): result = "" for c in x: if random.randint(0, 1) == 1: result += c.upper() else: result += c.lower() return result
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python). A few examples: ``` randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt" randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs" ``` Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
from random import choice def random_case(x): cases = (str.lower, str.upper) return ''.join(choice(cases)(char) for char in x)
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python). A few examples: ``` randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt" randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs" ``` Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
import random def random_case(s): return ''.join(random.choice([x.lower(), x.upper()]) for x in s)
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python). A few examples: ``` randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt" randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs" ``` Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
import random def random_case(x): return "".join(y.lower() if bool(random.getrandbits(1)) else y.upper() for y in x)
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python). A few examples: ``` randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt" randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs" ``` Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
import random def random_case(string): return "".join(random.choice([str.lower, str.upper])(c) for c in string)
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python). A few examples: ``` randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt" randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs" ``` Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
from random import choice def random_case(x): final = '' for i in x: do = choice(('l', 'u')) final += (i.lower() if do == 'l' else i.upper()) return final
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python). A few examples: ``` randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt" randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs" ``` Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
from random import choice LOWER_UPPER = (str.lower, str.upper) def random_case(text): return ''.join(choice(LOWER_UPPER)(c) for c in text)
Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python). A few examples: ``` randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt" randomCase("Donec eleifend cursus lobortis") == "DONeC ElEifEnD CuRsuS LoBoRTIs" ``` Note: this function will work within the basic ASCII character set to make this kata easier - so no need to make the function multibyte safe.
from random import choice def random_case(text): return ''.join(choice([c.upper(), c.lower()]) for c in text)
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order. Example Input: `['b', 'ba', 'ab', 'bb', 'c']` Expected Output: `['ab', 'b', 'ba', 'bb', 'c']` * The argument for your function will be a generator that will return a new word for each call of next() * Your function will return its own generator of the same words, except your generator will return the words in lexographic order * All words in the list are unique * All words will be comprised of lower case letters only (a-z) * All words will be between 1 and 8 characters long * There will be hundreds of thousands of words to sort * You may not use Python's sorted built-in function * You may not use Python's list.sort method * An empty list of words should result in an empty list. * `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it
import heapq, itertools def sort(iterable): heap = list(iterable) heapq.heapify(heap) return (heapq.heappop(heap) for i in range(len(heap)))
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order. Example Input: `['b', 'ba', 'ab', 'bb', 'c']` Expected Output: `['ab', 'b', 'ba', 'bb', 'c']` * The argument for your function will be a generator that will return a new word for each call of next() * Your function will return its own generator of the same words, except your generator will return the words in lexographic order * All words in the list are unique * All words will be comprised of lower case letters only (a-z) * All words will be between 1 and 8 characters long * There will be hundreds of thousands of words to sort * You may not use Python's sorted built-in function * You may not use Python's list.sort method * An empty list of words should result in an empty list. * `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it
def sort(words): from random import choice from itertools import chain words = list(words) if len(words) <= 1: return iter(words) pivot = choice(words) return chain(sort(w for w in words if w < pivot), [pivot], sort(w for w in words if w > pivot))
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order. Example Input: `['b', 'ba', 'ab', 'bb', 'c']` Expected Output: `['ab', 'b', 'ba', 'bb', 'c']` * The argument for your function will be a generator that will return a new word for each call of next() * Your function will return its own generator of the same words, except your generator will return the words in lexographic order * All words in the list are unique * All words will be comprised of lower case letters only (a-z) * All words will be between 1 and 8 characters long * There will be hundreds of thousands of words to sort * You may not use Python's sorted built-in function * You may not use Python's list.sort method * An empty list of words should result in an empty list. * `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it
from heapq import * def sort(iterable): h = [] for value in iter(iterable): heappush(h, value) return iter([heappop(h) for i in range(len(h))])
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order. Example Input: `['b', 'ba', 'ab', 'bb', 'c']` Expected Output: `['ab', 'b', 'ba', 'bb', 'c']` * The argument for your function will be a generator that will return a new word for each call of next() * Your function will return its own generator of the same words, except your generator will return the words in lexographic order * All words in the list are unique * All words will be comprised of lower case letters only (a-z) * All words will be between 1 and 8 characters long * There will be hundreds of thousands of words to sort * You may not use Python's sorted built-in function * You may not use Python's list.sort method * An empty list of words should result in an empty list. * `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it
def sort(arr): """ You'll have to try harder than that @sazlin """ result = [a for a in arr] result.__getattribute__('sort')() yield from result
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order. Example Input: `['b', 'ba', 'ab', 'bb', 'c']` Expected Output: `['ab', 'b', 'ba', 'bb', 'c']` * The argument for your function will be a generator that will return a new word for each call of next() * Your function will return its own generator of the same words, except your generator will return the words in lexographic order * All words in the list are unique * All words will be comprised of lower case letters only (a-z) * All words will be between 1 and 8 characters long * There will be hundreds of thousands of words to sort * You may not use Python's sorted built-in function * You may not use Python's list.sort method * An empty list of words should result in an empty list. * `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it
import heapq as hp def sort(words): words = list(words) hp.heapify(words) while words: yield hp.heappop(words)
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order. Example Input: `['b', 'ba', 'ab', 'bb', 'c']` Expected Output: `['ab', 'b', 'ba', 'bb', 'c']` * The argument for your function will be a generator that will return a new word for each call of next() * Your function will return its own generator of the same words, except your generator will return the words in lexographic order * All words in the list are unique * All words will be comprised of lower case letters only (a-z) * All words will be between 1 and 8 characters long * There will be hundreds of thousands of words to sort * You may not use Python's sorted built-in function * You may not use Python's list.sort method * An empty list of words should result in an empty list. * `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it
def sort(words): if not words: return it = iter(words) pivot = next(it) lt, ge = [], [] for i in it: if i < pivot: lt.append(i) else: ge.append(i) yield from sort(lt) yield pivot yield from sort(ge)
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order. Example Input: `['b', 'ba', 'ab', 'bb', 'c']` Expected Output: `['ab', 'b', 'ba', 'bb', 'c']` * The argument for your function will be a generator that will return a new word for each call of next() * Your function will return its own generator of the same words, except your generator will return the words in lexographic order * All words in the list are unique * All words will be comprised of lower case letters only (a-z) * All words will be between 1 and 8 characters long * There will be hundreds of thousands of words to sort * You may not use Python's sorted built-in function * You may not use Python's list.sort method * An empty list of words should result in an empty list. * `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it
from heapq import heapify, heappop def sort(words): words = list(words) heapify(words) while words: yield heappop(words)
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order. Example Input: `['b', 'ba', 'ab', 'bb', 'c']` Expected Output: `['ab', 'b', 'ba', 'bb', 'c']` * The argument for your function will be a generator that will return a new word for each call of next() * Your function will return its own generator of the same words, except your generator will return the words in lexographic order * All words in the list are unique * All words will be comprised of lower case letters only (a-z) * All words will be between 1 and 8 characters long * There will be hundreds of thousands of words to sort * You may not use Python's sorted built-in function * You may not use Python's list.sort method * An empty list of words should result in an empty list. * `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it
from itertools import chain def merge_sort(words): if len(words) <= 1: return words midpt = len(words) // 2 arr1 = merge_sort(words[:midpt]) arr2 = merge_sort(words[midpt:]) res = [] while len(arr1) > 0 and len(arr2) > 0: if arr1[0] > arr2[0]: res.append(arr2.pop(0)) else: res.append(arr1.pop(0)) if len(arr1) > 0: res.extend(arr1) else: res.extend(arr2) return res def sort(words): if not words: return [] dict_by_alpha = dict() for a in alphabet: dict_by_alpha[a] = [] for w in words: dict_by_alpha[w[0]] += [w] return chain.from_iterable(merge_sort(dict_by_alpha[a]) for a in alphabet)
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order. Example Input: `['b', 'ba', 'ab', 'bb', 'c']` Expected Output: `['ab', 'b', 'ba', 'bb', 'c']` * The argument for your function will be a generator that will return a new word for each call of next() * Your function will return its own generator of the same words, except your generator will return the words in lexographic order * All words in the list are unique * All words will be comprised of lower case letters only (a-z) * All words will be between 1 and 8 characters long * There will be hundreds of thousands of words to sort * You may not use Python's sorted built-in function * You may not use Python's list.sort method * An empty list of words should result in an empty list. * `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it
from heapq import heappush, heappop def sort(words): heap = [] for w in words: heappush(heap, w) while heap: yield heappop(heap)
Write a `sort` function that will sort a massive list of strings in caseless, lexographic order. Example Input: `['b', 'ba', 'ab', 'bb', 'c']` Expected Output: `['ab', 'b', 'ba', 'bb', 'c']` * The argument for your function will be a generator that will return a new word for each call of next() * Your function will return its own generator of the same words, except your generator will return the words in lexographic order * All words in the list are unique * All words will be comprised of lower case letters only (a-z) * All words will be between 1 and 8 characters long * There will be hundreds of thousands of words to sort * You may not use Python's sorted built-in function * You may not use Python's list.sort method * An empty list of words should result in an empty list. * `alphabet = 'abcdefghijklmnopqrstuvwxyz'` has been pre-defined for you, in case you need it
import heapq def sort(words): heap = [] cnt = 0 for w in words: cnt += 1 heapq.heappush(heap, w) def sorted_gen(): for i in range(cnt): yield heapq.heappop(heap) return sorted_gen()
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️ πŸ—ΊοΈ You would be given a map of the world in a type of string: string s = "01000000X000X011X0X" '0' : uninfected '1' : infected 'X' : ocean ⚫ The virus can't spread in the other side of the ocean. ⚫ If one person is infected every person in this continent gets infected too. ⚫ Your task is to find the percentage of human population that got infected in the end. β˜‘οΈ Return the percentage % of the total population that got infected. ❗❗ The first and the last continent are not connected! πŸ’‘ Example: start: map1 = "01000000X000X011X0X" end: map1 = "11111111X000X111X0X" total = 15 infected = 11 percentage = 100*11/15 = 73.33333333333333 βž• For maps without oceans "X" the whole world is connected. βž• For maps without "0" and "1" return 0 as there is no population.
def infected(s): lands = s.split('X') total = sum(map(len, lands)) infected = sum(len(x) for x in lands if '1' in x) return infected * 100 / (total or 1)
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️ πŸ—ΊοΈ You would be given a map of the world in a type of string: string s = "01000000X000X011X0X" '0' : uninfected '1' : infected 'X' : ocean ⚫ The virus can't spread in the other side of the ocean. ⚫ If one person is infected every person in this continent gets infected too. ⚫ Your task is to find the percentage of human population that got infected in the end. β˜‘οΈ Return the percentage % of the total population that got infected. ❗❗ The first and the last continent are not connected! πŸ’‘ Example: start: map1 = "01000000X000X011X0X" end: map1 = "11111111X000X111X0X" total = 15 infected = 11 percentage = 100*11/15 = 73.33333333333333 βž• For maps without oceans "X" the whole world is connected. βž• For maps without "0" and "1" return 0 as there is no population.
def infected(s): total_population = s.split('X') total = 0 infected = 0 for population in total_population: if "1" in population: infected += len(population) total += len(population) try: return (100 * infected) / total except ZeroDivisionError: return 0
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️ πŸ—ΊοΈ You would be given a map of the world in a type of string: string s = "01000000X000X011X0X" '0' : uninfected '1' : infected 'X' : ocean ⚫ The virus can't spread in the other side of the ocean. ⚫ If one person is infected every person in this continent gets infected too. ⚫ Your task is to find the percentage of human population that got infected in the end. β˜‘οΈ Return the percentage % of the total population that got infected. ❗❗ The first and the last continent are not connected! πŸ’‘ Example: start: map1 = "01000000X000X011X0X" end: map1 = "11111111X000X111X0X" total = 15 infected = 11 percentage = 100*11/15 = 73.33333333333333 βž• For maps without oceans "X" the whole world is connected. βž• For maps without "0" and "1" return 0 as there is no population.
def infected(s): total = infected = 0 curr = isInfected = 0 for c in s: if c == '0' or c == '1': if c == '1': isInfected = -1 curr += 1 elif c == 'X': infected += curr & isInfected total += curr isInfected = curr = 0 infected += curr & isInfected total += curr return infected / (total / 100) if total else 0
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️ πŸ—ΊοΈ You would be given a map of the world in a type of string: string s = "01000000X000X011X0X" '0' : uninfected '1' : infected 'X' : ocean ⚫ The virus can't spread in the other side of the ocean. ⚫ If one person is infected every person in this continent gets infected too. ⚫ Your task is to find the percentage of human population that got infected in the end. β˜‘οΈ Return the percentage % of the total population that got infected. ❗❗ The first and the last continent are not connected! πŸ’‘ Example: start: map1 = "01000000X000X011X0X" end: map1 = "11111111X000X111X0X" total = 15 infected = 11 percentage = 100*11/15 = 73.33333333333333 βž• For maps without oceans "X" the whole world is connected. βž• For maps without "0" and "1" return 0 as there is no population.
def infected(s): inf=0 saf=0 for c in s.split('X') : if '1' in c : inf += len(c) else : saf += len(c) return 0 if inf+saf==0 else inf/(inf+saf)*100
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️ πŸ—ΊοΈ You would be given a map of the world in a type of string: string s = "01000000X000X011X0X" '0' : uninfected '1' : infected 'X' : ocean ⚫ The virus can't spread in the other side of the ocean. ⚫ If one person is infected every person in this continent gets infected too. ⚫ Your task is to find the percentage of human population that got infected in the end. β˜‘οΈ Return the percentage % of the total population that got infected. ❗❗ The first and the last continent are not connected! πŸ’‘ Example: start: map1 = "01000000X000X011X0X" end: map1 = "11111111X000X111X0X" total = 15 infected = 11 percentage = 100*11/15 = 73.33333333333333 βž• For maps without oceans "X" the whole world is connected. βž• For maps without "0" and "1" return 0 as there is no population.
def infected(s): total = len(s)-s.count('X') infected = sum([len(i) for i in s.split('X') if '1' in i]) return infected/total*100 if total > 0 else infected
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️ πŸ—ΊοΈ You would be given a map of the world in a type of string: string s = "01000000X000X011X0X" '0' : uninfected '1' : infected 'X' : ocean ⚫ The virus can't spread in the other side of the ocean. ⚫ If one person is infected every person in this continent gets infected too. ⚫ Your task is to find the percentage of human population that got infected in the end. β˜‘οΈ Return the percentage % of the total population that got infected. ❗❗ The first and the last continent are not connected! πŸ’‘ Example: start: map1 = "01000000X000X011X0X" end: map1 = "11111111X000X111X0X" total = 15 infected = 11 percentage = 100*11/15 = 73.33333333333333 βž• For maps without oceans "X" the whole world is connected. βž• For maps without "0" and "1" return 0 as there is no population.
import re def infected(s): n = sum(map(len, re.findall(r'0*1[01]*', s))) s = len(s.replace('X','')) return s and 100*n/s
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️ πŸ—ΊοΈ You would be given a map of the world in a type of string: string s = "01000000X000X011X0X" '0' : uninfected '1' : infected 'X' : ocean ⚫ The virus can't spread in the other side of the ocean. ⚫ If one person is infected every person in this continent gets infected too. ⚫ Your task is to find the percentage of human population that got infected in the end. β˜‘οΈ Return the percentage % of the total population that got infected. ❗❗ The first and the last continent are not connected! πŸ’‘ Example: start: map1 = "01000000X000X011X0X" end: map1 = "11111111X000X111X0X" total = 15 infected = 11 percentage = 100*11/15 = 73.33333333333333 βž• For maps without oceans "X" the whole world is connected. βž• For maps without "0" and "1" return 0 as there is no population.
def infected(s): population = len(s) - s.count('X') return population and 100 * sum(len(continent) for continent in s.split('X') if '1' in continent) / population
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️ πŸ—ΊοΈ You would be given a map of the world in a type of string: string s = "01000000X000X011X0X" '0' : uninfected '1' : infected 'X' : ocean ⚫ The virus can't spread in the other side of the ocean. ⚫ If one person is infected every person in this continent gets infected too. ⚫ Your task is to find the percentage of human population that got infected in the end. β˜‘οΈ Return the percentage % of the total population that got infected. ❗❗ The first and the last continent are not connected! πŸ’‘ Example: start: map1 = "01000000X000X011X0X" end: map1 = "11111111X000X111X0X" total = 15 infected = 11 percentage = 100*11/15 = 73.33333333333333 βž• For maps without oceans "X" the whole world is connected. βž• For maps without "0" and "1" return 0 as there is no population.
def infected(s): infected = 0 total = 0 for land in s.split('X'): if '1' in land: infected += len(land) total += len(land) return infected / total * 100 if total > 0 else 0
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️ πŸ—ΊοΈ You would be given a map of the world in a type of string: string s = "01000000X000X011X0X" '0' : uninfected '1' : infected 'X' : ocean ⚫ The virus can't spread in the other side of the ocean. ⚫ If one person is infected every person in this continent gets infected too. ⚫ Your task is to find the percentage of human population that got infected in the end. β˜‘οΈ Return the percentage % of the total population that got infected. ❗❗ The first and the last continent are not connected! πŸ’‘ Example: start: map1 = "01000000X000X011X0X" end: map1 = "11111111X000X111X0X" total = 15 infected = 11 percentage = 100*11/15 = 73.33333333333333 βž• For maps without oceans "X" the whole world is connected. βž• For maps without "0" and "1" return 0 as there is no population.
def infected(s): totalinf = 0 total = 0 p = s.split('X') for item in p: if '1' in item: totalinf += len(item) total += len(item) else: total += len(item) return (float(100) * totalinf) / total if total !=0 else 0
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️ πŸ—ΊοΈ You would be given a map of the world in a type of string: string s = "01000000X000X011X0X" '0' : uninfected '1' : infected 'X' : ocean ⚫ The virus can't spread in the other side of the ocean. ⚫ If one person is infected every person in this continent gets infected too. ⚫ Your task is to find the percentage of human population that got infected in the end. β˜‘οΈ Return the percentage % of the total population that got infected. ❗❗ The first and the last continent are not connected! πŸ’‘ Example: start: map1 = "01000000X000X011X0X" end: map1 = "11111111X000X111X0X" total = 15 infected = 11 percentage = 100*11/15 = 73.33333333333333 βž• For maps without oceans "X" the whole world is connected. βž• For maps without "0" and "1" return 0 as there is no population.
def infected(s): if '1' not in s: return 0 s = s.split('X') return sum(len(i) for i in s if '1' in i) / sum(map(len, s)) * 100
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure) (the dedicated builtin(s) functionalities are deactivated)
from collections import deque def reverse(lst): q = deque() for x in lst: q.appendleft(x) return list(q)
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure) (the dedicated builtin(s) functionalities are deactivated)
def reverse(lst): out = list() for i in range(len(lst)-1,-1,-1): out.append(lst[i]) return out
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure) (the dedicated builtin(s) functionalities are deactivated)
def reverse(lst): empty_list = list() # use this! result = list() while lst: result.append(lst.pop()) return result
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure) (the dedicated builtin(s) functionalities are deactivated)
def reverse(lst): empty_list = list() for i in range(len(lst)): empty_list.append(lst.pop()) return empty_list
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure) (the dedicated builtin(s) functionalities are deactivated)
def reverse(lst): out = list() while lst: out.append(lst.pop(-1)) return out
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure) (the dedicated builtin(s) functionalities are deactivated)
from collections import deque def reverse(lst): cheat = deque(lst) cheat.reverse() return list(cheat)
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure) (the dedicated builtin(s) functionalities are deactivated)
def reverse(lst): out = list() for x in lst: out.insert(0, x) return out
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure) (the dedicated builtin(s) functionalities are deactivated)
def reverse(lst): result = list() for item in lst: result.insert(0, item) return result
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure) (the dedicated builtin(s) functionalities are deactivated)
def reverse(lst): temp = lst.copy() lst.clear() for i in range(len(temp)-1, -1, -1): lst.append(temp[i]) return lst
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure) (the dedicated builtin(s) functionalities are deactivated)
def reverse(lst): empty_list = list() for i in lst: empty_list = [i] + empty_list return empty_list
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds. *The Martingale strategy* You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet. ## Example ``` martingale(1000, [1, 1, 0, 0, 1]) === 1300 ``` Explanation: * you win your 1st round: gain $100, balance = 1100 * you win the 2nd round: gain $100, balance = 1200 * you lose the 3rd round: lose $100 dollars, balance = 1100 * double stake for 4th round and lose: staked $200, lose $200, balance = 900 * double stake for 5th round and win: staked $400, won $400, balance = 1300 **Note: Your balance is allowed to go below 0.**
def martingale(bank, outcomes): stake = 100 for i in outcomes: if i == 0: bank -= stake stake *= 2 else: bank += stake stake = 100 return bank
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds. *The Martingale strategy* You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet. ## Example ``` martingale(1000, [1, 1, 0, 0, 1]) === 1300 ``` Explanation: * you win your 1st round: gain $100, balance = 1100 * you win the 2nd round: gain $100, balance = 1200 * you lose the 3rd round: lose $100 dollars, balance = 1100 * double stake for 4th round and lose: staked $200, lose $200, balance = 900 * double stake for 5th round and win: staked $400, won $400, balance = 1300 **Note: Your balance is allowed to go below 0.**
def martingale(bank, outcomes): bet=100 for results in outcomes: if not bool(results): bank= bank -bet bet*=2 if bool(results): bank=bank+bet bet=100 return bank
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds. *The Martingale strategy* You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet. ## Example ``` martingale(1000, [1, 1, 0, 0, 1]) === 1300 ``` Explanation: * you win your 1st round: gain $100, balance = 1100 * you win the 2nd round: gain $100, balance = 1200 * you lose the 3rd round: lose $100 dollars, balance = 1100 * double stake for 4th round and lose: staked $200, lose $200, balance = 900 * double stake for 5th round and win: staked $400, won $400, balance = 1300 **Note: Your balance is allowed to go below 0.**
def martingale(bank, outcomes): nxt = 100 for result in outcomes: if result: bank += nxt nxt = 100 else: bank -= nxt nxt *= 2 return bank
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds. *The Martingale strategy* You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet. ## Example ``` martingale(1000, [1, 1, 0, 0, 1]) === 1300 ``` Explanation: * you win your 1st round: gain $100, balance = 1100 * you win the 2nd round: gain $100, balance = 1200 * you lose the 3rd round: lose $100 dollars, balance = 1100 * double stake for 4th round and lose: staked $200, lose $200, balance = 900 * double stake for 5th round and win: staked $400, won $400, balance = 1300 **Note: Your balance is allowed to go below 0.**
def martingale(n, a, m=100): return sum((y := x and m or -m) and (m := x and 100 or m * 2) and y for x in a) + n
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds. *The Martingale strategy* You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet. ## Example ``` martingale(1000, [1, 1, 0, 0, 1]) === 1300 ``` Explanation: * you win your 1st round: gain $100, balance = 1100 * you win the 2nd round: gain $100, balance = 1200 * you lose the 3rd round: lose $100 dollars, balance = 1100 * double stake for 4th round and lose: staked $200, lose $200, balance = 900 * double stake for 5th round and win: staked $400, won $400, balance = 1300 **Note: Your balance is allowed to go below 0.**
def martingale(bank, outcomes): loss=win=0 stake=100 for i in outcomes: if i==1: bank+=stake if stake!=100: stake=100 else: bank-=stake stake*=2 return bank #beat the house here...
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds. *The Martingale strategy* You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet. ## Example ``` martingale(1000, [1, 1, 0, 0, 1]) === 1300 ``` Explanation: * you win your 1st round: gain $100, balance = 1100 * you win the 2nd round: gain $100, balance = 1200 * you lose the 3rd round: lose $100 dollars, balance = 1100 * double stake for 4th round and lose: staked $200, lose $200, balance = 900 * double stake for 5th round and win: staked $400, won $400, balance = 1300 **Note: Your balance is allowed to go below 0.**
def martingale(bank, outcomes, rate = 100): for i in outcomes: bank -= rate if i: bank += rate*2 rate = 100 else: rate *= 2 return bank
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds. *The Martingale strategy* You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet. ## Example ``` martingale(1000, [1, 1, 0, 0, 1]) === 1300 ``` Explanation: * you win your 1st round: gain $100, balance = 1100 * you win the 2nd round: gain $100, balance = 1200 * you lose the 3rd round: lose $100 dollars, balance = 1100 * double stake for 4th round and lose: staked $200, lose $200, balance = 900 * double stake for 5th round and win: staked $400, won $400, balance = 1300 **Note: Your balance is allowed to go below 0.**
def martingale(bankRoll, outcomes): baseBet = 100 betMultiplier = 1 for i in outcomes: if i: #we won: Update our bank roll, reset our bet to the base case of 100 bankRoll += betMultiplier*baseBet betMultiplier = 1 else: #we lost: Update our bank roll, double our previous bet bankRoll -= betMultiplier*baseBet betMultiplier *= 2 return bankRoll #end martingale function
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds. *The Martingale strategy* You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet. ## Example ``` martingale(1000, [1, 1, 0, 0, 1]) === 1300 ``` Explanation: * you win your 1st round: gain $100, balance = 1100 * you win the 2nd round: gain $100, balance = 1200 * you lose the 3rd round: lose $100 dollars, balance = 1100 * double stake for 4th round and lose: staked $200, lose $200, balance = 900 * double stake for 5th round and win: staked $400, won $400, balance = 1300 **Note: Your balance is allowed to go below 0.**
BASE_BET = 100 def martingale(bank, outcomes, bet = BASE_BET): for win in outcomes: if win: bank += bet bet = BASE_BET else: bank -= bet bet *= 2 return bank
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds. *The Martingale strategy* You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet. ## Example ``` martingale(1000, [1, 1, 0, 0, 1]) === 1300 ``` Explanation: * you win your 1st round: gain $100, balance = 1100 * you win the 2nd round: gain $100, balance = 1200 * you lose the 3rd round: lose $100 dollars, balance = 1100 * double stake for 4th round and lose: staked $200, lose $200, balance = 900 * double stake for 5th round and win: staked $400, won $400, balance = 1300 **Note: Your balance is allowed to go below 0.**
def martingale(bank, outcomes): balance = bank stake = 100 for win in outcomes: if win: balance += stake stake = 100 else: balance -= stake stake *= 2 return balance
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds. *The Martingale strategy* You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet. ## Example ``` martingale(1000, [1, 1, 0, 0, 1]) === 1300 ``` Explanation: * you win your 1st round: gain $100, balance = 1100 * you win the 2nd round: gain $100, balance = 1200 * you lose the 3rd round: lose $100 dollars, balance = 1100 * double stake for 4th round and lose: staked $200, lose $200, balance = 900 * double stake for 5th round and win: staked $400, won $400, balance = 1300 **Note: Your balance is allowed to go below 0.**
def martingale(bank, outcomes): risking = 100 for outcome in outcomes: if outcome == 0: bank -= risking risking *= 2 if outcome == 1: bank += risking risking = 100 return bank
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive. For example: ```python count_char("fizzbuzz","z") => 4 count_char("Fancy fifth fly aloof","f") => 5 ``` The character can be any alphanumeric character. Good luck.
def count_char(s,c): return s.lower().count(c.lower())
The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive. For example: ```python count_char("fizzbuzz","z") => 4 count_char("Fancy fifth fly aloof","f") => 5 ``` The character can be any alphanumeric character. Good luck.
def count_char(strng, c): return strng.lower().count(c.lower())