<jupyter_start><jupyter_text><jupyter_code>class Student:
  school='Tenerife'
  def __init__(self,name,rollno):
    self.name=name
    self.rollno=rollno
    self.lap=self.Laptop()


  def show(self):
    print(self.name,self.rollno) 
    self.lap.show()


  class Laptop:
    def __init__(self):
      self.brand='Hp'
      self.cpu='i5'
      self.ram=8
    
    def show(self):
      print(self.brand,self.cpu,self.ram)



A,B = [4, -1, 0, 3], [-2, 5, 0, 3]

for i in range(1, len(A)):
  A[i] += A[i - 1]
  B[i] += B[i - 1]

print(A)
print(B)


s1=Student('teddy',5)
s1.show()
class PyCharm():
  def execute(self):
    print('Compiling')
    print('Running')

class MyEditor():
  def execute(self):
    print('spell check')
    print('variable check')
    print('running')
    print('compiling')

class Laptop():
  def code(self,ide):
    ide.execute()


ide = MyEditor()

lap1 = Laptop()

lap1.code(ide)

class Student():

  def __init__(self,m1,m2):
    self.m1=m1
    self.m2=m2


  def __add__(self,other):
    m1=self.m1+other.m1
    m2=self.m2+other.m2
    s3=Student(m1,m2)
    return s3

  def __gt__(self,other):
    r1=self.m1+self.m2
    r2=other.m1+other.m2
    if r1>r2:
      return True
    else:
      return False

  def __str__(self):
    return '{} {}'.format(self.m1,self.m2)

s1=Student(41,42)
s2=Student(43,44)

if s1>s2:
  print ('s1 wins')
else:
  print('s2 wins')


s3=s1+s2

print(s1)
from time import sleep
from threading import *


class Hello(Thread):
  def run(self):
    for i in range(5):
      print('Hello')
      sleep(1)



class Hi(Thread):
  def run(self):
    for i in range(5):
      print('Hi')
      sleep(1)



t1=Hello()
t2=Hi()

t1.start()
sleep(0.2)
t2.start()


t1.join()
t2.join()

print('Bye')
from time import *

def add(x,y):
  return x+y

def sub(x,y):
  return x-y

def timer(func,x,y):
  before=time()
  rv=func(x,y)
  after=time()
  print('elapsed' , after-before)
  return rv



print(timer(add,54,60))
#####Decorators

from time import time



def sub(x,y):
  return x-y

def timer(func):
  def f (*args,**kwargs):
    before=time()
    rv=func(*args,**kwargs)
    after=time()
    print('elapsed' , after-before)
    return rv
  return f



@timer
def add(x,y):
  return x+y

print(add(20,10))




#generators



#complex , a lot of code
class Compute():

  def __iter__(self):
    self.last=0
    return self

  def __next__(self):
    rv = self.last
    self.last +=1 
    if self.last>=10:
      raise StopIteration()
    sleep(.5)
    return rv


for val in Compute():
  print(val)


#Generator

#Generator
#give values to the "caller" one at a time
def compute():
  for i in range(10):
    sleep(.5)
    yield i


for val in compute():
  print(val)


#context manager

from sqlite3 import connect

def temptable(cur):
  cur.execute('create table points(x int ,y int)')
  yield
  cur.execute('drop table points')


class contextmanager():
  def __init__(self,gen):
    self.gen=gen

  def __call__(self,*args,**kwargs):
    self.args,self.kwargs=args,kwargs
    return self

  def __enter__(self):
    self.gen_inst=self.gen(*self.args,**self.kwargs)
    next(self.gen_inst)

  def __exit__(self,*args):
    next(self.gen_inst, None)


#@Contextmanager

with connect('test.db') as conn:
  cur=conn.cursor()
  with contextmanager(temptable)(cur):
    cur.execute('insert into points(x,y) values(1,1)')
    cur.execute('insert into points(x,y) values(2,2)')
    cur.execute('insert into points(x,y) values(3,3)')
    cur.execute('insert into points(x,y) values(4,4)')
    for row in cur.execute('select x,y from points'):
      print(row)
    


    


    



#context manager

from sqlite3 import connect
from contextlib import contextmanager

@contextmanager
def temptable(cur):
  cur.execute('create table points(x int ,y int)')
  try:
    yield
  finally:
    cur.execute('drop table points')
  
#temptable=contextmanager(temptable)
'''
class contextmanager():
  def __init__(self,gen):
    self.gen=gen

  def __call__(self,*args,**kwargs):
    self.args,self.kwargs=args,kwargs
    return self

  def __enter__(self):
    self.gen_inst=self.gen(*self.args,**self.kwargs)
    next(self.gen_inst)

  def __exit__(self,*args):
    next(self.gen_inst, None)
'''

