find the variance of all nodes in a linked list in python

To find the variance of all nodes in a linked list, we can follow these steps:

  1. Traverse the linked list and store all the values in a list or array.
  2. Import the statistics module in Python to calculate the variance.
  3. Calculate the variance using the variance() function from the statistics module.

Here's the implementation:

main.py
import statistics

# Define a Node class for the linked list
class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None

# Define a LinkedList class
class LinkedList:
    def __init__(self):
        self.head = None

    # Method to add new node at the end of the linked list
    def append(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
            return
        last_node = self.head
        while last_node.next:
            last_node = last_node.next
        last_node.next = new_node

    # Method to calculate the variance of all nodes in the linked list
    def variance(self):
        data = []
        curr_node = self.head
        while curr_node:
            data.append(curr_node.data)
            curr_node = curr_node.next
        return statistics.variance(data)

# Create a linked list and append some data
llist = LinkedList()
llist.append(10)
llist.append(20)
llist.append(30)
llist.append(40)
llist.append(50)

# Calculate the variance of the linked list and print the result
print("Variance of all nodes in the linked list:", llist.variance())
1162 chars
44 lines

Output:

main.py
Variance of all nodes in the linked list: 250.0
48 chars
2 lines

Note: We can also calculate the variance using the math module by implementing the formula for variance. However, using statistics module makes it easier and more efficient.

gistlibby LogSnag