Python Coding Challenges

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example: Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5

# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param num, a list of integers # @return a tree node # 12:37 def sortedArrayToBST(self, num): if not num: return None mid = len(num) // 2 root = TreeNode(num[mid]) root.left = self.sortedArrayToBST(num[:mid]) root.right = self.sortedArrayToBST(num[mid+1:]) return root

Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL

# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next Python: Iterative & Recursive class Solution(object): def reverseList(self, head): # Iterative prev, curr = None, head while curr: curr.next, prev, curr = prev, curr, curr.next return prev def reverseList_v1(self, head): # Recursive """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head p = self.reverseList(head.next) head.next.next = head head.next = None return p

Given the head of a linked list, remove the nth node from the end of the list and return its head. Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]

# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: ....def removeNthFromEnd(self, head, n): .... ....def index(node): .... .... ....if not node: .... .... .... ....return 0 .... .... ....i = index(node.next) + 1 .... .... ....if i > n: .... .... .... ....node.next.val = node.val .... .... ....return i .... ....index(head) .... ....return head.next

Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly. It is guaranteed that the node to be deleted is not a tail node in the list. Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = node.next.next

Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false. Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: if not head or not head.next: return False slow, fast = head, head.next while slow != fast: if not fast or not fast.next: return False slow, fast = slow.next, fast.next.next return True

This function, sum_digits(), produces the sum of all the digits in a positive number as if they were each a single number. Make this both iterative and recursive.

# Linear - O(N), where "N" is the number of digits in the number def sum_digits(n): if n < 0: ValueError("Inputs 0 or greater only!") result = 0 while n is not 0: result += n % 10 n = n // 10 return result + n #recursive def sum_digits(n): if n <= 9: return n last_digit = n % 10 return sum_digits(n // 10) + last_digit

Write an algorithm such that if an element in an MxN matrix is 0, the entire row and column are set to 0.

# O(MxN) import unittest def zero_matrix(matrix): m = len(matrix) n = len(matrix[0]) rows = [] cols = [] for x in range(m): for y in range(n): if matrix[x][y] == 0: rows.append(x) cols.append(y) for row in rows: nullify_row(matrix, row) for col in cols: nullify_col(matrix, col) return matrix def nullify_row(matrix, row): for i in range(len(matrix[0])): matrix[row][i] = 0 def nullify_col(matrix, col): for i in range(len(matrix)): matrix[i][col] = 0

Implement a string compression that counts repeated characters. For example, "aabccccaaa" becomes "a2b1c4a3". If the compressed string would not be shorter than the original, return the original.

# O(N) import unittest def string_compression(string): compressed = [] counter = 0 for i in range(len(string)): if i != 0 and string[i] != string[i - 1]: compressed.append(string[i - 1] + str(counter)) counter = 0 counter += 1 # add last repeated character compressed.append(string[-1] + str(counter)) # returns original string if compressed string isn't smaller return min(string, ''.join(compressed), key=len) class Test(unittest.TestCase): '''Test Cases''' data = [ ('aabcccccaaa', 'a2b1c5a3'), ('abcdef', 'abcdef') ] def test_string_compression(self): for [test_string, expected] in self.data: actual = string_compression(test_string) self.assertEqual(actual, expected) if __name__ == "__main__": unittest.main()

Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,3,4,4]

# iteratively def mergeTwoLists1(self, l1, l2): dummy = cur = ListNode(0) while l1 and l2: if l1.val < l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return dummy.next # recursively def mergeTwoLists2(self, l1, l2): if not l1 or not l2: return l1 or l2 if l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2 # in-place, iteratively def mergeTwoLists(self, l1, l2): if None in (l1, l2): return l1 or l2 dummy = cur = ListNode(0) dummy.next = l1 while l1 and l2: if l1.val < l2.val: l1 = l1.next else: nxt = cur.next cur.next = l2 tmp = l2.next l2.next = nxt l2 = tmp cur = cur.next cur.next = l1 or l2 return dummy.next

A robot is sitting on the upper left corner of a grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are off-limits. Design an algorithm to find a path for the robot from the top left to the bottom right.

#Solution with recursion O(2^r+c) def getPath(maze): if maze == None or len(maze) == 0: return None path = [] if isPath(maze, len(maze)-1, len(maze[0])-1, path): return path return None def isPath(maze, row, col, path): #if out of bounds or not available, return if col < 0 or row < 0 or not maze[row][col]: return False isAtOrigin = (row == 0) and (col == 0) #if there's a path from the start to here, add my location if isAtOrigin or isPath(maze, row, col-1, path) or isPath(maze, row-1, col,path): point = (row,col) path.append(point) return True

For our first problem, we would like to "rotate" a list, or move elements forward in a list by a number of spaces, k. Elements at the greatest index will "wrap around" to the beginning of the list. list = ['a', 'b', 'c', 'd', 'e', 'f'] rotate(list, 0) # ['a', 'b', 'c', 'd', 'e', 'f'] rotate(list, 1) # ['f', 'a', 'b', 'c', 'd', 'e'] rotate(list, 3) # ['d', 'e', 'f', 'a', 'b', 'c']

#my solution! :-) def rotate(my_list, num_rotations): if num_rotations == 0: return my_list while num_rotations > 0: x = my_list.pop() my_list.insert(0,x) num_rotations -= 1 return my_list

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3

