Here is my code first:
res = []
for x in range(9):
if x == 0:
res.append([1])
elif x == 1:
res.append([1,1])
print(res)
else:
l=[]
for y in range(len(res[x-1])):
if y == 0:
l.append(1)
else:
l.append(res[x-1][y] + res[x-1][y-1])
l.append(1)
res.append(1)
and I meet the problem. Then I change a little bit of code like this:
res = [[1],[1,1]]
for i in range(2,9):
res.append([1])
for j in range(len(res[i-1])):
if j > 0:
res[i].append(int(res[i-1][j-1]+res[i-1][j]))
res[i].append(1)
print(res)
and the error has gone. I am quite wondering what is wrong inside?
Let's say you have my_var = 5
. By running len(my_var)
you will get an error, because variable my_var
is an int (short for an integer).
However, if you have my_var = [5]
, your command len(my_var)
will work because it is a list.
Similarly in your code, as khelwood says, if you have l.append(1)
, your variable l
will contain an integer 1. This will raise an error if you call len()
on this element. If you want to append something to a list then find its length later, make sure it is not an int but a list, try l append([1])
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.