我2-3个小时前去考试了。我们的老师要求我们:
1)从用户那里获取一个字符串句子。
2)将字符串发送给函数。
3)我们的任务是删除空格,但我们不能使用字符串函数,我们必须使用递归。
怎么了?
def deletespace(name):
if(len(name)==0):
return ""
else:
str=""
if(ord[name[0]])>chr(65) and ord(name[0])<chr(122):
return str+deletespace(name[1:])
name=input("Please enter the name..")
deletespace(name)发布于 2015-04-15 01:14:04
缺少第二个if的else子句。在这种情况下,您返回什么?
发布于 2015-04-15 01:23:08
测试可能已经结束,但您仍然可以从以下示例中学到一些东西:
>>> def del_char(text, char=' '):
head, *tail = text
return ('' if head == char else head) + \
(del_char(tail, char) if tail else '')
>>> def main():
name = input('Please enter your name: ')
spaceless = del_char(name)
print(spaceless)
>>> main()
Please enter your name: Arda Zaman
ArdaZaman
>>> 如果您想要一个功能更强大的del_char函数版本,请尝试使用这个str_replace函数,它可以做与第一个函数相同的事情,但具有扩展的功能:
def str_replace(string, old=' ', new='', count=0):
head, tail = string[0], string[1:]
if head == old:
head, count = new, count - 1
if not count:
return head + tail
return head + str_replace(tail, old, new, count) if tail else head发布于 2015-04-15 01:26:57
我发现有两个问题:
1)。在第6行,您试图访问ord的索引if(ord[name[0]])>chr(65) and ord(name[0])<chr(122):,这会抛出一个语法错误。您可能指的是if ord(name[0])>chr(65) and ord(name[0])<chr(122):
2)。缺少第二个if的else外壳。
https://stackoverflow.com/questions/29633424
复制相似问题