在 python 中编写一个递归函数,复制字符串中的每个字符
Write a recursive function in python that duplicates each character in a string
例如,输入为 "abc",函数应为 return "aabbcc"。
我是递归函数的新手,对它们真的很困惑。
#iterate through x, store each value twice in y, print y joined by nothing
x = 'abc'
y=[i*2 for i in x]
print ''.join(y)
这里的 "bottom limit" 是当传入的字符串(或列表或元组......)为空时 - 在这种情况下你只是 return 它,这将结束递归:
def recdup(seq):
if not seq:
return seq
head, tail = seq[0:1], seq[1:]
return (head * 2) + recdup(tail)
例如,输入为 "abc",函数应为 return "aabbcc"。
我是递归函数的新手,对它们真的很困惑。
#iterate through x, store each value twice in y, print y joined by nothing
x = 'abc'
y=[i*2 for i in x]
print ''.join(y)
这里的 "bottom limit" 是当传入的字符串(或列表或元组......)为空时 - 在这种情况下你只是 return 它,这将结束递归:
def recdup(seq):
if not seq:
return seq
head, tail = seq[0:1], seq[1:]
return (head * 2) + recdup(tail)