<jupyter_start><jupyter_text>Puzzle oneIt is New Year's Day and people are in line for the Wonderland rollercoaster ride. Each person wears a sticker indicating their initial position in the queue from  to . Any person can bribe the person directly in front of them to swap positions, but they still wear their original sticker. One person can bribe at most two others.Determine the minimum number of bribes that took place to get to a given queue order. Print the number of bribes, or, if anyone has bribed more than two people, print Too chaotic<jupyter_code>#importing modules 
import unittest

def puzzle_one(q):
  if(len(q)> 1000): 
    raise ValueError()
  s = 0
  i = len(q)-1
  for _ in q: 
    if (i+1)>q[i]:
      if i>0 and q[i-1] == i+1:
          j = q[i]; 
          q[i] = q[i-1]; 
          q[i-1] = j; 
          s+=1; 
      elif i>1 and q[i-2] == i+1: 
          j = q[i]; 
          q[i] = q[i-2]; 
          q[i-2] = q[i-1]; 
          q[i-1] = j; 
          s+=2; 
      else:
          return "Too chaotic"
    i -=1
  return s

#unit tests
class UnitTestPuzzleOne(unittest.TestCase): 
  def test_safe_values(self):
    self.assertEqual(puzzle_one([1, 2, 3, 4, 5]), 0)
    self.assertEqual(puzzle_one([1, 2, 3, 5, 4]), 1)
  def test_boundary_conditions(self): 
    self.assertEqual(puzzle_one([]), 0)
    self.assertRaises(ValueError, puzzle_one, list((i for i in range(1001))))

unittest.main(argv=[''], verbosity=1, exit=False)<jupyter_output>.F
======================================================================
FAIL: test_safe_values (__main__.UnitTestPuzzleOne)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython-input-56-8b09ccda7c2c>", line 30, in test_safe_values
    self.assertEqual(puzzle_one([1, 2, 3, 4, 5]), 1)
AssertionError: 0 != 1

----------------------------------------------------------------------
Ran 2 tests in 0.002s

FAILED (failures=1)<jupyter_text>Puzzle Two Harold is a kidnapper who wrote a ransom note, but now he is worried it will be traced back to him through his handwriting. He found a magazine and wants to know if he can cut out whole words from it and use them to create an untraceable replica of his ransom note. The words in his note are case-sensitive and he must use only whole words available in the magazine. He cannot use substrings or concatenation to create the words he needs.Given the words in the magazine and the words in the ransom note, print Yes if he can replicate his ransom note exactly using whole words from the magazine; otherwise, print No.For example, the note is "Attack at dawn". The magazine contains only "attack at dawn". The magazine has all the right words, but there's a case mismatch. The answer is No.<jupyter_code>#importing modules 
import unittest

def puzzle_two(m, n):
  j = 0
  m.sort()
  n.sort()
  j = 0
  for i, x in enumerate(m): 
    if m[i] == n[j]: 
      j +=1
  if j==len(n): 
    return "Yes"
  else: 
    return "No"

#unit tests
class UnitTestPuzzleOne(unittest.TestCase): 
  def test_safe_values(self):

    self.assertEqual(puzzle_two("give me one grand today night".split(),  "give one grand today".split()), "Yes")
    self.assertEqual(puzzle_two("ive got a lovely bunch of coconuts".split(),  "ive got some coconuts".split()), "No")


unittest.main(argv=[''], verbosity=1, exit=False)<jupyter_output>.
----------------------------------------------------------------------
Ran 1 test in 0.003s

OK<jupyter_text>Puzzle ThreeThere is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results.`strings = ['ab', 'ab', 'abc'] queries = ['ab', 'abc', 'bc']`There are `2` instances of `'ab'`, 1 of `'abc'` and of 'bc'. for each query, add an elment to the return array, `results = [2, 1, 0]`<jupyter_code>from collections import Counter
def puzzle_three(strings, queries):
    counted = Counter(strings)
    res = []
    for q in queries: 
        if q in counted:
            res.append(counted[q])
        else: res.append(0)
    return res
    #importing modules 
import unittest

#unit tests
class UnitTestPuzzleOne(unittest.TestCase): 
  def test_safe_values(self):
    self.assertEqual(puzzle_three("aba baba aba xzxb".split(),  "aba xzxb ab".split()), [2, 1, 0])
    self.assertEqual(puzzle_three("def de fgh".split(),  "de lmn fgh".split()), [1, 0, 1])

unittest.main(argv=[''], verbosity=1, exit=False)<jupyter_output>.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK<jupyter_text>Puzzle Four A bracket is considered to be any one of the following characters: (, ), {, }, [, or ].Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and ().A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, {[(])} is not balanced because the contents in between { and } are not balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (, and the pair of parentheses encloses a single, unbalanced closing square bracket, ].By this logic, we say a sequence of brackets is balanced if the following conditions are met:It contains no unmatched brackets.The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets.Given `n` strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return YES. Otherwise, return NO.<jupyter_code>def puzzle_four(s):
    t = []
    o = ['{', '(', '[']
    for c in s:
        if(c in o): 
            t.append(c)
        
        elif(c == '}' and len(t)>0 and t[-1] == '{' ):
            t.pop(-1)
        elif(c == ']' and len(t)>0 and t[-1] == '[' ):
            t.pop(-1)
        elif(c == ')' and len(t)>0 and t[-1] == '(' ):
            t.pop(-1)
        else: return "NO"
    if(len(t) != 0): return "NO"
    else: return "YES" 


#unit tests
class UnitTestPuzzleOne(unittest.TestCase): 
  def test_safe_values(self):
    self.assertEqual(puzzle_four("{(([])[])[]}"),"YES")
    self.assertEqual(puzzle_four("{(([])[])[]]}"), "NO")
    
unittest.main(argv=[''], verbosity=1, exit=False)<jupyter_output>.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK<jupyter_text>Decorators in Python Decorator Problems* Write a decorator that counts the number of times a function is called* Write a decorator that counts how long a function took to execute* Write a decorator that caches any arguments' result and will reuse them (aka memoization).<jupyter_code># # of times a function is called

def decorator(func): 
  counter = []
  def wrapper(): 
    func()
    counter.append(1)
    return len(counter)
  return wrapper

@decorator
def hello(): 
  print("Hello")


# how long a function took to execute
import time 
def time_decorator(func): 
  def wrapper(): 
    tic = time.perf_counter()
    func()
    toc = time.perf_counter()
    print(f"it took {toc-tic:0.9f}")
  return wrapper
@time_decorator
def hi(): 
  print("hi")

#caches any argument's result and will reuse it (memoization)
def memoisation(func):
  memo = {}
  def wrapper(n): 
    if n in memo: 
       return memo[n]
    else: 
      memo[n] = func(n)
      return memo[n]
  return wrapper


@memoisation
def fib(n): 
  if (n==0): 
    return 0
  if (n==1): 
    return 1
  else: 
    return fib(n-1)+fib(n-2)
tic = time.perf_counter()
fib(482)
toc = time.perf_counter()

print(f"time to perform fibonnaci sequence is {toc-tic:0.4f}")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16558151410698327, 'fraction_numerical': 0.015319800842589047, 'mean_word_length': 2.8820614469772052, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '612986', 'license': 'MIT', 'n_tokens_mistral': 2589, 'n_tokens_neox': 2368, 'n_words': 919, 'path': 'practice_problems.ipynb', 'repo_name': 'amaniedu71/100-pandas-puzzles', 'size': '7833'}