#@Contextmanager

with connect('test.db') as conn:
  cur=conn.cursor()
  with temptable(cur):
    cur.execute('insert into points(x,y) values(1,1)')
    cur.execute('insert into points(x,y) values(2,2)')
    cur.execute('insert into points(x,y) values(3,3)')
    cur.execute('insert into points(x,y) values(4,4)')
    for row in cur.execute('select x,y from points'):
      print(row)
from functools import reduce


numbers=[i for i in range(1,21)]


def square(n):
  return n**2

def even(n):
  return n%2==0

def multiply(x,y):
  return x*y


squares=list(map(square, numbers))
print(squares)

evens=list(filter(even, numbers))
print(evens)


summary=reduce(multiply, numbers)
print(summary)



squares = list(map(lambda x : x**2, numbers))

print (squares)

filters = list(filter(lambda x : x % 2 ==0,numbers))
print(filters)

reduced = reduce(lambda x,y : x*y,numbers)
print(reduced)<jupyter_output>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
2432902008176640000
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
2432902008176640000<jupyter_text>New Section<jupyter_code>#decorators

from datetime import datetime



def log(func):
  def wrapper(*args,**kwargs):
    with open ('logs.txt','a') as f:
      f.write('called function with'+ ' '.join([str(arg) for arg in args]) + 'at'+str(datetime.now()))
    print('called function with '+ ' , '.join([str(arg) for arg in args]) + ' at '+str(datetime.now()))
    val=func(*args,**kwargs)
    return val
  return wrapper


@log
def run(a,b,c=9):
  print(a+b+c)


run(1,3,9)

a=1
b=2
def func():

  global b
  b = b+1
func()
print(b)



def SetAnnual():
  global annual
  annual=10000
def PrintMonthly():
  print("Your monthly payment is "+str(annual/12)+" USD.")
SetAnnual()
PrintMonthly()

pitchnames=['fly','when','you','can']
# create a dictionary to map pitches to integers
note_to_int = dict((note, number) for number, note in enumerate(pitchnames))
print(note_to_int)
print(dict([(number,note) for number , note in enumerate(pitchnames)]))
Q=[1, 2, 3, 4]
Q=[P-1 for P in Q]

print(Q)
moves=0
for i,P in enumerate(Q):
        # i is the current position of P, while P is the
        # original position of P.
        #
        # First check if any P is more than two ahead of 
        # its original position
        if P - i > 2:
            print("Too chaotic")

        for j in range(max(P-1,0),i):
            if Q[j] > P:
                moves += 1
        print(moves)
def minimumBribes(q):
    bribes = 0
    for i in range(len(q)-1,-1,-1):
        if q[i] - (i + 1) > 2:
            print('Too chaotic')
            return
        for j in range(max(0, q[i] - 2),i):
            if q[j] > q[i]:
                bribes+=1
    print(bribes)


q=[1,2,3,4,5,6,7,8]


minimumBribes(q)
q=[1,2,3,5,4,6,7,8]

#for i in range(len(q)-1,-1,-1):
#  print(i)

bribes = 0
for i in range(len(q)-1,-1,-1):
    if q[i] - (i + 1) > 2:
        print('Too chaotic')
        
    for j in range(max(0, q[i] - 2),i):
        print(j)
        if q[j] > q[i]:
            bribes+=1
            print(j)
            print(i)


sorted_ids=[1, 2, 4, 5, 8, 9, 10, 12, 13, 16, 17, 18, 20]
a = sorted_ids[0]
b = sorted_ids[-1]
nums = set(sorted_ids)
expected = ["T" + str(i) if i in nums else 'V' for i in range(a,b+1)]
print(expected)
def minimumSwaps(arr):
    ref_arr = sorted(arr)
    index_dict = {v: i for i,v in enumerate(arr)}
    swaps = 0
    
    for i,v in enumerate(arr):
        correct_value = ref_arr[i]
        if v != correct_value:
            to_swap_ix = index_dict[correct_value]
            arr[to_swap_ix],arr[i] = arr[i], arr[to_swap_ix]
            index_dict[v] = to_swap_ix
            index_dict[correct_value] = i
            swaps += 1
            
    return swaps


e=[1,3,4,2,6,5]
print(minimumSwaps(e))



arr=[1,3,4,2,6,5]
ref_arr = sorted(arr)
index_dict = {v: i for i,v in enumerate(arr)}
swaps = 0

for i,v in enumerate(arr):
    correct_value = ref_arr[i]
    if v != correct_value:
        to_swap_ix = index_dict[correct_value]
        arr[to_swap_ix],arr[i] = arr[i], arr[to_swap_ix]
        index_dict[v] = to_swap_ix
        index_dict[correct_value] = i
        swaps += 1
    print(arr)

