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

递归函数swap输出不符合需求,需实现每两个字符反转输出

Fixing the String Pair Reversal with Recursion

Got it, let's break down why your current code isn't working and fix it step by step:

  • Your input is a nested list [["abcdefgh"]], so when your original swap function accesses aList[0], it's grabbing the inner list ["abcdefgh"]—not the actual string you need to manipulate.
  • The original function’s logic is built for summing list elements, not reversing pairs of characters in a string. That’s why you’re just getting the original string printed out instead of the desired reversed-pair result.

Solution 1: Simplest Direct String Handling

We’ll rewrite the swap function to target string character pairs directly, then extract the inner string from your nested list before passing it in:

def swap(s):
    # Base case 1: empty string, return nothing
    if len(s) == 0:
        return ""
    # Base case 2: single character, no reversal needed
    elif len(s) == 1:
        return s
    # Reverse the first two characters, then recurse on the rest of the string
    return s[1] + s[0] + swap(s[2:])

# Extract the inner string from your nested list input
aList = [["abcdefgh"]]
result = swap(aList[0][0])
print(result)  # Output: badcfehg

Solution 2: Auto-Handle Nested Lists

If you want the function to accept the original nested list directly without manual extraction, add a check to dig down to the inner string first:

def swap(input_data):
    # If input is a list, recursively grab the inner element until we get a string
    if isinstance(input_data, list):
        return swap(input_data[0])
    # Now we're working with the target string
    s = input_data
    if len(s) == 0:
        return ""
    elif len(s) == 1:
        return s
    # Swap first two chars + recurse on the remaining substring
    return s[1] + s[0] + swap(s[2:])

aList = [["abcdefgh"]]
result = swap(aList)
print(result)  # Output: badcfehg

How This Logic Works

  • For strings longer than 1 character, we take the second character first, then the first, then append the result of running the same function on the substring starting at index 2.
  • The base cases handle empty strings and single characters where no reversal is needed.
  • The nested list handling in Solution 2 makes the function more flexible for your specific input structure.

内容的提问来源于stack exchange,提问作者zach_93

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:26:32