0% found this document useful (0 votes)
14 views

Cheat Sheet For Python

The document discusses various algorithms and data structures including converting between linked lists and lists, lists and strings, recursion, backtracking, binary tree traversal, and finding the kth smallest element in a binary search tree.

Uploaded by

albusfons939393
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Cheat Sheet For Python

The document discusses various algorithms and data structures including converting between linked lists and lists, lists and strings, recursion, backtracking, binary tree traversal, and finding the kth smallest element in a binary search tree.

Uploaded by

albusfons939393
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

Convert linked lists to lists:

class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def convertLinkedListToList(self, head: ListNode) ->
list:
result = []
current = head
while current:
result.append(current.val)
current = current.next
return result

2. Convert lists to linked lists:

class Solution:
def convertListToLinkedList(self, lst: list) -> ListNode:
# Initialize a dummy node to simplify the code
dummy = ListNode()
current = dummy
# Iterate through the list and create linked list nodes
for val in lst:
current.next = ListNode(val)
current = current.next
# Return the head of the linked list (skip the dummy
node)
return dummy.next

3. Convert lists to strings:


num1 = int(''.join(str(x) for x in list1))
4. Convert list of strings to list of integers:
lis = [``'1'``, '-4'``, '3'``, '-6'``, '7'``]
res = [``eval``(i) for i in lis]
5. Reverse strings and lists:
result.reverse()
6. Find frequency of item in a list:
def k_most_frequent_elements(nums, k):
# Create a dictionary to store the frequency of each element
frequency_dict = {}
# Count the frequency of each element
for num in nums:
if num in frequency_dict:
frequency_dict[num] += 1
else:
frequency_dict[num] = 1

7. Recursion:

class Solution:
def isHappy(self, n: int) -> bool:
def calculate_square_sum(number):
square_sum = 0
while number > 0:
digit = number % 10
square_sum += digit ** 2
number //= 10
return square_sum
seen = set()
while n != 1:
n = calculate_square_sum(n) #Recursion
if n in seen:
return False # Cycle detected, not a happy number
seen.add(n)
return True

8. Backtracking:

class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def backtrack(s, left, right):
if len(s) == 2 * n:
result.append(s)
return
if left < n:
backtrack(s + '(', left + 1, right)
if right < left:
backtrack(s + ')', left, right + 1)
result = []
backtrack('', 0, 0)
return result

9. In-order Traversal of Binary Tree


The nodes are visited in the following order:
10. Visit the left subtree.
11. Visit the current node (the root of the subtree being traversed).
12. Visit the right subtree.

Here's a step-by-step explanation of how in-order traversal works:

1. Start at the root node of the binary tree.


2. Recursively traverse the left subtree (if it exists) by applying the in-order traversal to the
left child node.
3. Visit the current node.
4. Recursively traverse the right subtree (if it exists) by applying the in-order traversal to
the right child node.

class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
result = []
if root is None:
return []
if root is not None:
result += self.inorderTraversal(root.left)
result.append(root.val)
result += self.inorderTraversal(root.right)
return result

The method should be called on self to access itself recursively.

10. K-th Smallest/Largest in a BST

class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
node = stack.pop()
if node is not None:
k-=1
if k == 0:
return node.val
else:
k+=1
root = node.right

You might also like