arr=[1,3,4,2,6,5]

ind={v:j for j,v in enumerate(arr)}

print(ind)

for i in range(len(arr)):
  

# Python3 Program to find the smallest
# positive missing number


def solution(A): # Our original array

	m = max(A) # Storing maximum value
	if m < 1:

		# In case all values in our array are negative
		return 1
	if len(A) == 1:

		# If it contains only one element
		return 2 if A[0] == 1 else 1
	l = [0] * m
	for i in range(len(A)):
		if A[i] > 0:
			if l[A[i] - 1] != 1:

				# Changing the value status at the index of our list
				l[A[i] - 1] = 1
	for i in range(len(l)):

		# Encountering first 0, i.e, the element with least value
		if l[i] == 0:
			return i + 1
			# In case all values are filled between 1 and m
	return i + 2

# Driver Code
A = [0, 1, 2, -10, -20]
print(solution(A))



def firstMissingPositive(A):
    seen={}
    if(max(A)<1):
        return 1
    for ele in A:
        seen[ele]=True

    for i in range(1,len(A)+2): 
        if(i not in seen):
            return i 


A = [0, 1, 2, -10, -20]
print(firstMissingPositive(A))


seen={}

for ele in A:
    seen[ele]=True

for i in range(1,len(A)+2): 
  print(i)
def solution(S):
    occurrences = [0] * 26

    for i in range(len(S)):
        occurrences[ord(S[i]) - ord('a')] += 1

    best_char = 'a'
    best_res = 0

    for i in range(1, 26):
        if occurrences[i] >= best_res:
            best_char = chr(ord('a') + i)
            best_res = occurrences[i]

    return best_char



print(solution('dzzzzzzfdsddasasamatteroffactthisthingisffdsadsadsadasdsadsadasiwenttopickoninslasweekasdfghjklzxcvbnmeqweqweqweqwdasdasdasdasczdasdasdsadasdadasdasdasdasdasdasdasdasdazxxzxxscxsdsdsdsdsdsdsdsdzxzdsdsdsdsdszxca'))
import re

a='234\n er\n4 56\n'
s=[x for x in a.split("\n")]
f=''.join(s)
print(re.findall(r'\d+',f))
print(s)
S='zzzzzziwenttopickoninslasweekasdfghjklzxcvbnm'

occurrences = [0] * 26

for i in range(len(S)):
    occurrences[ord(S[i]) - ord('a')] += 1

best_char='a'
best_res=0
for i in range(1, 26):
    if occurrences[i] >= best_res:
        best_char = chr(ord('a') + i)
        best_res = occurrences[i]
print(best_res)
print(best_char)
print(occurrences)
print(ord('b'))
s = "i like this program very much"
words = s.split(' ')
string =[]
for word in words:
    string.insert(0,word)
 
print("Reversed String:")
print(" ".join(string))
#Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target
def twosum(nums=(6, 7, 11, 15, 3, 6, 5, 3), target=6):
    #lookup = dict(((v, i) for i, v in enumerate(nums)))
    lookup={v:i for i, v in enumerate(nums) }
    for i,v in enumerate(nums):
      if lookup.get(target-v,i)!=i:
        return  (i+1, lookup.get(target-v)+1)
        break

'''
    return next(( (i+1, lookup.get(target-v)+1) 
            for i, v in enumerate(nums) 
                if lookup.get(target-v, i) != i), None)
''' 

print(twosum())
matrix = [[1,2,3],[4,5,6],[7,8,9]]
for i in range(len(matrix)):
  for j in range(len(matrix[i])):
    print(matrix[i][j])
#recursive approach

def printdata(arr,i,j,m,n):
  '''
  arr
  i ,j :starting index of matrix, row
  m length of matrix
  n number of columns 

  '''

  if(i>=m or j>=n):
    return

  #print the first row
  for p in range(i,n):
    print(arr[i][p],end=" ")

  #print the last row

  for q in range(i+1,m):
    print(arr[q][n-1],end=" ")


  #print last row if last row and first row are not the same
  if ((m-1) != i):
    for p in range(n-2,j-1,-1):
      print(arr[m-1][p],end=" ")

  #print first column if first and last column are not the same
  if ((n-1)!=j):
    for p in range(m-2, i ,-1):
      print(arr[p][j],end=" ")

  printdata(arr,i + 1,j + 1,m - 1,n - 1)



# Driver code
R = 5
C = 4
arr = [[1, 2, 3, 4],
       [5, 6, 7, 8],
       [9, 10, 11, 12],
       [13, 14, 15, 16],
       [20, 21, 22, 23]
       ]


