This notebook was prepared by Donne Martin. Source and license info is on GitHub.

# Solution Notebook¶

## Constraints¶

• Can we assume this is a non-circular, singly linked list?
• Yes
• Do we expect the function to return a new list?
• Yes
• Can we assume the input x is valid?
• Yes
• Can we assume we already have a linked list class that can be used for this problem?
• Yes
• Can we create additional data structures?
• Yes
• Can we assume this fits in memory?
• Yes

## Test Cases¶

• Empty list -> []
• One element list -> [element]
• Left linked list is empty
• Right linked list is empty
• General case
• Partition = 10
• Input: 4, 3, 13, 8, 10, 1, 10, 12
• Output: 4, 3, 8, 1, 10, 10, 13, 12

## Algorithm¶

• Create left and right linked lists
• For each element in the list
• If elem < x, append to the left list
• else, append to the right list
• Merge left and right lists

Complexity:

• Time: O(n)
• Space: O(n)

## Code¶

In [1]:
%run ../linked_list/linked_list.py

In [2]:
class MyLinkedList(LinkedList):

def partition(self, data):
return

# Build the left and right lists
while curr is not None:
if curr.data < data:
left.append(curr.data)
elif curr.data == data:
right.insert_to_front(curr.data)
else:
right.append(curr.data)
curr = curr.next
if curr_left is None:
return right
else:
# Merge the two lists
while curr_left.next is not None:
curr_left = curr_left.next
return left


## Unit Test¶

In [3]:
%%writefile test_partition.py
import unittest

class TestPartition(unittest.TestCase):

def test_partition(self):
print('Test: Empty list')

print('Test: One element list, left list empty')

print('Test: Right list is empty')

print('Test: General case')
# Partition = 10
# Input: 4, 3, 13, 8, 10, 1, 14, 10, 12
# Output: 4, 3, 8, 1, 10, 10, 13, 14, 12
self.assertEqual(partitioned_list.get_all_data(),
[4, 3, 8, 1, 10, 10, 13, 14, 12])

print('Success: test_partition')

def main():
test = TestPartition()
test.test_partition()

if __name__ == '__main__':
main()

Overwriting test_partition.py

In [4]:
run -i test_partition.py

Test: Empty list
Test: One element list, left list empty
Test: Right list is empty
Test: General case
Success: test_partition