TC: O(b) SC: O(log n) class Solution recursive: def isSymmetric(self, root): if root is None: return True else: return self.isMirror(root.left, root.right) def isMirror(self, left, right): if left is None and right is None: return True if left is None or right is None: return False if left.val == right.val: outPair = self.isMirror(left.left, right.right) inPiar = self.isMirror(left.right, right.left) return outPair and inPiar else: return False class Solution iterative: def isSymmetric(self, root): if root is None: return True stack = [[root.left, root.right]] while len(stack) > 0: pair = stack.pop(0) left = pair[0] right = pair[1] if left is None and right is None: continue if left is None or right is None: return False if left.val == right.val: stack.insert(0, [left.left, right.right]) stack.insert(0, [left.right, right.left]) else: return False return True

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations.

def challenge(nums): ....slow = fast = 0 ....while fast < len(nums): ........if nums[fast] != 0: ............nums[slow], nums[fast] = nums[fast], nums[slow] ........if nums[slow] != 0: ............slow += 1 ........fast += 1 ....return nums

Remove duplicates from a linked list

def remove_duplicates(self): current_node = self.head while current_node: while current_node.next and current_node.next.val == current_node.val: current_node.next = current_node.next.next current_node = current_node.next return self

Build a deck of cards with Object-Orientated Programming.

class Card: def __init___(self, suit, value): self.suit = suit self.value= value def show(self): print(f"{self.value}of {self.suit}") class Deck: def __init__(self): self.cards = [] self.build() def build(self): for s in ["Spades", "Clubs", "Diamonds", "Hearts"]: for v in range(1,14): self.cards. append( Card(s,v)) def show(self): for c in self.cards: c.show() #Next, we want to create a random number we call "r = random.randit(0, i)" we're passing our range from 0 to i. We only want to pick a number that is to the left our our current position. Because we are starting to the right of our list, iterating backwards and we want to pick a random index that is to the left of that. Then we want to swap two cards, the card at "i" and the card at "r". def shuffle(self): for i in range(len(self.card) -1, 0, -1): r = random.randint(0,i) self.cards[i], self.cards[r] = self.cards[r], self.cards[i] def draw(self): return self.cards.pop()

Count the number of prime numbers less than a non-negative number, n. Example 1: Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

class Solution(object): def countPrimes(self, n): if n <= 2: return 0 prime = [True] * n prime[:2] = [False, False] for base in xrange(2, int((n - 1) ** 0.5) + 1): if prime[base]: prime[base ** 2::base] = [False] * len(prime[base ** 2::base]) return sum(prime)

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.

class Solution(object): def isValid(self, s): # The stack to keep track of opening brackets. stack = [] # Hash map for keeping track of mappings. This keeps the code very clean. # Also makes adding more types of parenthesis easier mapping = {")": "(", "}": "{", "]": "["} # For every bracket in the expression. for char in s: # If the character is an closing bracket if char in mapping: # Pop the topmost element from the stack, if it is non empty # Otherwise assign a dummy value of '#' to the top_element variable top_element = stack.pop() if stack else '#' # The mapping for the opening bracket in our hash and the top # element of the stack don't match, return False if mapping[char] != top_element: return False else: # We have an opening bracket, simply push it onto the stack. stack.append(char) # In the end, if the stack is empty, then we have a valid expression. # The stack won't be empty for cases like ((() return not stack

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3.

class Solution(object): def maxDepth(self, root): if root is None: return 0 queue = [root] depth = 0 while queue: depth += 1 for i in range(len(queue)): cur_root = queue.pop(0) if cur_root.left: queue.append(cur_root.left) if cur_root.right: queue.append(cur_root.right) return depth

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order.

class Solution(object): ....def isValid(self, s): ........stack = ['N'] ........m = {')':'(',']':'[','}':'{'} ........for i in s: ............if i in m.keys(): ................ if stack.pop() != m[i]: ....................return False ................else: ....................stack.append(i) ........return len(stack) == 1

You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step

class Solution: def climbStairs(self, n: int) -> int: a, b = 1, 1 for i in range(n): a, b = b, a + b return a

Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.

class Solution: def longestCommonPrefix(strs): strs.sort() # so last and first character must have the same first letters prefix = "" for x, y in zip(strs[0], strs[-1]): #first word, #last word if x == y: prefix += x else: break return prefix print(Solution.longestCommonPrefix(["pie", "pig"]))

Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. Input: str = " -42" Output: -42 Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42. Input: str = "4193 with words" Output: 4193 Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

class Solution: def myAtoi(self, str: str) -> int: str = str.strip() str = re.findall('(^[\+\-0]*\d+)\D*', str) try: result = int(''.join(str)) MAX_INT = 2147483647 MIN_INT = -2147483648 if result > MAX_INT > 0: return MAX_INT elif result < MIN_INT < 0: return MIN_INT else: return result except: return 0

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example: Given nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length.

class Solution: def removeDuplicates(self, nums): len_ = 1 if len(nums)==0: return 0 for i in range(1,len(nums)): if nums[i] != nums[i-1]: nums[len_] = nums[i] len_ +=1 return len_ [1,2,2,3] nums[1] != nums[0] so... nums[1] = nums[1], length = 2 [1,2..] nums[2] == nums[1] so... skip, length = 2 [1,2,2...] nums[3] != nums[2] nums[2] = nums[3], length = 3 [1,2,3...]

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]]