printdata(arr,0,0,R,C)



n=5
m=3

queries = [[1,2,100],[2,5,100],[3,4,100]]

#for _ in range(m):
  #   queries.append(list(map(int, queries.rstrip().split())))

#result = arrayManipulation(n, queries)

#fptr.write(str(result) + '\n')

#fptr.close()



arr = [0]*n
for i in queries:
      arr[i[0] - 1] += i[2]
      if i[1] != len(arr):
          arr[i[1]] -= i[2]
    
maxval = 0
itt = 0
print(arr)
for q in arr:
    itt += q
    if itt > maxval:
        maxval = itt
print(maxval)



def arrayManipulation(n, queries):
  arr = [0]*n
  '''for i in queries:
      arr[i[0] - 1] += i[2]
      arr[i[1]] -= i[2]
  '''
  for i in queries:
      arr[i[0] - 1] += i[2]
      if i[1] != len(arr):
          arr[i[1]] -= i[2]
  maxval = 0
  itt = 0
  print(arr)
  for q in arr:
      itt += q
      if itt > maxval:
          maxval = itt
  return maxval


arr=[1,3,4,2,6,5]
ref_arr = sorted(arr)
index_dict = {v: i for i,v in enumerate(arr)}

print(index_dict)

print(index_dict[1])
n = 5

m = 3

queries = [[1,2,100],[2,5,100],[3,4,100]]

#for _ in range(m):
  #   queries.append(list(map(int, queries.rstrip().split())))

#result = arrayManipulation(n, queries)

#fptr.write(str(result) + '\n')

#fptr.close()



arr = [0]*n
for i in queries:
    print(i[2])
r=[1,2,3,4,5,6]

print (r[::-1])

r=3
arr=[1,3,9,9,27,81,81]

map_arr = {}
map_doubles = {}
count = 0
# Traversing the array from rear, helps avoid division
for x in arr[::-1]:

    r_x = r*x
    r_r_x = r*r_x

    # case: x is the first element (x, x*r, x*r*r)
    count += map_doubles.get((r_x, r_r_x), 0)

    # case: x is the second element (x/r, x, x*r)
    map_doubles[(x,r_x)] = map_doubles.get((x,r_x), 0) + map_arr.get(r_x, 0)

    # case: x is the third element (x/(r*r), x/r, x)
    map_arr[x] = map_arr.get(x, 0) + 1


print(map_doubles)
print(map_arr)
print(count)
import collections

#from collections import defaultdict


queries=[[1, 5],[1, 6],[3, 2],[1, 10],[1, 10],[1, 6],[2, 5],[3, 2]]

results=[]
arr = dict()

freq = collections.defaultdict(int)
#freq=dict()

for x in queries:
    ops, value =x
    initial = arr.get(value,0)
    j=freq.get(value)
    #print(initial)
    #print(freq.get(value))
    if ops==3:
        #results.append[1 if freq.get(value)   else 0]
        if freq.get(value):
          results.append(1)
        else:
          results.append(0)

    #if 1==0:
      #do nothing
    if ops!=3:
        freq[initial]-=1
        if ops==1:
            arr[value]=initial+1
        elif ops==2 and initial:
            arr[value]-=1
    freq[arr.get(value,0)]+=1
#print(results)  



def freqQuery(queries):
    results = []
    lookup = dict()
    freqs = collections.defaultdict(set)
    for command, value in queries:
        freq = lookup.get(value, 0)
        if command == 1:
            lookup[value] = freq + 1
            freqs[freq].discard(value)
            freqs[freq + 1].add(value)
        elif command == 2:
            lookup[value] = max(0, freq - 1)
            freqs[freq].discard(value)
            freqs[freq - 1].add(value)
        elif command == 3:
            results.append(1 if freqs[value] else 0)
    print(freqs.items())
    
freqQuery(queries)    



import collections

dict = collections.defaultdict(list)
dict[1]=[1,2,3]
dict[2]=[4,5,6]

print (dict)

if dict.get(2) == True:
    print (True)
else:
    print (False)
import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(list)
for k, v in s:
  d[k].append(v)

print(d.items())
print(d['yellow'])
from collections import defaultdict


def ransom_note(magazine, ransom):
    dicty = defaultdict(int)
    for word in magazine:
        dicty[word]+=1
    for word in ransom: 
        if dicty[word]==0 : return False 
        dicty[word]-=1
    return True 


magazine=['two', 'times', 'three', 'is', 'not', 'four']
ransom=['two', 'times', 'two', 'is', 'four']
dicty = defaultdict(int)
for word in magazine:
    dicty[word]+=1
