我被要求創建一個程序,我已完成後,我做的是一個遞歸版本。 它的意義不大,它的鞋帶串起來。這裏是它的版本是我寫的,誰能告訴我如何做一個遞歸程序出來呢?遞歸編程殘端?
def laceStrings(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
"""
join = []
smaller = min(s1, s2, key=len)
for num in range(len(smaller)):
join.append(s1[num])
join.append(s2[num])
join = ''.join(join)
if len(s1) != len(s2):
smaller = len(smaller)
join = join + max(s1, s2, key=len)[smaller:]
return join
編輯:我的朋友給了我這個模板,但我仍然無法弄清楚。誰能幫忙?
def laceStringsRecur(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
"""
def helpLaceStrings(s1, s2, out):
if s1 == '':
#PLACE A LINE OF CODE HERE
if s2 == '':
#PLACE A LINE OF CODE HERE
else:
#PLACE A LINE OF CODE HERE
return helpLaceStrings(s1, s2, '')
我認爲這是一個完全可以接受的問題。 thg435的回答顯示它相當有責任感。投票重新開放。 –