class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n = len(matrix) for i in range(n): for j in range(i+1, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] for i in range(n): for j in range(n//2): matrix[i][j], matrix[i][n-1-j] = matrix[i][n-1-j],matrix[i][j]

Given an array, rotate the array to the right by k steps, where k is non-negative. 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: # speed up the rotation k %= len(nums) for i in range(k): previous = nums[-1] for j in range(len(nums)): nums[j], previous = previous, nums[j] Time complexity: O(n×k). All the numbers are shifted by one step (O(n) k times O(n)). Space complexity: O(1). No extra space is used. class Solution: # nums = [1,2,3,4,5,6,7], k = 3 def rotate(self, nums: List[int], k: int) -> None: n = len(nums) a = [0] * n #[0, 0, 0, 0] for i in range(n): a[(i + k) % n] = nums[i] nums[:] = a Time complexity: O(n). One pass is used to put the numbers in the new array. And another pass to copy the new array to the original one. Space complexity:O(n). Another array of the same size is used.

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Clarification: What should we return when needle is an empty string? This is a great question to ask during an interview. For the purpose of this problem, we will return 0 when needle is an empty string

class Solution: def strStr(self, haystack: str, needle: str) -> int: for i in range(0, len(haystack) - len(needle) + 1): if haystack[i:i+len(needle)] == needle: return i return -1

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: 2 / \ 1 3 Input: [2,1,3] Output: true Example 2: 5 / \ 1 4 / \ 3 6 Input: [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4.

class Solution: ....def isValidBST(self, root): ........def helper(node, lower = float('-inf'), upper = float('inf')): ................if not node: ....................return True ................val = node.val ................if val <= lower or val >= upper: ....................return False ................if not helper(node.right, val, upper): ....................return False ................if not helper(node.left, lower, val): ....................return False ................return True ........return helper(root)

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

class Solution: def romanToInt(self, s: str) -> int: output, currLevel, lookup = 0, 0, {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000} ....for i in range(len(s)-1,-1,-1): ........if lookup[s[i]] >= currLevel: currLevel = lookup[s[i]] output += lookup[s[i]] ........else: output -= lookup[s[i]] .....return output

Design a parking lot using oop

class parkingFloor(): def __init__(self,name): self.name = name self.spotTotal = {'compact':0,'large':0,'bike':0,'electric':0} self.spotTaken = {'compact':0,'large':0,'bike':0,'electric':0} self.freeSpot = {'compact':set(),'large':set(),'bike':set(),'electric':set()} self.takenSpot = {'compact':{},'large':{},'bike':{},'electric':{}} def assignSpot(self,tickt): if self.spotTaken[tickt.veh.type] >= self.spotTotal[tickt.veh.type]: return False for s in self.freeSpot[tickt.veh.type]: if s.id not in self.takenSpot[tickt.veh.type]: self.takenSpot[tickt.veh.type][s.id] = tickt self.spotTaken[tickt.veh.type]+=1 self.freeSpot[tickt.veh.type].remove(s) tickt.allocateSpot(s) return True return False def addSpot(self,type,v): for i in range(v): s = spot(type) self.freeSpot[type].add(s) self.spotTotal[type] += v class entryPanel(): def __init__(self,id): self.id = id def printTicket(self,tickt): print('Vehicle ID ',tickt.veh.id) print('Spot ID ',tickt.spot.id) print('Ticket ID ',tickt.id) print('Date Time',tickt.DateTime) def display(self,message): print(message) class vehicle(): def __init__(self,id,vehType): self.id = id self.type = vehType class spot(): def __init__(self,spotType): def generateId(): # some mechanism to generate spot id return 1 self.id = generateId() self.type = spotType class ticket(): def __init__(self,v1): self.id = self.generateId() self.veh = v1 self.spot = None self.DateTime = self.getTime() self.amount = 0 self.status = 'Active' self.payment = None def getTime(self): time = 1234 return time def generateId(self): # some mechanism to generate new ticket id new_ticket = 1 return new_ticket def allocateSpot(self,spot): self.spot = spot def addPayment(self,pay): self.status = 'Complete' self.payment = pay class parkingLot(): def __init__(self,name,address): self.name = name self.address = address self.level = [] def addLevel(self,floor): self.level.append(floor) def processEntry(self,t1,gate): for l in self.level: if l.assignSpot(t1): gate.printTicket(t1) return gate.display('No Spot Empty') def processExit(self,tickt,gate): def getTime(): # Gives the current time return 3 currTime = getTime() print('Processing fare',tickt.veh.type,tickt.spot.id,tickt.DateTime,currTime) amountCalculated = 7 tickt.addPayment(Payment(amountCalculated)) gate.display('Payment Successful') class Payment(): def __init__(self,amount): self.id = 'paymentid2' self.type = 'credit' # debit self.time = 'paymet time' class displayBoard(): def show(self,p): for l in p.level: print(l.name) for k in l.spotTotal.keys(): print(k, l.spotTotal[k] - l.spotTaken[k])

How can we print the number of words in descending order by count? {'dog': 2, 'apple': 1, 'cat': 3}

counts = [(count, word) for word, count in word_count.items()] counts.sort() for count, word in counts: print(f" {word} : {count}")

Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it. For example: if num = 4, then your program should return (4 * 3 * 2 * 1) = 24

def FirstFactorial(num): factorial = 1 for i in range(1, num+1): factorial = factorial * i return factorial print FirstFactorial(4) OR def FirstFactorial(num): if num == 1: return 1 else: return num*FirstFactorial(num-1)

Implement a binary search. def binary_search(val): """Using binary search, find val in range 1-100. Return # of guesses.""" assert 0 < val < 101, "Val must be between 1-100" num_guesses = 0 return num_guesses

def binary_search(val): """Using binary search, find val in range 1-100. Return # of guesses.""" assert 0 < val < 101, "Val must be between 1-100" num_guesses = 0 # START SOLUTION # higher_than = 0 lower_than = 101 guess = None while guess != val: num_guesses += 1 guess = (lower_than - higher_than) // 2 + higher_than if val > guess: higher_than = guess elif val < guess: lower_than = guess # END SOLUTION return num_guesses

Count the valleys: A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level. Given the sequence of up and down steps during a hike, find and print the number of valleys walked through. Sample Input UDDDUDUU Sample Output 1 Explanation If we represent _ as sea level, a step up as /, and a step down as \, the hike can be drawn as: _/\ _ \ / \/\/ The hiker enters and leaves one valley.

def countingValleys(n, s): a,b = 0,0 d = {"U":1, "D":-1} for i in s: if not a+d[i] and a<0: b+=1 a+=d[i] return b

Write an algorithm to delete a node in the middle of a singly linked list, given access only to that node. Example: Node c from a - b - c - d - e - f Nothing is returned but new list is a - b - d - e - f

def delete_middle_node(node): node.value = node.next.value node.next = node.next.next

Find the depth of a binary tree using recursive calls!

def depth(tree): if not tree: return 0 left_depth = depth(tree["left_child"]) right_depth = depth(tree["right_child"]) if left_depth > right_depth: return left_depth + 1 else: return right_depth + 1

Implement your version of fibonacci() which has the same functionality without using any recursive calls!

def fibonacci(n): if n < 0: ValueError("Input 0 or greater only!") fibs = [0, 1] if n <= len(fibs) - 1: return fibs[n] while n > len(fibs) - 1: fibs.append(fibs[-1] + fibs[-2]) return fibs[-1]

Implement your version of find_min() which has the same functionality using recursive calls!

def find_min(my_list, min = None): if not my_list: return min if not min or my_list[0] < min: min = my_list[0] return find_min(my_list[1:], min)

Write a function that can return the smallest value of an array or the index of that value. The function's 2nd parameter will tell whether it should return the value or the index. min([1,2,3,4,5], 'value') // => 1 min([1,2,3,4,5], 'index') // => 0

def find_smallest(numbers,to_return): return min(numbers) if to_return == 'value' else numbers.index(min(numbers)) OR def find_smallest(numbers,to_return): answer = None min_ = numbers[0] counter = 0 for x in range(1, len(numbers)): if numbers[x] < min_: counter = x min_ = numbers[x] if to_return == "value": answer = min_ elif to_return == "index": answer = counter return answer

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]

def generate(self, numRows): res = [[1]] for i in range(1, numRows): res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])] return res[:numRows] OR def generate(numRows): pascal = [[1]*(i+1) for i in range(numRows)] for i in range(numRows): for j in range(1,i): pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j] return pascal

