# Сортировка строки. В каждом слове содержится число.
# "is2 Thi1s T4est 3a"  -->  "Thi1s is2 3a T4est"
# "4of Fo1r pe6ople g3ood th5e the2"  -->  "Fo1r the2 g3ood 4of th5e pe6ople"

from msilib import sequence
from operator import itemgetter
from numpy import block


def order(sentence):
    my_list = sentence.split(' ')
    new_list = []
    print(my_list)
    for i in range(len(my_list)):
        for j in range(len(my_list)):
            if my_list[j].rfind(str(i+1)) != -1:
                new_list.append(my_list[j])

                
    return (' '.join(new_list))

# 
# def order(sentence):
    # return " ".join(sorted(sentence.split(), key=lambda x: int(filter(str.isdigit, x))))

# 
# def order(words):
#   return ' '.join(sorted(words.split(), key=lambda w:sorted(w)))


# print(order("is2 Thi1s T4est 3a"))

# ------------------------------------------------------------------------------- #

#
def find_even_index(arr):
    sum_left = 0
    sum_right = 0
    sum = []
    for i in range(len(arr)):
        for j in range(i):
            sum_left += arr[j]
        for k in range(len(arr) - 1,i ,-1):
            sum_right += arr[k]

        if sum_left == sum_right:
            sum.append(i)

        # print(f"Sum let: {sum_left} and sun right: {sum_right}")
        sum_left = sum_right = 0

    if len(sum) == 0:
        return -1
    else:
        sum.sort()
        return(sum[0])

'''
# Лучшее решение
def find_even_index(arr):
    for i in range(len(arr)):
        if sum(arr[:i]) == sum(arr[i+1:]):
            return i
    return -1
'''

# print(find_even_index([1,2,3,4,3,2,1]))
# print(find_even_index([1,2,3,4,5,6]))

# ------------------------------------------------------------------------------- #
# Задачка на работу с boxplot 
# Пока не завершил.

class StatisticalSummary(object):

    BOXPLOT = 0
    BOX_AND_WHISKER = 1
    BOX_AND_DECILE_WHISKER = 2
    TUKEY_BOX_AND_WHISKER = 3

    def __init__(self, seq):
        self.seq = seq
        self.le = 0 
        self.eu = 0 
        self.median = 0
        self.q1 = 0
        self.q3 = 0   

    def boxplot(self, plot=BOXPLOT, precision=None):
        result = []
        temp_list = []
        number = 0
        
        if type(self.seq[0]) == tuple:
            print("Пока не обрабатываем картежи")
        else:
            temp_list = self.clear_list(self.seq)
            temp_list.sort()
            self.calculation(temp_list)

            result.append(('Sample', number))

            return result
        
    def calculation(self, data):
        self.le = min(data)
        self.eu = max(data)
        self.median = self.calculate_median(data)
        self.calculate_quartile(data)
        


    def clear_list(self, data):
        cleared_list = []
        for i in data:
            if type(i) == int or type(i) == float:
                cleared_list.append(i)
        return cleared_list

    def calculate_median(self, data):
        data_len = len(data)
        if data_len%2 == 0:
            return ((data[int(data_len/2) - 1] + data[int(data_len/2)]))/2
        else:
            return data[data_len//2]

    def calculate_quartile(self, data):
        data_len = len(data)

        if data_len%4 == 0:
            index = int(data_len/4)
            q1 = (data[index] - data[index - 1])*0.25 + data[index - 1]
            index = int(data_len/4*3)
            q3 = (data[index] - data[index - 1])*0.75 + data[index - 1]
            print(data)
            print(q1)
            print(q3)
            return q1, q3
        

# data = list(range(1, 33)) + list(range(12, 21)) + list(range(12, 21)) + list(range(12, 21)) + [16]
# d1 = list(range(1, 33)) + list(range(12, 21)) + list(range(12, 21)) + list(range(12, 21)) + [16]

# print(data)

# d1 = range(1, 33) + range(12, 21) + range(12, 21) + range(12, 21) + [16]
# d2 = [d - 2 for d in d1[:len(data)//2]] + [d + 2 for d in d1[len(data)//2:]]
# data2 = [("A", n) for n in d1] + [("B", n) for n in d2]



# print(data2)
# print(type(data2))
# print(d2)
# test_list = [1, 2, 5, 2, 3, 'asdfasd', 2, 3, 12, 45, 3, 6, 25, 54, 32, 12, 14, 2]

# summary1 = StatisticalSummary(test_list)
# summary1.boxplot()

# ------------------------------------------------------------------------------- #

def is_valid_walk(walk):
    horizontl = 0
    vertical = 0
    for i in walk:
        if i == 'n':
            vertical += 1
        elif i == 's':
            vertical -= 1
        elif i == 'w':
            horizontl -= 1
        elif i == 'e':
            horizontl += 1
    
    return vertical == 0 and horizontl == 0 and len(walk) == 10
    

# Решение через метод count
# def isValidWalk(walk):
    # return len(walk) == 10 and walk.count('n') == walk.count('s') and walk.count('e') == walk.count('w')

# print(is_valid_walk(['w','e','w','e','w','e','w','e','w','e','w','e']))

# ------------------------------------------------------------------------------- #

# На входе одно число из массив четное или нечетно. Нужно его найти и вернуть.
def find_outlier(integers):
    types = []

    def is_even(value):
        return value%2 == 0

    for i in integers:
        types.append(is_even(i))
    
    if types.count(True) > types.count(False):
        return integers[types.index(False)]
    else:
        return integers[types.index(True)]


# Более короткое решение
# def find_outlier(int):
    # odds = [x for x in int if x%2!=0]
    # evens= [x for x in int if x%2==0]
    # return odds[0] if len(odds)<len(evens) else evens[0]


# print(find_outlier([2, 4, 0, 100, 4, 11, 2602, 36]))

# ------------------------------------------------------------------------------- #

# В переданной строке должно быть только 4 или 6 цифр       
def validate_pin(pin):
    return len(pin) in (4, 6) and pin.isdigit()

# print(validate_pin('-234'))

# ------------------------------------------------------------------------------- #

# Преобразует список в десятичное число
def binary_array_to_number(arr):
    return int(''.join(str(_) for _ in arr), 2)

# Решение через функцию map (Применяет функцию str к каждому элементу итерируемого объекта)
# def binary_array_to_number(arr):
    # return int("".join(map(str, arr)), 2)

# print(binary_array_to_number([1,0,0,1]))

# ------------------------------------------------------------------------------- #
def litres(time):
    return int(time*0.5//1)

# print(litres(2))

# ------------------------------------------------------------------------------- #

# Нужно вернуть n числе последовательности Трибоначчи
'''
def tribonacci(signature, n):
    sequence = []
    
    if n < 3:
        for i in range(n):
            sequence.append(signature[i])
        return sequence
    else:
        sequence.extend(signature)

    for i in range(3, n):
        sequence.append(sequence[i-3] + sequence[i-2] + sequence[i-1])

    return(sequence)
'''


# Хорошее решение через срез
def tribonacci(signature, n):
  res = signature[:n]
  print(res)
  for i in range(n - 3): 
      res.append(sum(res[-3:]))
  return res


# print(tribonacci([0.5, 0.5, 0.5], 1))