You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写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

  1. Loop Through Half the List: We only need to iterate up to Size//2 because swapping the first half with the second half covers all symmetric pairs.
  2. Symmetric Index Calculation: For each index i, the corresponding pair is at Size - 1 - i (e.g., for a 7-element list, i=0 pairs with 6, i=1 pairs with 5, i=2 pairs with 3).
  3. Odd Check: The condition List[i] % 2 !=0 or List[other_idx]%2 !=0 ensures we only swap if at least one element is odd.
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:48:13