Linked Lists - Length & Count

Implement Length() to count the number of nodes in a linked list.
Implement Count() to count the occurrences of an integer in a linked list.


I've decided to bundle these two functions within the same Kata since they are both very similar.

The `push()`/`Push()` and `buildOneTwoThree()`/`BuildOneTwoThree()` functions do not need to be redefined.

Source: codewars | Difficulty: EASY
Tags: Fundamentals

Data structures

Starter code: def __init__(self, data):
	

Solutions:
class Node(object):

	def __init__(self, data):
		self.data = data
		self.next = None

def length(node):
	leng = 0
	while node:
		leng += 1
		node = node.next
	return leng

def count(node, data):
	c = 0
	while node:
		if node.data == data:
			c += 1
		node = node.next
	return c


class Node(object):

	def __init__(self, data):
		self.data = data
		self.next = None

def length(node):
	if node:
		return 1 + length(node.next)
	return 0

def count(node, data):
	if node:
		if node.data == data:
			return 1 + count(node.next, data)
		return count(node.next, data)
	return 0


class Node(object):

	def __init__(self, data):
		self.data = data
		self.next = None

def count_if(node, fn):
	(n, c) = (node, 0)
	while n:
		if fn(n):
			c += 1
		n = n.next
	return c

def length(node):
	return count_if(node, lambda x: x != None)

def count(node, data):
	return count_if(node, lambda x: x.data == data)


class Node(object):

	def __init__(self, data):
		self.data = data
		self.next = None

def length(node):
	n = node
	len = 0
	while n is not None:
		len += 1
		n = n.next
	return len

def count(node, data):
	n = node
	count = 0
	while n is not None:
		if data == n.data:
			count += 1
		n = n.next
	return count


class Node(object):

	def __init__(self, data):
		self.data = data
		self.next = None

def iterlinkedlist(node):
	while node:
		yield node
		node = node.next

def length(node):
	return sum((1 for n in iterlinkedlist(node)))

def count(node, data):
	return sum((n.data == data for n in iterlinkedlist(node)))


class Node(object):

	def __init__(self, data):
		self.data = data
		self.next = None

def length(node):
	i = 0
	while node != None:
		i += 1
		node = node.next
	return i

def count(node, data):
	res = 0
	while node != None:
		res += node.data == data
		node = node.next
	return res


class Node(object):

	def __init__(self, data):
		self.data = data
		self.next = None

def length(node, filter=None):
	l = 0
	while node != None:
		(node, l) = (node.next, l + (filter is None or filter == node.data))
	return l

def count(node, data):
	return length(node, data)