codewars_DAY 2

来源:互联网 发布:天猫超市和淘宝店铺 编辑:程序博客网 时间:2024/06/02 01:40
  • Q1 The observed PIN:

Alright, detective, one of our colleagues successfully observed our target person, Robby the robber. We followed him to a secret warehouse, where we assume to find all the stolen stuff. The door to this warehouse is secured by an electronic combination lock. Unfortunately our spy isn’t sure about the PIN he saw, when Robby entered it.

The keypad has the following layout:

┌───┬───┬───┐
│ 1 │ 2 │ 3 │
├───┼───┼───┤
│ 4 │ 5 │ 6 │
├───┼───┼───┤
│ 7 │ 8 │ 9 │
└───┼───┼───┘
│ 0 │
└───┘
He noted the PIN 1357, but he also said, it is possible that each of the digits he saw could actually be another adjacent digit (horizontally or vertically, but not diagonally). E.g. instead of the 1 it could also be the 2 or 4. And instead of the 5 it could also be the 2, 4, 6 or 8.

He also mentioned, he knows this kind of locks. You can enter an unlimited amount of wrong PINs, they never finally lock the system or sound the alarm. That’s why we can try out all possible (*) variations.

* possible in sense of: the observed PIN itself and all variations considering the adjacent digits

Can you help us to find all those variations? It would be nice to have a function, that returns an array of all variations for an observed PIN with a length of 1 to 8 digits. We could name the function getPINs (get_pins in python). But please note that all PINs, the observed one and also the results, must be strings, because of potentially leading ‘0’s. We already prepared some test cases for you.

Detective, we count on you!

  • my answer:

    def get_pins(observed):    dic = {'1': '124', '2': '1235', '3': '236',             '4': '1457', '5': '24568', '6': '3569',             '7': '478', '8': '57890', '9': '689',             '0': '08'}    #results = set()    observed = list(observed)    for i in range(len(observed)):        observed[i] = dic[observed[i]]    observed[0] = list(observed[0])    while len(observed) != 1:        tmp = list(observed[1])        observed.pop(1)        p = set()        for i in observed[0]:            for j in tmp:                p.add(i+j)        observed[0] = list(p)    return observed[0]
  • other answer:

    adjacents = {      '1': ['2', '4'],      '2': ['1', '5', '3'],      '3': ['2', '6'],      '4': ['1', '5', '7'],      '5': ['2', '4', '6', '8'],      '6': ['3', '5', '9'],      '7': ['4', '8'],      '8': ['5', '7', '9', '0'],      '9': ['6', '8'],      '0': ['8'],    }def get_pins(observed):  if len(observed) == 1:    return adjacents[observed] + [observed]  return [a + b for a in adjacents[observed[0]] + [observed[0]] for b in get_pins(observed[1:])]

  • Q2 Snail:

Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
For better understanding, please follow the numbers of the next array consecutively:

array = [[1,2,3],
[8,9,4],
[7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]

  • my answer:

        def snail(array):    arr = []    def snail(array, arr=[]):        length = len(array)        if length == 2:            arr.extend([array[0][0], array[0][1], array[1][1], array[1][0]])            return        if length == 1:            arr += array[0]            return        tmp = [[] for i in range(4)]        for i in range(length):            tmp[0].append(array[0][i])            tmp[1].append(array[i][length - 1])            tmp[2].append(array[length - 1][length - i - 1])            tmp[3].append(array[length - i - 1][0])        arr.extend(tmp[0][:] + tmp[1][1:] + tmp[2][1:] + tmp[3][1:-1])        t_arr = [[] for i in range(length - 2)]        for i in range(length - 2):            p = array[i + 1][1:-1]            t_arr[i] += array[i + 1][1:-1]        snail(t_arr, arr)        return    snail(array, arr)    return arr
  • other answer:

    def snail(array):    return list(array[0]) + snail(zip(*array[1:])[::-1]) if array else []

  • Q3 Square into Squares. Protect trees!:

Description:

My little sister came back home from school with the following task: given a squared sheet of paper she has to cut it in pieces which, when assembled, give squares the sides of which form an increasing sequence of numbers. At the beginning it was lot of fun but little by little we were tired of seeing the pile of torn paper. So we decided to write a program that could help us and protects trees.

Task

Given a positive integral number n, return a strictly increasing sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n².

If there are multiple solutions (and there will be), return the result with the largest possible values:

Examples

decompose(11) must return [1,2,4,10]. Note that there are actually two ways to decompose 11², 11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10² but don’t return [2,6,9], since 9 is smaller than 10.

For decompose(50) don’t return [1, 1, 4, 9, 49] but [1, 3, 5, 8, 49] since [1, 1, 4, 9, 49] doesn’t form a strictly increasing sequence.

Note

Neither [n] nor [1,1,1,…,1] are valid solutions. If no valid solution exists, return nil, null, Nothing, None (depending on the language) or “” (Java, C#) or {} (C++).

The function “decompose” will take a positive integer n and return the decomposition of N = n² as:

[x1 … xk]
Hint

Very often xk will be n-1.

  • my answer:

    def decompose(n):    if n == 0 or n == 1: return [n]    sum = 2 * n - 1       ##n ** 2 - (n - 1) ** 2    arr = []    getNum(sum, arr)    if not arr: return None    arr.append(n-1)    return sorted(arr)def getNum(p, arr=[]):    if p == 0: return True    if p == 1:        if p in arr:            return False        arr.append(1)        return True    maxi = int(sqrt(p))    for i in range(1, maxi+1)[::-1]:        if i in arr:            continue        arr.append(i)        if getNum(p - i**2, arr):            return True        arr.pop()    return False
  • other1 :

    def decompose(n):    def _recurse(s, i):        if s < 0:            return None        if s == 0:            return []        for j in xrange(i-1, 0, -1):            sub = _recurse(s - j**2, j)            if sub != None:                return sub + [j]    return _recurse(n**2, n)
  • other2:

    def decompose(n):    total = 0    answer = [n]    while len(answer):        temp = answer.pop()        total += temp ** 2        for i in range(temp - 1, 0, -1):            if total - (i ** 2) >= 0:                total -= i ** 2                answer.append(i)                if total == 0:                    return sorted(answer)    return None
0 0
原创粉丝点击