Issue
def len_link(lst):
"""Returns the length of the link.
>>> lst = link(1, link(2, link(3, link(4))))
>>> len_link(lst)
4
>>> len_link(empty)
0
"""
Hi I'm having a hard time understanding how to find the length of a linked list if someone could help I would really appreciate it.
Solution
As stated in "Functional linked lists in Python":
The length operation returns the number of elements in a given list. To find the length of a list we need to scan all of its n elements. Therefore this operation has a time complexity of O(n).
def length(xs): if is_empty(xs): return 0 else: return 1 + length(tail(xs)) assert length(lst(1, 2, 3, 4)) == 4 assert length(Nil) == 0
head and tail are respectively:
def head(xs): return xs[0] assert head(lst(1, 2, 3)) == 1 def tail(xs): return xs[1] assert tail(lst(1, 2, 3, 4)) == lst(2, 3, 4)
Answered By - Abhishek Dey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.