Python Practice Problems

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Without recursion, traverse a binary tree in Preorder.

# A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # An iterative process to print preorder traveral of BT def iterativePreorder(root): # Base CAse if root is None: return # create an empty stack and push root to it nodeStack = [] nodeStack.append(root) # Pop all items one by one. Do following for every popped item # a) print it # b) push its right child # c) push its left child # Note that right child is pushed first so that left # is processed first */ while(len(nodeStack) > 0): # Pop the top item from stack and print it node = nodeStack.pop() print (node.data, end=" ") # Push right and left children of the popped node # to stack if node.right is not None: nodeStack.append(node.right) if node.left is not None: nodeStack.append(node.left) # Driver program to test above function root = Node(10) root.left = Node(8) root.right = Node(2) root.left.left = Node(3) root.left.right = Node(5) root.right.left = Node(2) iterativePreorder(root)

Implement a bubble sort algorithm.

# Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n-1): # range(n) also work but outer loop will repeat one time more than needed. # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Driver code to test above arr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) print ("Sorted array is:") for i in range(len(arr)): print ("%d" %arr[i]),

Traverse a binary tree in preorder

For traversing a (non-empty) binary tree in a preorder fashion, we must do these three things for every node n starting from the tree's root: (N) Process n itself. (L) Recursively traverse its left subtree. When this step is finished, we are back at n again. (R) Recursively traverse its right subtree. When this step is finished, we are back at n again. # Data structure to store a binary tree node class Node: def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right # Recursive function to perform preorder traversal on the tree def preorder(root): # return if the current node is empty if root is None: return # Display the data part of the root (or current node) print(root.data, end=' ') # Traverse the left subtree preorder(root.left) # Traverse the right subtree preorder(root.right) if __name__ == '__main__': """ Construct the following tree 1 / \ / \ 2 3 / / \ / / \ 4 5 6 / \ / \ 7 8 """ root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.right.left = Node(5) root.right.right = Node(6) root.right.left.left = Node(7) root.right.left.right = Node(8) preorder(root)

Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. Example 4: Input: s = "" Output: 0 Constraints: 0 <= s.length <= 5 * 104 s consists of English letters, digits, symbols and spaces.

Intuition Check all the substring one by one to see if it has no duplicate character. Algorithm Suppose we have a function boolean allUnique(String substring) which will return true if the characters in the substring are all unique, otherwise false. We can iterate through all the possible substrings of the given string s and call the function allUnique. If it turns out to be true, then we update our answer of the maximum length of substring without duplicate characters. —————————————————————————————- class Solution: def lengthOfLongestSubstring(self, s: str) -> int: def check(start, end): chars = [0] * 128 for i in range(start, end + 1): c = s[i] chars[ord(c)] += 1 if chars[ord(c)] > 1: return False return True n = len(s) res = 0 for i in range(n): for j in range(i, n): if check(i, j): res = max(res, j - i + 1) return res

Write a code to perform the inversion count of an array.

Inversion Count for an array indicates - how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j # Python3 program to count # inversions in an array def getInvCount(arr, n): inv_count = 0 for i in range(n): for j in range(i + 1, n): if (arr[i] > arr[j]): inv_count += 1 return inv_count # Driver Code arr = [1, 20, 6, 4, 5] n = len(arr) print("Number of inversions are", getInvCount(arr, n))

UnNest a nested list [[[1,2],3],[4,5,6]] In to [1,2,3,4,5,6]

MyList = [[[1,2],3],[4,5,6]] def travList(a, tType=(list)): if isInstance (a, tType): for value in a: for subvalue in travList(value, tType): yield subvalue else: yield a Print(list(travList(MyList)))

How do you reverse through a list?

a = [1, 2, 3, 4, 5] for x in reversed(a): print(x) OR a = [1, 2, 3, 4, 5] for x in a[::-1]: print(x)

Find Minimum in Rotated Sorted Array

class Solution(object): def findMin(self, nums): """ :type nums: List[int] :rtype: int """ # If the list has just one element then return that element. if len(nums) == 1: return nums[0] # left pointer left = 0 # right pointer right = len(nums) - 1 # if the last element is greater than the first element then there is no rotation. # e.g. 1 < 2 < 3 < 4 < 5 < 7. Already sorted array. # Hence the smallest element is first element. A[0] if nums[right] > nums[0]: return nums[0] # Binary search way while right >= left: # Find the mid element mid = left + (right - left) / 2 # if the mid element is greater than its next element then mid+1 element is the smallest # This point would be the point of change. From higher to lower value. if nums[mid] > nums[mid + 1]: return nums[mid + 1] # if the mid element is lesser than its previous element then mid element is the smallest if nums[mid - 1] > nums[mid]: return nums[mid] # if the mid elements value is greater than the 0th element this means # the least value is still somewhere to the right as we are still dealing with elements greater than nums[0] if nums[mid] > nums[0]: left = mid + 1 # if nums[0] is greater than the mid value then this means the smallest value is somewhere to the left else: right = mid - 1

Find the pivot index Given an array of integers nums, calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. Return the leftmost pivot index. If no such index exists, return -1.

class Solution(object): def pivotIndex(self, nums): S = sum(nums) leftsum = 0 for i, x in enumerate(nums): if leftsum == (S - leftsum - x): return i leftsum += x return -1

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. Example 1: Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,3,4,4] Example 2: Input: l1 = [], l2 = [] Output: [] Example 3: Input: l1 = [], l2 = [0] Output: [0] Constraints: The number of nodes in both lists is in the range [0, 50]. -100 <= Node.val <= 100 Both l1 and l2 are sorted in non-decreasing order.

class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 if l1.val > l2.val: #if l1 value > l2 value, then we swap them l1, l2 = l2, l1 l1.next = self.mergeTwoLists(l1.next, l2) return l1

Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]

class Solution: def rotate(self, nums: List[int], k: int) -> None: n = len(nums) a = [0] * n for i in range(n): a[(i + k) % n] = nums[i] nums[:] = a

Determine all the matching integers in two lists using bigO(a,b)

def lister2(lista, listb): p1 = 0 p2 = 0 newlist =[] while p1 < len(lista) and p2 < len(listb): if lista[p1] == listb[p2]: newlist.append(lista[p1]) p1 += 1 p2 += 1 elif lista[p1] > listb[p2]: p2 += 1 else: p1 += 1 return newlist list1 = [1,2,3,5,6,9] list2 = [1,5,7,8,9] print(lister2(list1,list2))

Given a string, find the first non-repeating character in it and return its index. # If it doesn't exist, return -1. # Note: all the input strings are already lowercase.

def solution(s): # build hash map : char and how often it appears count = collections.Counter(s) # <-- gives back a dictionary with words occurrence count #Counter({'l': 1, 'e': 3, 't': 1, 'c': 1, 'o': 1, 'd': 1}) # find the index for idx, ch in enumerate(s): if count[ch] == 1: return idx return -1 print(solution('alphabet')) print(solution('barbados')) print(solution('crunchy'))

Two Sum

def twoSum(nums, target): required = {} for i in range(len(nums)): if target - nums[i] in required: return [required[target - nums[i]],i] else: required[nums[i]]=i input_list = [2,8,12,15] print(twoSum(input_list, 20))

# Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. # The string will only contain lowercase characters a-z.

s = 'radkar' def solution(s): for i in range(len(s)): t = s[:i] + s[i+1:] if t == t[::-1]: return True return s == s[::-1] solution(s)


Set pelajaran terkait

Engineering Materials exam 1 (FAU) 9/27/18 morano

View Set

Chapter 2: Collecting Subjective Data: The Interview & Health Hx

View Set