Python作业在线等

[复制链接]
查看11 | 回复1 | 2010-10-26 10:27:18 | 显示全部楼层 |阅读模式
def insert_all(word, letter):

"""

Computes all words that can be formed from word simply by inserting

letter into all positions in word

word -- string

return list

"""

result = ""

index = 0

x = index + 1


while 0index:

result += word[:index] + letter + word[x:]

index += 1

return result
assertEqual(set(insert_all("","a")), set(["a"]))
assertEqual(set(insert_all("a","b")), set(["ab","ba"]))
assertEqual(set(insert_all("ab","c")), set(["abc","acb","cab"]))
运行后它说Traceback (most recent call last):
File "C:\Python26\SAVES\lab6.py", line 198, in

assertEqual(set(insert_all("a","b")), set(["ab","ba"]))
File "C:\Python26\SAVES\lab6.py", line 186, in insert_all

result += word[:index], letter
TypeError: cannot concatenate 'str' and 'tuple' objects
求跟正

回复

使用道具 举报

千问 | 2010-10-26 10:27:18 | 显示全部楼层
你的应该result += word[:index], letter改为result += word[:index]+ letter另附改良版:def insert_all(word, letter):
if len(word)==0:
print "The word is empty!"
return
words=[]
for i in range(len(word)+1):
new_word=word[:i]+letter+word[i:]
words.append(new_word)
return words
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行