借助迭代理解递归

2024-06-08 22:36:14 发布

您现在位置:Python中文网/ 问答频道 /正文

  def unZip(master3):    
       c = len(master3)
       sub1=''
       sub2=''
       for i in range(0,c,2):
           sub1+=master3[i]
           sub2+=master3[i+1]
       print(sub1,",",sub2)

基本上,我写了一段代码,将可选字符和字符串分开,分别显示

我一直试图用递归来转换或理解这一点,但最近一直失败。你知道吗

这是我的尝试,有人能告诉我该怎么做吗?你知道吗

def unzip(a):
    storage1=''
    storage2=''
    storage3=''
    storage4=''
    if len(a)==0:
        return 0
    else:
        if len(a)>=1:
            storage1=a[0::2]
            storage2=a[1::2]
            storage3+=storage1
            storage4+=storage2
            print(storage3,storage4)
            return unzip(a[0]+a[1:])


Tags: forlenreturnifdefprintunzipstorage2
1条回答
网友
1楼 · 发布于 2024-06-08 22:36:14

与其使用切片来确定字符串,不如一次从字符串中提取一个字符,然后像这样调用递归函数

def unzip(s, a, b='', c=''):
    if len(a) == 0:
        return b + ', ' + c
    if s%2 == 0:
        b += a[0]
    else:
        c += a[0]
    return unzip(s+1, a[1:], b, c)

print unzip(0, 'HelloWorld')

Hlool, elWrd

它从字符串a开始,根据变量s是偶数还是奇数,交替添加到bc。将a的第一个字母添加到bc中,然后从a中删除该字母。然后再次调用函数,但使用s+1。如果a的长度为零,则返回bc,然后打印结果

为了得到与你所拥有的相同的结果,你可以把你的简化为

a = 'HelloWorld'
storage1=a[0::2]
storage2=a[1::2]

print(storage1,storage2)

('Hlool', 'elWrd')

切片负责获取a中的每一个字母,然后您就可以打印它了。你现在设置它的方式就是不断地传递a,变成一个无限循环,因为a的大小永远不会改变。你知道吗

相关问题 更多 >