I will give you an integer. Give me back a shape that is as long and wide as the integer. The integer will be a whole number between 0 and 50. Example n = 3, so I expect a 3x3 square back just like below as a string: +++ +++ +++

def generateShape(int): solution = '' for i in range(int): solution += '+' * int + '\n' return solution[:-1]

Write a method to compute all permutations of a string of unique characters.

def getPerms(string): permutations = [] if string == None: return None if len(string) == 0: #base case permutations.append(" ") return permutations first = string[0] #get first letter in string remainder = string[1:] words = getPerms(remainder) for word in words: index = 0 for letter in word: s = insertCharAt(word, first, index) permutations.append(s) index += 1 return permutations def insertCharAt(word, char, i): start = word[:i] end = word[i:] return start + char + end

Write an efficient function that takes stock_prices and returns the best profit I could have made from one purchase and one sale of one share of Apple stock yesterday. For example: stock_prices = [10, 7, 5, 8, 11, 9] get_max_profit(stock_prices)

def get_max_profit(stock_prices): if len(stock_prices) < 2: raise ValueError('Getting a profit requires at least 2 prices') # We'll greedily update min_price and max_profit, so we initialize # them to the first price and the first possible profit min_price = stock_prices[0] max_profit = stock_prices[1] - stock_prices[0] # Start at the second (index 1) time # We can't sell at the first time, since we must buy first, # and we can't buy and sell at the same time! # If we started at index 0, we'd try to buy *and* sell at time 0. # This would give a profit of 0, which is a problem if our # max_profit is supposed to be *negative*--we'd return 0. for current_time in range(1, len(stock_prices)): current_price = stock_prices[current_time] # See what our profit would be if we bought at the # min price and sold at the current price potential_profit = current_price - min_price # Update max_profit if we can do better max_profit = max(max_profit, potential_profit) # Update min_price so it's always # the lowest price we've seen so far min_price = min(min_price, current_price) return max_profit Complexity O(n) time and O(1) space. We only loop through the list once.

