Given a flight itinerary consisting of starting city, destination city, and ticket price (2D list) - find the optimal price flight path to get from start to destination. (A variation of Dynamic Programming Shortest Path)
Given some coin denominations and a target value M, return the coins combination with the minimum number of coins.
Time complexity: O(MN), where N is the number of distinct type of coins.
Space complexity: O(M).
Given a set of numbers in an array which represent a number of consecutive days of Airbnb reservation requested, as a host, pick the sequence which maximizes the number of days of occupancy, at the same time, leaving at least a 1-day gap in-between bookings for cleaning.
The problem reduces to finding the maximum sum of non-consecutive array elements.
E.g.
// [5, 1, 1, 5] => 10
The above array would represent an example booking period as follows -
// Dec 1 - 5
// Dec 5 - 6
// Dec 6 - 7
// Dec 7 - 12
The answer would be to pick Dec 1-5 (5 days) and then pick Dec 7-12 for a total of 10 days of
occupancy, at the same time, leaving at least 1-day gap for cleaning between reservations.
Similarly,
// [3, 6, 4] => 7
// [4, 10, 3, 1, 5] => 15
Given a list of denominations (e.g., [1, 2, 5] means you have coins worth $1, $2, and $5) and a target number k, find all possible combinations, if any, of coins in the given denominations that add up to k. You can use coins of the same denomination more than once.
Tire
"""A Trie/Prefix Tree is a kind of search tree used to provide quick lookupof words/patterns in a set of words. A basic Trie however has O(n^2) space complexitymaking it impractical in practice. It however provides O(max(search_string, length oflongest word)) lookup time making it an optimal approach when space is not an issue."""classTrieNode:def__init__(self): self.nodes =dict()# Mapping from char to TrieNode self.is_leaf =Falsedefinsert_many(self,words: [str]):""" Inserts a list of words into the Trie :param words: list of string words :return: None """for word in words: self.insert(word)definsert(self,word:str):""" Inserts a word into the Trie :param word: word to be inserted :return: None """ curr = selffor char in word:if char notin curr.nodes: curr.nodes[char]=TrieNode() curr = curr.nodes[char] curr.is_leaf =Truedeffind(self,word:str) ->bool:""" Tries to find word in a Trie :param word: word to look for :return: Returns True if word is found, False otherwise """ curr = selffor char in word:if char notin curr.nodes:returnFalse curr = curr.nodes[char]return curr.is_leafdefdelete(self,word:str):""" Deletes a word in a Trie :param word: word to delete :return: None """def_delete(curr: TrieNode,word:str,index:int):if index ==len(word):# If word does not existifnot curr.is_leaf:returnFalse curr.is_leaf =Falsereturnlen(curr.nodes)==0 char = word[index] char_node = curr.nodes.get(char)# If char not in current trie nodeifnot char_node:returnFalse# Flag to check if node can be deleted delete_curr =_delete(char_node, word, index +1)if delete_curr:del curr.nodes[char]returnlen(curr.nodes)==0return delete_curr_delete(self, word, 0)defprint_words(node: TrieNode,word:str):""" Prints all the words in a Trie :param node: root node of Trie :param word: Word variable should be empty at start :return: None """if node.is_leaf:print(word, end=" ")for key, value in node.nodes.items():print_words(value, word + key)deftest_trie(): words ="banana bananas bandana band apple all beast".split() root =TrieNode() root.insert_many(words)# print_words(root, "")assertall(root.find(word) for word in words)assert root.find("banana")assertnot root.find("bandanas")assertnot root.find("apps")assert root.find("apple")assert root.find("all") root.delete("all")assertnot root.find("all") root.delete("banana")assertnot root.find("banana")assert root.find("bananas")returnTruedefprint_results(msg:str,passes:bool) ->None:print(str(msg), "works!"if passes else"doesn't work :(")defpytests():asserttest_trie()defmain():""">>> pytests() """print_results("Testing trie functionality", test_trie())if__name__=="__main__":main()
Exotic
import mathfrom numbers import Rationaldefnumber_decorate(func):defnumber_wrapper(*args,**kwargs):returnNumber(func(*args, **kwargs))return number_wrapperdefabout(number):returnNumber(float(number.value))defpoint(number):returnNumber(number.value /10** (int(math.log10(number.value)) +1))classNumber(Rational): names_list = ['ZERO','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT','NINE'] names ={i: name for i, name inenumerate(names_list)}def__init__(self,value):ifisinstance(value, Number): value = value.value self.value = valuedef__complex__(self):returncompile(self.value)def__bool__(self):returnbool(self.value)@number_decoratedef__add__(self,other):return self.value + other@number_decoratedef__radd__(self,other):return other + self.value@number_decoratedef__neg__(self):return-self.value@number_decoratedef__pos__(self):return+self.value@number_decoratedef__mul__(self,other):return self.value * other@number_decoratedef__rmul__(self,other):return other * self.value@number_decoratedef__truediv__(self,other):return self.value / other@number_decoratedef__rtruediv__(self,other):return other / self.value@number_decoratedef__pow__(self,power):return self.value**power@number_decoratedef__rpow__(self,base):return base ** self.value@number_decoratedef__abs__(self):returnabs(self.value)@number_decoratedefconjugate(self):return self.value.conjugate()def__eq__(self,other):return self.value == otherdef__float__(self):returnfloat(self.value)@number_decoratedef__trunc__(self):return math.trunc(self.value)@number_decoratedef__floor__(self):return math.floor(self.value)@number_decoratedef__ceil__(self):return math.ceil(self.value)@number_decoratedef__round__(self,n=None):returnround(self.value, n)@number_decoratedef__floordiv__(self,other):return self.value // other@number_decoratedef__rfloordiv__(self,other):return other // self.value@number_decoratedef__mod__(self,other):return other % self.value@number_decoratedef__rmod__(self,other):return self.value % other@number_decoratedef__lt__(self,other):return self.value < other@number_decoratedef__le__(self,other):return self.value <= other@number_decoratedef__gt__(self,other):return self.value > other@number_decoratedef__ge__(self,other):return self.value >= other@number_decoratedefnumerator(self):return self.value.numerator@number_decoratedefdenominator(self):return self.value.denominatordef__int__(self):returnint(self.value)def__repr__(self):returnrepr(self.value)@number_decoratedef__and__(self,other):if0< other <1:return self.value + otherelse:return self.value *10+ otherZERO =Number(0)ONE =Number(1)TWO =Number(2)THREE =Number(3)FOUR =Number(4)FIVE =Number(5)SIX =Number(6)SEVEN =Number(7)EIGHT =Number(8)NINE =Number(9)