Python: Start with a list of integers, keep every other element in place and otherwise sort the list
Python Programming Puzzles: Exercise-92 with Solution
Sort Keeping Every Other Element Fixed
Write a Python program to start with a list of integers, keep every other element in place and otherwise sort the list.
Input: [2, 5, 6, 3, 1, 4, 34] Output: [1, 5, 2, 3, 6, 4, 34] Input: [8, 0, 7, 2, 9, 4, 1, 2, 8, 3] Output: [1, 0, 7, 2, 8, 4, 8, 2, 9, 3]
Sample Solution:
Python Code:
# Define a function named 'test' that takes a list of numbers 'nums' as a parameter
def test(nums):
# Create a copy of the original list to avoid modifying the input list
li = nums.copy()
# Iterate through the elements of the list with even indices
for i in range(len(li)):
# Check if the current index is even
if i % 2 == 0:
# Iterate through the elements with even indices after the current index
for j in range(i + 2, len(li), 2):
# Check if the element at index 'j' is less than the element at index 'i'
if li[j] < li[i]:
# Call the 'swap' function to swap elements at indices 'i' and 'j'
swap(li, i, j)
# Return the modified list
return li
# Define a function named 'swap' that swaps elements at indices 'i' and 'j' in the given list 'li'
def swap(li, i, j):
# Temporary variable to store the value at index 'i'
temp = li[i]
# Swap the values at indices 'i' and 'j'
li[i] = li[j]
li[j] = temp
# Example 1
nums1 = [2, 5, 6, 3, 1, 4, 34]
print("Original list of numbers:")
print(nums1)
print("Keep every other element in place and otherwise sort the list:")
print(test(nums1))
# Example 2
nums2 = [8, 0, 7, 2, 9, 4, 1, 2, 8, 3]
print("\nOriginal list of numbers:")
print(nums2)
print("Keep every other element in place and otherwise sort the list:")
print(test(nums2))
Sample Output:
Original list (triple) of lists: [2, 5, 6, 3, 1, 4, 34] In the said list, keep every other element in place and otherwise sort the list.: [1, 5, 2, 3, 6, 4, 34] Original list (triple) of lists: [8, 0, 7, 2, 9, 4, 1, 2, 8, 3] In the said list, keep every other element in place and otherwise sort the list.: [1, 0, 7, 2, 8, 4, 8, 2, 9, 3]
Flowchart:
Python Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Find all n-digit integers that start or end with 2.
Next: Find the closest palindrome.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/puzzles/python-programming-puzzles-92.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics