#!/usr/bin/env python3 """Sorts all even integers in a list and leaves all odd integers in place. The program prompts the user to enter a sequence of integers. It then sorts all even integers in the sequence and leaves all odd integers in their original position, and prints out the sorted sequence, elements separated by spaces. """ import sys __author__ = "Alan Mao and Patrick Duhanxhiu" __copyright__ = "Copyright (c) 2016, Alan Mao and Patrick Duhanxhiu" def merge_sort(nums, start, end): if start < end: middle = (start + end) // 2 merge_sort(nums, start, middle) merge_sort(nums, middle + 1, end) merge(nums, start, middle, end) def merge(nums, start, middle, end): list1 = nums[start:middle + 1] list2 = nums[middle + 1:end + 1] list1.append(sys.maxsize) list2.append(sys.maxsize) index1 = 0 index2 = 0 for index in range(start, end + 1): if list1[index1] <= list2[index2]: nums[index] = list1[index1] index1 += 1 else: assert list1[index1] > list2[index2] nums[index] = list2[index2] index2 += 1 def file_init(nums): file_name = input('Enter the file name: ') try: file = open(file_name) except OSError: print('Error: the file specified cannot be opened') sys.exit(0) for line in file: for token in line.split(): nums.append(int(token)) def stdin_init(nums): try: for k in input('Enter a sequence of integers: ').split(): nums.append(int(k)) except (TypeError, ValueError): print('Please enter a sequence of integers. ') stdin_init(nums) ints = [] while True: input_method = input('Read the input from a file or from the standard input? ') if input_method == 'File': file_init(ints) break elif input_method == 'Standard input': stdin_init(ints) break else: print('Please enter "File" or "Standard input" to continue.') even_ints = [x for x in ints if x % 2 == 0] for i in range(len(ints)): if ints[i] % 2 == 0: ints[i] = None merge_sort(even_ints, 0, len(even_ints) - 1) j = 0 for i in range(len(ints)): if ints[i] is None: ints[i] = even_ints[j] j += 1 print(' '.join([str(x) for x in ints]))