Sunday, April 3, 2022

How Green Is My Valley? Python Codewars

Task:

  • Input : an array of integers.

  • Output : this array, but sorted in such a way that there are two wings:

  • the left wing with numbers decreasing,

  • the right wing with numbers increasing.

  • the two wings have the same length. If the length of the array is odd the wings are around the bottom, if the length is even the bottom is considered to be part of the right wing.

  • each integer l of the left wing must be greater or equal to its counterpart r in the right wing, the difference l - r being as small as possible. In other words the right wing must be nearly as steep as the left wing.

The function is make_valley or makeValley or make-valley.

a = [79, 35, 54, 19, 35, 25]
make_valley(a) --> [79, 35, 25, *19*, 35, 54]
The bottom is 19, left wing is [79, 35, 25], right wing is [*19*, 35, 54].
79..................54
    35..........35
        25. 
          ..19

Solution:


def make_valley(arr):
    lst = sorted(arr)
    if len(lst)% 2 == 1:
        center = [lst.pop(0)]
    else:
        center = []
    left = []
    right = []
    for idx in range(0,len(lst)):
        if idx % 2 == 0:
            right.append(lst[idx])
        else:
            left.append(lst[idx])
    left.sort(reverse=True)
    return left + center + right

print(make_valley([17, 17, 15, 14, 8, 7, 7, 5, 4, 4, 1]))

How Green Is My Valley? Solutions | Codewars



Related Posts


No comments :

Post a Comment