class Solution:
# @param n, an integer
# @return a string
def countAndSay(self, n):
def f(string):
a = []
count_1 = 1
count_2 = 1
s = string[1:] + 'e' #calculate i from string[1](this is to disregard the case of string[0]), meanwhile add 'e' to notify the end of the string
for i, j in enumerate(s):
if j == '1':
if string[i] == '1': #check whether the last member in string is the same as j
count_1 += 1 #if so, count_1 add 1, save for further list appending
else:
count_1 = 1 #reset the count if last character does not match with j
a.append[(str(count_2) + '2')]
if j == '2':
if string[i] == '2':
count_2 += 1
else:
count_2 = 1
a.append[(str(count_1) + '1')]
if j == 'e': #j=='e' if the iteration reach the end, and it is the right time for adding the final member of the expected list
if string[i] == '1':
a.append[(str(count_1) + '1')]
if string[i] == '2':
a.append[(str(count_2) + '2')]
return ''.join(list)
def seq(n):
if n == 1:
return '1'
if n == 2:
return '11'
if n == 3:
return '21'
else:
return f(seq(n-1))
return seq(n)
这是来自leetcode的问题的解决方案: https://leetcode.com/problems/count-and-say/
它通知我:
运行时错误消息:第17行:TypeError: 'builtin_function_or_method'对象没有属性' getitem '
上次执行的输入:4
第17行如下:
a.append[(str(count_2) + '2')]
请,我是一个完全新手,不知道如何解决这个问题。 另外,我希望你也改进我的代码。非常感谢你。
答案 0 :(得分:1)
嗯,显然,第17行看起来应该是
a.append(str(count_2) + '2')
当您使用方括号(a.append[key]
)时,Python会尝试在__getitem__
上调用a.append
方法