Given a 2D Array, : 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 An hourglass in A is a subset of values with indices falling in this pattern in arr's graphical representation: a b c d e f g There are 16 hourglasses in arr. An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print the maximum hourglass sum. The array will always be 6 x 6. Example -9 -9 -9 1 1 1 0 -9 0 4 3 2 -9 -9 -9 1 2 3 0 0 8 6 6 0 0 0 0 -2 0 0 0 0 1 2 4 0 The highest hourglass sum is 28 from the hourglass beginning at row 1, column 2: 0 4 3 1 8 6 6

def hourglassSum(arr): sums = [] for i in range(len(arr)-2): for j in range(len(arr)-2): sums.append(arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2]) return(max(sums))

Write a method in the LinkedList class: .insert(). .insert() takes two arguments: -the value which will be used to initialize a Node. -the insertion location for the node instance. -return self at the end of the function.

def insert(self, node_value, location): if not location: new_head = Node(node_value) new_head.next = self.head self.head = new_head return self prev = self.head node = Node(node_value) current_node = self.head.next while location > 1: prev = current_node current_node = current_node.next location -= 1 prev.next = node node.next = current_node return self

Given two singly linked lists, determine if the two lists intersect. Return the intersecting node.

def intersection(list1, list2): ....if list1.tail is not list2.tail: ........return False ....shorter = list1 if len(list1) < len(list2) else list2 ....longer = list2 if len(list1) < len(list2) else list1 ....diff = len(longer) - len(shorter) ....shorter_node, longer_node = shorter.head, longer.head ....for i in range(diff): ........longer_node = longer_node.next ....while shorter_node is not longer_node: ........shorter_node = shorter_node.next ........longer_node = longer_node.next ....return longer_node

Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2->1 Output: true

def isPalindrome(self, head): fast = slow = head # find the mid node while fast and fast.next: fast = fast.next.next slow = slow.next # reverse the second half node = None while slow: nxt = slow.next slow.next = node node = slow slow = nxt # compare the first and second half nodes while node: # while node and head: if node.val != head.val: return False node = node.next head = head.next return True O(n) extra space solution by using deque: def isPalindrome(self, head): queue = collections.deque([]) cur = head while cur: queue.append(cur) cur = cur.next while len(queue) >= 2: if queue.popleft().val != queue.pop().val: return False return True

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true

