编写Array_Swap函数实现整数列表中对应位置元素的奇偶条件交换
Python: Implement Array Swap with Odd Element Condition
Let's work through this problem to get the desired behavior. First, let's restate the requirements clearly to make sure we're on the same page:
Requirements
- Define a function
Array_Swap(List, Size)that takes an integer list and its length as parameters - Swap elements symmetrically: first ↔ last, second ↔ second-last, etc.
- Only perform the swap if at least one of the two elements is odd
- Print the modified list after all valid swaps
- Example: Input list
[5, 16, 4, 7, 19, 8, 2]should become[2, 16, 19, 7, 4, 8, 5]
Issues with the Original Code
The provided code doesn't implement the swap logic correctly — it's just assigning values from the middle of the list to the front, and there's no check for odd elements. Let's fix that.
Corrected Code
def Array_Swap(List, Size): # Iterate through the first half of the list for i in range(Size // 2): # Get the symmetric index from the end other_idx = Size - 1 - i # Check if at least one element is odd if List[i] % 2 != 0 or List[other_idx] % 2 != 0: # Perform the swap (Python's tuple unpacking makes this clean) List[i], List[other_idx] = List[other_idx], List[i] # Print the modified list print("交换后的列表:", List) # Get user input L = [] n = int(input("请输入元素个数: ")) for i in range(n): x = int(input(f"请输入第{i+1}个元素: ")) L.append(x) # Call the function Array_Swap(L, len(L))
How It Works
- Loop Through Half the List: We only need to iterate up to
Size//2because swapping the first half with the second half covers all symmetric pairs. - Symmetric Index Calculation: For each index
i, the corresponding pair is atSize - 1 - i(e.g., for a 7-element list, i=0 pairs with 6, i=1 pairs with 5, i=2 pairs with 3). - Odd Check: The condition
List[i] % 2 !=0 or List[other_idx]%2 !=0ensures we only swap if at least one element is odd. - Swap Operation: Python's tuple unpacking (
a, b = b, a) is a concise way to swap two elements without needing a temporary variable.
Test the Example
If we input the sample list [5,16,4,7,19,8,2]:
- i=0: 5 (odd) and 2 (even) → swap → list becomes
[2,16,4,7,19,8,5] - i=1:16 (even) and8 (even) → no swap
- i=2:4 (even) and19 (odd) → swap → list becomes
[2,16,19,7,4,8,5] - i=3: We stop here since 7//2=3, range(3) is 0,1,2.
Which matches the expected output perfectly!
内容的提问来源于stack exchange,提问作者recklessdude777
相关产品推荐
相关产品推荐

