While studying linked lists from – https://composingprograms.com/pages/23-sequences.html#linked-lists
JavaScript
x
11
11
1
empty ='empty'
2
four = [1, [2, [3, [4, 'empty']]]]
3
x = [1,2];
4
5
def is_link(s):
6
"""s is a linked list if it is empty or a (first, rest) pair."""
7
return s == empty or (len(s) == 2 and is_link(s[1]))
8
9
print(is_link(four))
10
print(is_link(x))
11
The program recognizes four as a linked list, But when i plug in x it returns an error instead of returning “False”.
If i change value of x to just [1] or [1,2,3] it returns as expected, but if i enter a normal list [1,2] with 2 values i run into this error. .Why is this?
Advertisement
Answer
Look at the executions, on your condition len(s) == 2
this only satisfies [1, 2]
so it checks for the next one is_link(s[1])
which raises an error because it’s a check length of integer in next iteration.
JavaScript
1
28
28
1
In [24]: print(is_link([1]))
2
[1]
3
False
4
5
In [25]: print(is_link([1, 2, 3]))
6
[1, 2, 3]
7
False
8
9
In [26]: print(is_link([1, 2]))
10
[1, 2]
11
2
12
---------------------------------------------------------------------------
13
TypeError Traceback (most recent call last)
14
Input In [26], in <module>
15
----> 1 print(is_link([1, 2]))
16
17
Input In [20], in is_link(s)
18
2 print(s)
19
3 """s is a linked list if it is empty or a (first, rest) pair."""
20
----> 4 return s == empty or (len(s) == 2 and is_link(s[1]))
21
22
Input In [20], in is_link(s)
23
2 print(s)
24
3 """s is a linked list if it is empty or a (first, rest) pair."""
25
----> 4 return s == empty or (len(s) == 2 and is_link(s[1]))
26
27
TypeError: object of type 'int' has no len()
28