【发布时间】:2016-02-19 14:16:43
【问题描述】:
编写一个名为symmetry 的函数,它接受一个字符串文本作为参数 并返回字典 d。文本中某个单词的第一个和最后一个字母的每个字母都应该是 d 中的一个键。例如,如果文本包含单词“shucks”,则“s”应该是 d 中的键。 d 中 's' 的值是以 's' 开头和结尾的单词的数量。参数文本只包含大小写字符和空格。
以下是正确输出的示例:
t = '''The sun did not shine
it was too wet to play
so we sat in the house
all that cold cold wet day
I sat there with Sally
we sat there we two
and I said how I wish
we had something to do'''
print(symmetry(t))
{'d': 1, 'i': 3, 't': 1}
我已经多次尝试得到这个问题的答案,但我似乎无法得到答案。使用我的代码,每个字母都被放入字典中,而不仅仅是单词开头和结尾的字母。你能帮我更好地理解这一点吗?
这是我目前的代码:
def symmetry(text):
d = {}
text.split()
for word in text:
if word[0] == word[-1]:
d[word[0]] =+ 1
else:
return word
return d
text = ''' The sun did not shine
it was too wet to play
so we sat in the house
all that cold cold wet day
I sat there with Sally
we sat there we two
and I said how I wish
we had something to do'''
print(symmetry(text))
【问题讨论】:
-
d[word[0]] =+ 1-=+不是运算符。它被解释为= +1,或者实际上只是= 1。我猜这不是本意?
标签: python dictionary python-3.4