for word in ransom: 
    #if dicty[word]==0 : #return False 
    dicty[word]-=1

#print(dicty.items())
print(ransom_note(magazine, ransom))





def checkMagazine(magazine, ransom):
    dicty = defaultdict(int)
    for word in magazine:
        dicty[word]+=1
    for word in ransom: 
        if dicty[word]==0 : return 'No' 
        dicty[word]-=1
    return 'Yes' 


#bubble sort
a=[4,2,3,1]
numSwaps = 0

while True:
    SwapsFlag = False
    for i in range(len(a)-1):
        if a[i] > a[i+1]:
            a[i], a[i+1] = a[i+1], a[i]
            numSwaps += 1
            SwapsFlag = True
    if not SwapsFlag:
        break


print('Array is sorted in', numSwaps, 'swaps.')
print('First Element:', a[0])
print('Last Element:', a[-1])
#toys

def maximumToys(prices, k):
    prices.sort()
    count = 0
    for i in prices:
        if (i <= k):
            count += 1
            k -= i
        else:
            break
    return count


from functools import cmp_to_key
class Player:
    def __init__(self, name, score):
        self.name=name
        self.score=score
        
    def __repr__(self):
        return{'name':self.name,'age':self.score}
        
        
    def comparator(a, b):
        if a.score>b.score:
            return -1
        if a.score<b.score:
            return 1
        if a.name>b.name:
            return 1
        if a.score==b.score:
            if a.name>b.name:
                return 1
            elif a.name<b.name:
                return -1
            else:
                return 0
        

n = int(input())
data = []
for i in range(n):
    name, score = input().split()
    score = int(score)
    player = Player(name, score)
    data.append(player)
    
data = sorted(data, key=cmp_to_key(Player.comparator))
for i in data:
    print(i.name, i.score)
#---------------------------------------
# Merge Sort
#---------------------------------------
import sys

def merge_sort(A):
	merge_sort2(A, 0, len(A)-1)
	
def merge_sort2(A, first, last):
	if first < last:
		middle = (first + last)//2
		merge_sort2(A, first, middle)
		merge_sort2(A, middle+1, last)
		merge(A, first, middle, last)
		
def merge(A, first, middle, last):
	L = A[first:middle+1]
	R = A[middle+1:last+1]
	L.append(sys.maxsize)
	R.append(sys.maxsize)
	i = j = 0
	
	for k in range (first, last+1):
		if L[i] <= R[j]:
			A[k] = L[i]
			i += 1
		else:
			A[k] = R[j]
			j += 1
			
A = [5,9,1,2,4,8,6,3,7,55,78,99,109,32,28,16,567]
A = [9,5]
print(A)
merge_sort(A)
print(A)
def merge(a1, a2):
    swaps, i, j, result, m, n = 0, 0, 0, [], len(a1), len(a2)
    ra = result.append
    while i < m and j < n:
        if a1[i] <= a2[j]:
            ra(a1[i])
            i += 1
        else:
            ra(a2[j])
            j += 1
            swaps += m - i
    result += a1[i:]
    result += a2[j:]    
    return swaps, result
    
def msort(arr):
    n = len(arr)
    mid = n // 2
    if n > 1:
        left_swaps, left_result = msort(arr[:mid])
        right_swaps, right_result = msort(arr[mid:])
        m_swaps, result = merge(left_result, right_result)
        return m_swaps + left_swaps + right_swaps, result
    return 0,arr


print(msort([9,5])[0])
d=7
a=[1,2,3,4,5]




new_idx = d % len(a)
print(new_idx)
print(a[:new_idx]+a[new_idx:])


def rotLeft(a, d):
    new_idx = d % len(a)
    return a[new_idx:] + a[:new_idx]



a=[1,2,3,4,5]



print(sum(a[0:2]))


a=[1,2,3,4,5]

A=[1,2,3,4,5]
for i in reversed(range(len(A))):
  print(i)

  



arr=[[1, 1, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0],
[0, 0, 2, 4, 4, 0],
[0, 0, 0, 2, 0, 0],
[0, 0, 1, 2, 4, 0]
]

count = -64
#row = 1
#col = 1
for row in range(1,4):
  for col in range(1,4):
    temp = arr[row][col] + arr[row][col+1]+arr[row][col+2]+arr[row+1][col+1] + arr[row+2][col]+arr[row+2][col+1]+ arr[row+2][col+2]
    if temp > count:
        count = temp
print(count)
def hourglassSum(arr):
    count = -64
    for row in range(1,4):
        for col in range(1,4):
            temp = arr[row][col] + arr[row][col+1]+arr[row][col+2]+arr[row+1][col+1] + arr[row+2][col]+arr[row+2][col+1]+ arr[row+2][col+2]
            if temp > count:
                count = temp
    return count



