코드로 우주평화

English beggars 본문

나는 이렇게 학습한다/Algorithm & SQL

English beggars

daco2020 2022. 3. 16. 21:58
반응형

Description:

Born a misinterpretation of this kata, your task here is pretty simple: given an array of values and an amount of beggars, you are supposed to return an array with the sum of what each beggar brings home, assuming they all take regular turns, from the first to the last.

 

For example: [1,2,3,4,5] for 2 beggars will return a result of [9,6], as the first one takes [1,3,5], the second collects [2,4].

 

The same array with 3 beggars would have in turn have produced a better out come for the second beggar: [5,7,3], as they will respectively take [1,4], [2,5] and [3].

 

Also note that not all beggars have to take the same amount of "offers", meaning that the length of the array is not necessarily a multiple of n; length can be even shorter, in which case the last beggars will of course take nothing (0).

 

Note: in case you don't get why this kata is about English beggars, then you are not familiar on how religiously queues are taken in the kingdom ;)

 

Note 2: do not modify the input array.

 

 

Solution:

1. Skip the order of elements in the array by 'n' and add values.
2. Put the added values ​​in the dictionary in order.
3. Only the values ​​of the dictionary are returned as a list.

 

def beggars(values, n):
    temp_dict = {}
    for i in range(n):
        count = 0
        for _ in values:
            if temp_dict.get(i):
                temp_dict[i] += sum(values[i+count:i+count+1])
            else:
                temp_dict[i] = sum(values[i+count:i+count+1])
            count += n
            
    return list(temp_dict.values())

 

 

 

Best Practices:

def beggars(values, n):
    return [sum(values[i::n]) for i in range(n)]

Using skipping of slices makes it easier to find.

 

 

반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

자료구조 _ Array와 Dynamic Array  (0) 2022.03.17
Meeting  (0) 2022.03.17
Kebabize  (0) 2022.03.16
+1 Array  (0) 2022.03.15
A square of squares  (0) 2022.03.13