[英]How to create a recursive function that returns a copy of a single parameter (a list of strings), but with every character duplicated in each place?
Basically, I need to write a recursive function that takes a list of strings and then returns a list of strings with each character in each string repeated/doubled. 基本上,我需要编写一个递归函数,该函数需要一个字符串列表,然后返回一个字符串列表,每个字符串中的每个字符都重复/加倍。
For example, doubleStringList(['I','love','overflow']) would return ['II','lloovvee','oovveerrffllooww']. 例如,doubleStringList(['I','love','overflow'])将返回['II','lloovvee','oovveerrffllooww']。
I decided to split it up into two recursive functions. 我决定将其分为两个递归函数。 I already made one function that returns the strings with doubled characters:
我已经做了一个函数,该函数返回带有双倍字符的字符串:
def doubleCharacter(seq):
if len(seq) == 0:
return seq
else:
return (seq[0] * 2) + doubleCharacter(seq[1:])
For example, entering doubleCharacter("overflow") would return 'oovveerrffllooww' 例如,输入doubleCharacter(“ overflow”)将返回'oovveerrffllooww'
I'm trying to create a second recursive function that uses the first except for a list of strings as the paremeter rather than a single string. 我正在尝试创建第二个递归函数,该函数使用第一个递归函数,但将字符串列表作为参数而不是单个字符串。 For example:
例如:
def doubleStringList(sList):
if len(sList) == 0:
return sList
else:
return doubleCharacter(sList[0]) + doubleStringList(sList[1:])
Theoretically, if I entered doubleStringList(["overflow","is","great"]), it should return ["oovveerrffllooww", "iiss", "ggrreeaatt"]. 从理论上讲,如果我输入doubleStringList([“ overflow”,“ is”,“ great”]),它应该返回[“ oovveerrffllooww”,“ iiss”,“ ggrreeaatt”]。 If someone could please help me figure out this code, I would appreciate it greatly.
如果有人可以帮助我找出该代码,我将不胜感激。
The error message gives a big clue: 错误消息提供了一个重要线索:
TypeError: can only concatenate str (not "list") to str
So, the last line should be 所以,最后一行应该是
return [doubleCharacter(sList[0])] + doubleStringList(sList[1:])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.