def hourglassSum(arr):
    count = -64
    row = 0
    col = 0
    while row < 4 :
        temp = arr[row][col] + arr[row][col+1]+arr[row][col+2]+arr[row+1][col+1] + arr[row+2][col]+arr[row+2][col+1]+ arr[row+2][col+2]
        if temp > count:
            count = temp
        col +=1
        if col == 4:
            col = 0
            row +=1
    return count

s='tried'
for i, char in enumerate(s[1:]):
  print(char,i)
  
def substrCount(n, s):
    count = 0

    prevprevChar, prevprevCount = None, 0
    prevChar, prevCount = None, 0
    currentChar, currentCount = None, 0

    for char in s:
        if char != currentChar:
            prevprevChar, prevprevCount = prevChar, prevCount
            prevChar, prevCount = currentChar, currentCount
            currentChar, currentCount = char, 0

        currentCount += 1
        count += currentCount

        if prevCount == 1 and prevprevChar == currentChar and currentCount <= prevprevCount:
            count += 1

    return count


s='aadaada'

count = 0

prevprevChar, prevprevCount = None, 0
prevChar, prevCount = None, 0
currentChar, currentCount = None, 0

for char in s:
    if char != currentChar:
        prevprevChar, prevprevCount = prevChar, prevCount
        prevChar, prevCount = currentChar, currentCount
        currentChar, currentCount = char, 0

    currentCount += 1
    count += currentCount

    print(char,currentChar,prevChar,prevprevChar)
    print(currentCount,prevCount,prevprevCount)
def number_needed(str1, str2):
    
    dict_chars = dict()
    
    for char in str1:
        if char in dict_chars:
            dict_chars[char] += 1
        else:
            dict_chars[char] = 1
    for char in str2:
        if char in dict_chars:
            dict_chars[char] -= 1
        else:
            dict_chars[char] = -1
    
    sum_diff = 0
    
    for char in dict_chars.keys():
        sum_diff += abs(dict_chars[char])
        
    return sum_diff
    
a = input().strip()
b = input().strip()

print(number_needed(a, b))
def luckBalance(k, contests):
    # sort from greatest luck to least luck
    contests.sort(reverse=True)
    luck = 0

    for contest in contests:
        if contest[1] == 0:
            luck += contest[0]
        elif k > 0:
            luck += contest[0]
            k -= 1
        else:
            luck -= contest[0]

    return luck
import collections
from collections import defaultdict
s='eggegg'
res = collections.defaultdict(int)
for char in s:
    res[char] += 1


remain_chars = dict(res)

print(remain_chars)
print(res)
from collections import Counter



