Skip to main content

Command Palette

Search for a command to run...

[TIL] Algorithms Day 11 - Recursion, Sort

03/17/23

Updated
View as Markdown
[TIL] Algorithms Day 11 - Recursion, Sort

Problem 1. Hanoi Tower - Recursion

n = int(input())

def hanoi(n, start, mid, target):
    if n == 1: # we can count the steps here
        print(start, target)
        return

    hanoi(n-1, start, target, mid) # move 1st to (n-1)nd disks to mid
    hanoi(1, start, mid, target) # move the largest disk to target
    hanoi(n-1, mid, start, target) # move disks in mid to target

# the total number of actions are in consistent permutation with the following formula
print(2**n-1)
hanoi(n, 1, 2, 3)

Problem 2. Coordinate - sort()

n = int(input())
list = []
for _ in range(n):
    ilst.append(list(map(int, input().split())))

list.sort(key=lambda x: (x[1], x[0])) # sort by y-axis first, but if the values of y-axis are the same, sort by x-axis
for x, y in list:
    print(x, y)

Problem 3. Statistics - sort()

import collections

n = int(input())
num_lst = []
for _ in range(n):
    num_lst.append(int(input()))
num_lst.sort() # python uses Timsort which is derived from merge sort and insertion sort => O(n*logn)

# Average
print(round(sum(num_lst) / n))

# Median (the number of values are always odd in this problem)
print(num_lst[n//2])

# Most common value
most = collections.Counter(num_lst).most_common() # printing list with tuples (val, num_of_val_counted)
if len(most) > 1 and most[0][1] == most[1][1]: # if there are multiples, print the second smallest value in most commons
    print(most[1][0])
else:
    print(most[0][0])

# Range
print(num_lst[-1]-num_lst[0])
# Different ways to get average
from statistics import mean
avg = mean(num_list)

from numpy import mean
avg = mean(num_list)

# Different way to get median
# What is median: the value in the middle when the list sorted, so it doesn't need to care about the dramatically bigger or smaller values relatively
from numpy import median
print(median([100, 200, 400, 1000000])) # 300, if the number of values is even, it brings the average of the two values in the middle

Today I Learned

Part 1 of 50

Today I Learned!