[6 kyu] Sort the odd

You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places.

Note: Zero isn’t an odd number and you don’t need to move it. If you have an empty array, you need to return it.

Example

sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]

Solution :

def sort_array(source_array):
    odd_list = []
    if source_array == []:
        return []
    else:
        for i in range(len(source_array)):
            if source_array[i] % 2 != 0:
                odd_list.append(source_array[i])
                source_array[i] = None
    odd_list.sort()
    for index in range(len(source_array)):
        if source_array[index] is None:
            source_array[index] = odd_list[0]
            odd_list.pop(0)
    return source_array
    # Return a sorted array.
发布了16 篇原创文章 · 获赞 0 · 访问量 46

猜你喜欢

转载自blog.csdn.net/HM_773_220/article/details/104771928