s='eggegg'
t = s[::-1] # s reversed so we can search fowards not backwards
half_sc = Counter({char:count//2 for char, count in Counter(s).items()}) # half of s's chars
print(half_sc)
print(Counter(s).items())
# Complete the minimumAbsoluteDifference function below.
def minimumAbsoluteDifference(arr):
    min_abs_diff = sys.maxsize
    tmp_result = 0
    arr.sort()
    for i in range (len(arr) - 1):
        tmp_result = abs(arr[i] - arr[i + 1])
        if tmp_result < min_abs_diff:
            min_abs_diff = tmp_result
    return min_abs_diff


a=[1,5,3,4,2]
myDict = {item : 1 for index, item in enumerate(a)}
print(myDict)

'''
count = 0
for each in myDict:
    if each + 1 in myDict:
        count += 1
print(count)
'''
print(set(a) & set([item + 1 for item in set(a)]))
print(len(set(a) & set([item + 1 for item in set(a)])))




# Complete the pairs function below.
def pairs(k, arr):
    return len(set(arr) & set([item + k for item in set(arr)]))
def triplets(a, b, c):
    a = list(sorted(set(a)))
    b = list(sorted(set(b)))
    c = list(sorted(set(c)))
    
    ai = 0
    bi = 0
    ci = 0
    
    ans = 0
    
    while bi < len(b):
        while ai < len(a) and a[ai] <= b[bi]:
            ai += 1
        
        while ci < len(c) and c[ci] <= b[bi]:
            ci += 1
        
        ans += ai * ci
        bi += 1
    
    return ans
print(5//2)
def minTime(machines, goal):

    machines.sort()

    low_rate = machines[0]
    lower_bound = (goal // (len(machines) / low_rate))
    high_rate = machines[-1]
    upper_bound = (goal // (len(machines) / high_rate)) + 1

    while lower_bound < upper_bound:

        num_days = (lower_bound + upper_bound) // 2
        total = getNumItems(machines, goal, num_days)
        if total >= goal:
            upper_bound = num_days
        else:
            lower_bound = num_days + 1

    return int(lower_bound)


def getNumItems(machines, goal, num_days):

    total = 0

    for machine in machines:
        total += (num_days // machine)

    return total


machines=[2,3,2]
goal=10
#print(minTime(machines,goal))



machines.sort()

low_rate = machines[0]
lower_bound = (goal // (len(machines) / low_rate))
high_rate = machines[-1]
upper_bound = (goal // (len(machines) / high_rate)) + 1


print(low_rate)
print(high_rate)
print(lower_bound)
print(upper_bound)

print(10//1.5)
print(10//(3/3))
def maximumSum(a, m):
    prefixSum = [(a[0] % m, 1)]
    for i in xrange(1,len(a)):
        prefixSum.append(((prefixSum[i-1][0] + a[i] % m) % m, i+1))
    prefixSum.sort()
    loopMin = m
    for i in xrange(len(prefixSum)-1):
        if prefixSum[i][1] > prefixSum[i+1][1] and prefixSum[i+1][0] - prefixSum[i][0] < loopMin:
            loopMin = prefixSum[i+1][0] - prefixSum[i][0]
    return max(prefixSum[-1][0], m-loopMin)



#read about prefixSum
def whatFlavors(cost, money):
    remains = dict()
    for index, c in enumerate(cost):
        if c not in remains:
            remains[money - c] = index + 1
        else:
            print(str(remains[c])+' '+str(index + 1))

whatFlavors([1,2,3,4,5],5)


def maxSubsetSum(arr):
    dp = dict()# key : max index of subarray, value = sum
    dp[0], dp[1] = arr[0], max(arr[0], arr[1])
    for i, num in enumerate(arr[2:], start=2):
        dp[i] = max(dp[i-1], dp[i-2]+num, dp[i-2], num)
    print(dp)


maxSubsetSum([-2,1,3,-4,5])


def majorityElement(A):
    count={}
    for i in A:
        count[i]=count.get(i,0)+1
        
        if count[i]>len(A)//2:
            return i

print(majorityElement([2,1,2,1]))

def candy(A):
    
    candies=[1]*len(A)
    
    for i in range(1,len(A)):
        if A[i]==A[i-1]:
            continue
        elif A[i]>A[i-1] and candies[i]<=candies[i-1]:
            candies[i]=candies[i-1]+1
            
        else:
            j= i -1
            while( j>=0 and A[j] > A[j+1] and candies[j]<=candies[j+1]  ):
                candies[j] = candies[j+1] + 1
                j-=1
                
    
    return(sum(candies))


print(candy([1,5,2,1]))
# Function to calculate nth Fibonacci number
def fib(n, lookup):
  
    # Base case
    if n == 0 or n == 1 :
        lookup[n] = n
  
    # If the value is not calculated previously then calculate it
    if lookup[n] is None:
        lookup[n] = fib(n-1 , lookup)  + fib(n-2 , lookup) 
  
    # return the value corresponding to that value of n
    return lookup[n]
# end of function
  
# Driver program to test the above function
def main():
    n = 4 
    # Declaration of lookup table
    # Handles till n = 100 
    lookup = [None]*(101)
    print ("Fibonacci Number is ", fib(n, lookup))
  
if __name__=="__main__":
    main()

A=[2,1,2,1]
count={}
for i in A:
    count[i]=count.get(i,0)+1

print(count)
        
# Definition for a binary tree node.
class TreeNode:
     def __init__(self, val=0, left=None, right=None):
         self.val = val
         self.left = left
         self.right = right

'''
class Node:
 
    # Utility function to create new node
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
'''
def isMirror(root1, root2):
    # If both trees are empty, then they are mirror images
        if root1 is None and root2 is None:
            return True

        """ For two trees to be mirror images,
            the following three conditions must be true
            1 - Their root node's key must be same
            2 - left subtree of left tree and right subtree
              of the right tree have to be mirror images
            3 - right subtree of left tree and left subtree
               of right tree have to be mirror images
        """
        if (root1 is not None and root2 is not None):
            if root1.val == root2.val:
                return (isMirror(root1.left, root2.right)and
                        isMirror(root1.right, root2.left))

        # If none of the above conditions is true then root1
        # and root2 are not mirror images
        return False
    
class Solution:
    #def isSymmetric(self, root: TreeNode) -> bool:
    
 
 
    def isSymmetric(self, root: TreeNode) -> bool:

        # Check if tree is mirror of itself
        return isMirror(root, root)
        

# Driver Code
# Let's construct the tree show in the above figure
root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(4)
root.right.right = Node(3)
#print ("Symmetric" if isSymmetric(root) == True else "Not symmetric")


print(vars(root.left))
# Definition for a binary tree node.
# class TreeNode:
def __init__(self, val=0, left=None, right=None):
    self.val = val
    self.left = left
    self.right = right
    
       
    
    
class Solution:
    def minDepth(self, root: TreeNode) -> int:
        #corner case
        if root is None:
            return 0
         
            
        #initialize queue 
        q=[]
        
        q.append({'node':root, 'depth':1})
        
        while (len(q)>0):
            
            #Remove the front queue item
            
            queueItem = q.pop()
            
            #Get details of the removed item
            node=queueItem['node']
            depth=queueItem['depth']
            
            #if this the first leaf node so far return the depth
            
            if (node.left is None and node.right is None) or (node.left =='null' and node.right=='null'):
                return depth
            
            
            #if left subtree is not none add it to queue
            
            if node.left is not None:
                q.append({'node' : node.left, 'depth' : depth+1})
                
            #if right subtree is non none add it to queue    
            if node.right is not None:
                q.append({'node' : node.right, 'depth':depth+1})
def foo(iteration=0):
    if iteration >= 5:    ###
        return            ### dont call foo. stop the recursion
    print(f"spam number {iteration}")
    foo(iteration+1)
    print("exiting foo")


foo() ### start
print("finished")




#print("equal" if isequal(1,10)==True else "not equal")
t=1
def find(index,w):
    s=''
    temp=w[index]
    for x in range(len(w)-1,-1,-1):
        if(w[x]>temp):
            break
    s=(w[0:index]+w[x]+ ''.join(sorted( w[index+1:x]+temp+w[x+1:]))).strip()
    print(s)
for i in range(t):
    w='dkhc'
    index=0
    flag=1
    if(sorted(w,reverse=True)==[k for k in w]):
          print("no answer")
    elif(len(w)==2):
        print(w[::-1])
    else:
        for j in range(len(w)-2,0,-1):
            if(w[j]<w[j+1]):
                index=j
                find(index,w)
                flag=0
                break
            else:
                index=j-1
        if(flag==1):

            find(index,w)
w='dkhc'



for j in range(len(w)-2,0,-1):
    if(w[j]<w[j+1]):
        index=j
        #find(index,w)
        print(index)
        flag=0
        break
    else:
        index=j-1

        print(index)






def deckOfCards(cards, pair): # sde 3 amazon

  result = []
  result.append(pair)
  for i in cards:
    if i == pair:
      continue
    pair = result[-1] # get the last item of the list
    if i[0] == pair[0] or i[1] == pair[1]:
      result.append(i)

  return result


cards = [["H", 3], ["H", 4], ["S", 4], ["D", 5], ["D", 1]]
pair = ["H",3]
print(deckOfCards(cards,pair))
def deckofcards(cards,pair):

  result=[]

  result.append(pair)

  for i in cards:
    if i == pair:
      continue

    pair=result[-1]

    if (i[0]==pair[0] or i[1]==pair[1]):
      result.append(i)

  return(result)
    
    

cards=[["H",3],["H",4],["S",4],["D",5],["D",1]]

pair=["H",3]


print(deckofcards(cards,pair))


#remove duplicate strings


w='abccdeffgghhi'

#create list of zeroes for the 26 characters

flag=[0]*26
#print(flag)

#create an empty list to store the result

result=""

#iterate thru the string from right to left, if flag is zero then we are encountering this for the first time
#if flag is 1 then this character has been encountered before
'''
for i in range (len(w)):
  if flag[ord(w[i])-ord('a')]!=1:
    #result.append(w[i])
    result+=(w[i])
    flag[ord(w[i])-ord('a')]=1
'''

for ch in w:
  if flag[ord(ch)-ord('a')]==0:
    result+=ch
    flag[ord(ch)-ord('a')]=1

print(result)



print(ord('a'))

print(ord('b')- ord('a'))
A, B = [4, -1, 0, 3],  [-2, 5, 0, 3]

for i in range(1, len(A)):
    A[i] += A[i - 1]
    B[i] += B[i - 1]




print(A)


print(B)<jupyter_output>[4, 3, 3, 6]
[-2, 3, 3, 6]
{'fraction_non_alphanumeric': 0.15710382513661203, 'fraction_numerical': 0.034242100261344735, 'mean_word_length': 2.4610956932881076, 'pattern_counts': {'":': 1, '<': 31, '<?xml version=': 0, '>': 44, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '393101', 'license': 'MIT', 'n_tokens_mistral': 13601, 'n_tokens_neox': 12630, 'n_words': 3360, 'path': 'oop.ipynb', 'repo_name': 'xonmaina/Classical-Piano-Composer', 'size': '33672'}