def isPalindrome(self, s: str) -> bool: s = s.lower() start = 0 end = len(s)- 1 while start < end: if not s[start].isalnum(): start += 1 elif not s[end].isalnum(): end -= 1 else: if s[start].lower() != s[end].lower(): return False else: start += 1 end -= 1 return True

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. Input: board = [["5","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] Output: true

def isValidSudoku(self, board): sudoku = [] for i, row in enumerate(board): for j, c in enumerate(row): if c != '.': #(i,c) = left to right rows, index of row and number #(c,j) = number and index of number sudoku += ((i, c), (c, j), (i//3, j//3, c)) return len(sudoku) == len(set(sudoku))

Return the nearest prime number. solve(4) = 3. The nearest primes are 3 and 5. If difference is equal, pick the lower one. solve(125) = 127

def is_prime(p): if p % 2 == 0 : return False for x in range(3,int(p**.5)): if p % x == 0: return False return True #return not any([p%x==0 for x in range(3,int(p**.5))]) if is_prime(n): return n step = (n%2) + 1 while 1: if is_prime(n-step): return n-step elif is_prime(n+step): return n+step else: step += 2 return None

Jumping on clouds! For each game, Emma can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting position to the last cloud. Emma will get an array of clouds numbered 0 if they are safe or 1 if they must be avoided. 7 0 0 1 0 0 1 0 Sample Output 0 4 Explanation 0: Emma must avoid c[2] and c[5]. She can win the game with a minimum of 4 jumps: Sample Input 1 0 0 0 0 1 0 Sample Output 1 3 Explanation 1:The only thundercloud to avoid is c[4] . Emma can win the game in 3 jumps:

def jumpingOnClouds(c): ....x = 0 ....count = 0 ....while x < len(c) - 2: ........x = x + 1 if c[x+2] else x+2 ........count += 1 ....if x < len(c) - 1: ........count += 1 ....return count

Write an algorithm to find the kth to last element of a singly linked list.

def kth_to_last(ll, k): ....runner = current = ll.head ....for i in range(k): ........if runner is None: ............return None ........runner = runner.next ....while runner: ........current = current.next ........runner = runner.next ....return current

Find the length of the sequence in an array, between the first and the second occurrence of a specified number. For example, for a given array arr [0, -3, 7, 4, 0, 3, 7, 9] Finding length between two 7s like lengthOfSequence([0, -3, 7, 4, 0, 3, 7, 9], 7) would return 5.

def length_of_sequence(arr, n): if arr.count(n) != 2: return 0 a = arr.index(n) # list_name.index(element, start, end) element - The element whose lowest index will be returned. start (Optional) - The position from where the search begins. b = arr.index(n, a + 1) return b - a + 1

For a given string s find the character c with longest *consecutive* repetition and return: (character, # of repetitions)

def longest_repetition(chars): max_char = '' max_count = 0 char = '' count = 0 for c in chars: if c != char: count = 0 char = c else: count += 1 if count > max_count: max_char = char max_count = count return max_char, max_count

This challenge, you'll return the maximum profit possible for buying-and-selling a stock. The best function will be given a list of stock prices as they happened throughout the day: best([15, 10, 20, 22, 1, 9]) It should return the maximum possible profit on the stock for that day. For example, with these prices, our best option would have been to buy the stock at $10 and sell it at $22. So the profit would be $12:

def maxProfit(self, prices: List[int]) -> int: if not prices or len(prices) == 1: return 0 min_ = float('inf') #useful for finding lowest values for something max_ = 0 ans = 0 for i in range(len(prices)-1): if min_ > prices[i]: min_ = prices[i] # for each number, if it is lower than min, it becomes the new min else: if prices[i] < prices[i+1]: continue # if its not lower than min_ and not lower than the number to the right, continue else: max_ = prices[i]-min_ ans += max_ min_ = float('inf') # num is not lower than min and is higher than the number to the right, so max is the num minus min, add the total to max, and reset min if prices[-2] < prices[-1]: ans += prices[-1] - min_ return ans

Given an integer array nums, design an algorithm to randomly shuffle the array. Implement the Solution class: Solution(int[] nums) Initializes the object with the integer array nums. int[] reset() Resets the array to its original configuration and returns it. int[] shuffle() Returns a random shuffling of the array.

import random class Solution: def __init__(self, nums): self.nums = nums def reset(self): return self.nums def shuffle(self): return sorted(self.nums, key=lambda x: random.random())

Write a function max_sub_sum() which has a single parameter: my_list. max_sub_sum() should return the maximum sum of contiguous values in my_list. Your solution should run in O(N) time and O(1) space! # <> will mark the current element nums = [1, -7, 2, 15, -11, 2] most_seen = 0 current_max_sub_sum = 0 [<1>, -7, 2, 15, -11, 2] most_seen = 1 current_max_sub_sum = 1 [1, <-7>, 2, 15, -11, 2] most_seen = 1 current_max_sub_sum = -6 # our sum is negative # anything positive which comes after # will be better without this "sub-list" # reset current max to 0! current_max_sub_sum = 0

def maximum_sub_sum(my_list): if max(my_list) < 0: return max(my_list) max_sum = 0 max_sum_tracker = 0 for i in range(len(my_list)): max_sum_tracker += my_list[i] if max_sum_tracker < 0: max_sum_tracker = 0 if max_sum_tracker > max_sum: max_sum = max_sum_tracker return max_sum

Given a list of integers, return the maximum sum possible from a contiguous sub-list. A sub-list is an uninterrupted portion of the list (up to and including the entire list). nums = [1, -7, 2, 15, -11, 2] maximum_sub_sum(nums) # 17 # The sum of sub-list nums[2:4]

def maximum_sub_sum(my_list): max_sum = my_list[0] for i in range(len(my_list)): for j in range(i, len(my_list)): sub_sum = sum(my_list[i:j + 1]) if sub_sum > max_sum: max_sum = sub_sum return max_sum

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2. Example: Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]

def merge(self, nums1, m, nums2, n): while m > 0 and n > 0: if nums1[m-1] >= nums2[n-1]: nums1[m+n-1] = nums1[m-1] m -= 1 else: nums1[m+n-1] = nums2[n-1] n -= 1 if n > 0: nums1[:n] = nums2[:n]

Write a function that returns the merge point node of two linked lists if it exists.

def merge_point(linked_list_a, linked_list_b): size_of_a = linked_list_a.size() size_of_b = linked_list_b.size() diff = abs(size_of_a - size_of_b) if size_of_a > size_of_b: bigger = linked_list_a.head smaller = linked_list_b.head else: bigger = linked_list_b.head smaller = linked_list_a.head for i in range(diff): bigger = bigger.next while bigger and smaller: if bigger == smaller: return bigger bigger = bigger.next smaller = smaller.next return None

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Example 1: Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. Example 2: Input: nums = [0,1] Output: 2 Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.

def missingNumber(self, nums): n = len(nums) return n * (n+1) / 2 - sum(nums)

Write a function to return the mean, median, and mode of a list of numbers.

def mmm(arr): mean = sum(arr) / float(len(arr)) arr = sorted(arr) median = arr[int(len(arr) / 2)] hashtable = {} for i in arr: if i in hashtable: hashtable[i] = 1 if mode is None or hashtable[i] > mode: mode = i return {'mean': mean, 'median': median, 'mode': mode}

Remove Duplicates: We can reduce the space complexity to O(1) with an in-place solution. Now we want to alter a sorted input list with all duplicates moved to the end of the list. The return value will be the index of the final unique value.

def move_duplicates(dupe_list): unique_idx = 0 for i in range(len(dupe_list) - 1): if dupe_list[i] != dupe_list[i + 1]: dupe_list[i], dupe_list[unique_idx] = dupe_list[unique_idx], dupe_list[i] unique_idx += 1 dupe_list[unique_idx], dupe_list[len(dupe_list) - 1] = dupe_list[len(dupe_list) - 1], dupe_list[unique_idx] return unique_idx

We want to check if two strings are, at most, one edit away from being the same. An edit is adding, deleting, or changing a single letter. So, for example, "make" can be turned into "fake" by just changing one letter: >>> one_away("make", "fake") True But we can't turn "task" into "take" without changing two letters: >>> one_away("task", "take") False

def one_away(w1, w2): """Given two strings, are they, at most, one edit away?""" # START SOLUTION # Strings length can only vary by, at most, one letter if abs(len(w1) - len(w2)) > 1: return False # Make sure w2 is the shorter string if len(w2) > len(w1): w1, w2 = w2, w1 # Keep track of number of wrong letters wrong = 0 # Loop over w1 with i and over w2 with j i = j = 0 while j < len(w2): if w1[i] != w2[j]: # We found a wrong letter wrong += 1 if wrong > 1: return False # We'll move to the next char in the longer string. i += 1 # If same length, move the next char in shorter. # Otherwise, don't move in shorter string --- this # will cover the case of a added letter. if len(w1) == len(w2): j += 1 else: # Both letters match; move to next letter in both i += 1 j += 1 return True

Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result. Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0). If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers. Examples "is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est" "4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople" "" --> ""

def order(sentence): return " ".join(sorted(sentence.split(), key=lambda x: int(filter(str.isdigit, x))))

Write a function to find all the numbers that overlap between two ranges. For example, in the ranges [5,20] and [17,20] the overlapping integers are [17,18,19,20]

def overlapping(range1, range2): overlap = [ ] for i in range(range1[0], range1[1] + 1): if i >= range2[0] and i <= range2[1]: overlap.append(i) return overlap

Write a function pair_sum(), which has two parameters: nums and target. pair_sum() should return a list containing a single pair of indices whose values sum to target. This can be any pair that meets the requirements. If no such values exist, return None. Your solution should run in O(N) time and O(N) space! # <> marks the current element nums = [4, 2, 8, 9, 6] target = 8 [<4>, 2, 8, 9, 6] # target - 4 = 4 # we need another 4... [4, <2>, 8, 9, 6] # target - 2 = 6 # we need a 6...

def pair_sum(nums, target): complements = {} indices = {} for i in range(len(nums)): x = complements.get(nums[i], None) if x is not None: return [indices[x], i] complements[target - nums[i]] = nums[i] indices[nums[i]] = i

Write code to remove duplicates from an unsorted linked list. How would you solve this problem if a temporary buffer is not allowed?

def remove_dups(ll): ....if ll.head is None: ........return ....current = ll.head ....seen = set([current.value]) ....while current.next: ........if current.next.value in seen: ............current.next = current.next.next ........ else: ............seen.add(current.next.value) .............current = current.next ....return ll def remove_dups_followup(ll): ....if ll.head is None: ........ return .... current = ll.head ....while current: ........runner = current ............while runner.next: ................if runner.next.value == current.value: ....................runner.next = runner.next.next ............else: ................runner = runner.next ........current = current.next ....return ll.head

Return reverse of string using recursion. You may NOT use the reversed() function!

def rev_string(astring): # START SOLUTION if len(astring) < 2: return astring return astring[-1] + rev_string(astring[:-1])

Write a function that takes a list of characters and reverses the letters in place. ↴ Why a list of characters instead of a string? The goal of this question is to practice manipulating strings in place. Since we're modifying the input, we need a mutable ↴ type like a list, instead of Python 2.7's immutable strings.

def reverse(list_of_chars): left_index = 0 right_index = len(list_of_chars) - 1 while left_index < right_index: # Swap characters list_of_chars[left_index], list_of_chars[right_index] = \ list_of_chars[right_index], list_of_chars[left_index] # Move towards middle left_index += 1 right_index -= 1

Reverse a string subtracting all punctuation and numbers.

def reverse_letter(s): return ''.join([i for i in s if i.isalpha()])[::-1]

Given a sorted list rotated k times, return the index where the "unrotated" list would begin. rotated_list = ['c', 'd', 'e', 'f', 'a'] rotation_point(rotated_list) # index 4 # a sorted list would start with 'a' another_rotated_list = [13, 8, 9, 10, 11] rotation_point(rotated_list) # index 1 # a sorted list would start with 8 *Use a modified binary search algorithm to improve our solution's time efficiency from O(N) to O(logN).

def rotation_point(rotated_list): low = 0 high = len(rotated_list) - 1 while low <= high: mid = (low + high) // 2 mid_next = (mid + 1) % len(rotated_list) mid_previous = (mid - 1) % len(rotated_list) if (rotated_list[mid] < rotated_list[mid_previous]) and (rotated_list[mid] < rotated_list[mid_next]): return mid elif rotated_list[mid] < rotated_list[high]: high = mid - 1 else: low = mid + 1

Given a variable name in snake_case, return camelCase of name.

def snake_to_camel(variable_name): """Given a variable name in snake_case, return camelCase of name.""" # START SOLUTION words = variable_name.split("_") for i in range(1, len(words)): words[i] = words[i].capitalize() return "".join(words)

In the following 6 digit number: 283910 91 is the greatest sequence of 2 consecutive digits. In the following 10 digit number: 1234567890 67890 is the greatest sequence of 5 consecutive digits. Complete the solution so that it returns the greatest sequence of five consecutive digits found within the number given. The number will be passed in as a string of only digits. It should return a five digit integer. The number passed may be as large as 1000 digits.

def solution(digits): maxNum = 0 for i in range(len(digits)-4): curNum = int(digits[i:i+5]) if curNum > maxNum: maxNum = curNum return maxNum

The vowel substrings in the word codewarriors are o,e,a,io. The longest of these has a length of 2. Given a lowercase string that has alphabetic characters only and no spaces, return the length of the longest vowel substring. Vowels are any of aeiou.

def solve(s): vowels = ['a','e','i','o','u'] count = 0 totals = [] for letter in s: if letter in vowels: count += 1 else: count = 0 totals.append([count]) # [0] turns [2] into just 2 return max(totals)[0]

Given two already-sorted lists: >>> a = [1, 3, 5, 7] >>> b = [2, 6, 8, 10] Write a function that returns a new list that is the sorted merge of both of them. For the above lists, our result would be: >>> sort_ab(a, b) [1, 2, 3, 5, 6, 7, 8, 10] It would be easy to do this by just using Python's built-in sort method, like this: >>> out = a + b >>> out.sort() However, this would have the runtime of O(n log n), where n is the combined length of a and b. You can get a much better runtime by exploiting the fact that both of the input lists are already sorted.

def sort_ab(a, b): """Given already-sorted lists, `a` and `b`, return sorted list of both. You may not use sorted() or .sort(). """ # START SOLUTION result = [] a_index = 0 # index into list a b_index = 0 # index into list b while a_index < len(a) and b_index < len(b): # Check current items in both lists: # if a < b, add a and increase a_index # else add b and increase b_index if a[a_index] < b[b_index]: result.append(a[a_index]) a_index += 1 else: result.append(b[b_index]) b_index += 1 # One list could have things remaining; add any remaining items result.extend(a[a_index:]) result.extend(b[b_index:]) return result

Write a function named substring_between_letters that takes a string named word, a single character named start, and another character named end. This function should return the substring between the first occurrence of start and end in word. If start or end are not in word, the function should return word. For example, substring_between_letters("apple", "p", "e") should return "pl".

def substring_between_letters(word, start, end): start_ind = word.find(start) end_ind = word.find(end) if start_ind > -1 and end_ind > -1: return(word[start_ind+1:end_ind]) return word

Have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string. Input: "fun times!" Output: gvO Ujnft!

ef LetterChanges(str): newstr = "" outstr = "" for char in str: if char.isalpha(): if char != "z": newstr = newstr + chr(ord(char)+1) else: newstr = newstr + "a" else: newstr = newstr + char for char in newstr: if (char == "a") or (char == "e") or (char == "i") or (char == "o") or (char == "u"): char = char.upper() outstr = outstr + char return outstr # keep this function call here print(LetterChanges(input()))

Check for a palindrone without using sorted. Is first letter same as last? If so, move in both directions Reached middle? It's a palindrome!

for word in ['radar', 'racecar', 'grumble']: palindrome = True start = 0 end = len(word) - 1 # pos of last letter while start < end: if word[start] != word[end]: print(f"Not a palindrome: {word}") palindrome = False break start = start + 1 end = end - 1 if palindrome: print(f"Palindrome: {word}")

Have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty. Input: "fun&!! time" Output: time Input: "I love dogs" Output: love

import re def LongestWord(sen): sen = re.sub("[^\w\s]", "", sen) #replaces not (^) word characters or spaces with the empty string lst = sen.split() max = 0 max_word = "" for i in lst: if len(i) > max: max = len(i) max_word = i return max_word # keep this function call here print(LongestWord(input()))

Fibonacci With Memoization The Fibonacci sequence is a perfect case to apply dynamic programming. Each Fibonacci number relies on two previous numbers, and those numbers never change. We have overlapping sub-problems! We'll store the answers to sub-problems using memoization. Think of it like jotting notes down on a memo. With each sub-problem, we'll check if we have a note in our memo. If we do, then we can use that information, otherwise, we'll need to do a calculation and then store that calculation in our memo pad! Remember these notes are possible because the answer will always be the same: the nth Fibonacci number will never change. Just like the 1 + 1 + 1 + 1 example, we don't need to recompute the 3rd and 4th Fibonacci number to calculate the 5th Fibonacci number if we already know the 3rd and 4th number.

num_in_fibonacci = 9 function_calls = [] def fibonacci(num, memo): function_calls.append(1) if num < 0: print("Not a valid number") if num <= 1: return num elif memo.get(num): return memo.get(num) else: memo[num] = fibonacci(num - 1, memo) + fibonacci(num - 2, memo) return memo[num] fibonacci_result = fibonacci(num_in_fibonacci, {})


संबंधित स्टडी सेट्स

ENT chapter 7 (head and neck surgery)

View Set

Chapter 3: Genetics Concept Questions

View Set

EXAM 3 REVIEW MAR 3503 PRACTICE QUESTIONS

View Set