好的,我意识到这已经被遗忘了,但我已经开始研究我的了,所以就这样吧。
注意:此实现将始终首先打印较短的字符串,如果您想始终从打印string1 的第一个字符开始,请参阅下面的更新。
我喜欢你复制输入参数,因为这是保留输入的好习惯,我只是稍微修改了它以添加一个约定,所以len(x) <= len(y) 总是正确的。我还选择不使用其他库,而是自己实现zip。
def extendedString(string1, string2):
if len(string1) <= len(string2): # Convention: len(x) <= len(y)
x = string1
y = string2
else:
x = string2
y = string1
z=""
for i in range(len(x)): # Go through shorter string
z+=x[i] # Add the i-th char in x to z
z+=y[i] # Add the i-th char in y to z
if i < len(y): # If the second string is longer
for j in range(i+1, len(y)): # for the rest of the length
z+=x[i] # add the last char of x to z
z+=y[j] # add the j-th char of y to z
return z
print(extendedString("abc", "efg"))
print(extendedString("ab", "defg"))
print(extendedString("abcd", "ef"))
输出:
$ python zip.py
aebfcg
adbebfbg
eafbfcfd
更新
此实现将确保始终首先打印string1。
def extendedString(string1, string2):
x = string1
y = string2
z=""
if len(x) <= len(y):
shorter = x
longer = y
else:
shorter = y
longer = x
for i in range(len(shorter)):
z+=x[i]
z+=y[i]
if i < len(longer):
for j in range(i+1, len(longer)):
if shorter == x:
z+=x[i]
z+=y[j]
else:
z+=x[j]
z+=y[i]
return z
print(extendedString("abc", "efg"))
print(extendedString("ab", "defg"))
print(extendedString("abcd", "ef"))
输出:
$ python zip.py
aebfcg
adbebfbg
aebfcfdf