繁体   English   中英

有人可以帮助我了解以下python程序吗?

[英]Can someone help me understand the following python program?

该函数在函数内部具有一个函数。 该程序创建一个包含所有可能的字符串组合的列表。 我在遵循内部函数时遇到麻烦,它是递归的。 有人可以帮帮我吗?

def combine0(s):
    out = []
    length = len(s)
    def loc(start):
        for i in range(start, length):
            out.append(s[i])
            print (''.join(out))
            if (i < length-1):
                loc(i+1)
            del out[-1]   
    loc(0)

combine0('mary')

产生

m
ma
mar
mary
may
mr
mry
my
a
ar
ary
ay
r
ry
y

是的,这是一个调用自身的函数,名称是递归调用 这里是这种代码的一些描述

更正后的代码将是:

def combine0(s):
    out = []
    length = len(s)
    def loc(start):
        for i in range(start, length):
            out.append(s[i])
            print (''.join(out))
            if (i < length-1):
                loc(i+1)
            del out[-1]
    loc(0)

combine0("abc")

和“ abc”的输出:

a ab abc ac b bc c

当使用参数'Mary'调用时, combine0

s = 'Mary'
out = []
length = len(s) # in this case length=4

# for i in range(0, 4):
# i = 0
out.append(s[0])    # s[0] = 'M', out = ['M']
print(''.join(out)) # print('M')
# if i < length - 1: => if 0 < 3:
# loc(i + 1) => loc(1)
# for j in range(1, 4):
# j = 1
out.append(s[1])    # s[1] = 'a', out = ['M', 'a']
print(''.join(out)) # print('Ma')
# if j < length - 1: => if 1 < 3:
# loc(j + 1) => loc(2)
# for k in range(2, 4):
# k = 2
out.append(s[2])    # s[2] = 'r', out = ['M', 'a', 'r']
print(''.join(out)) # print ('Mar')
# if k < length - 1: => if 2 < 3:
# loc(k + 1) => loc(3)
# for l in range(3, 4):
# l = 3
out.append(s[3])    # s[3] = 'y', out = ['M', 'a', 'r', 'y']
print(''.join(out)) # print('Mary')
# if l < length - 1: => if 3 < 3:
# condition fails -> do not recurse
del out[-1] # out = ['M', 'a', 'r']
# end of for l in range(3, 4)
del out[-1] # out = ['M', 'a']
# k = 3, now in for k in range(2, 4):
out.append(s[3])    # s[3] = 'y', out = ['M', 'a', 'y']
print(''.join(out)) # print('May')
# if k < length - 1: => if 3 < 3:
# condition fails -> do not recurse
del out[-1] # out = ['M', 'a']
# end of for k in range(2, 4)
del out[-1] # out = ['M']
# j = 2, now in for j in range (1, 4):
out.append(s[2])    # s[2] = 'r', out = ['M', 'r']
print(''.join(out)) # print('Mr')
# if j < length - 1: => if 2 < 3:
# loc(j + 1) => loc(3)
# for m in range(3, 4)
# m = 3
out.append(s[3])    # s[3] = 'y', out = ['M', 'r', 'y']
print(''.join(out)) # print('Mry')
# if m < length - 1: => if 3 < 3:
# condition fails -> do not recurse
del out[-1] # out = ['M', 'r']
# end of for m in range(3, 4)
del out[-1] # out = ['M']
# j = 3, now in for j in range (1, 4):
out.append(s[3])    # s[3] = 'y', out = ['M', 'y']
print(''.join(out)) # print('My')
# if j < length - 1: => if 3 < 3:
# condition fails -> do not recurse
del out[-1] # out = ['M']
# end of for j in range(1, 4)
del out[-1] # out = []
# i = 1

#... you get the rest

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM