Skip to content

PW_14

Dec To Bin

python
def dec_to_bin(dec: int) -> str:
    if dec < 2:
        return str(dec)
    return dec_to_bin(dec // 2) + str(dec % 2)

def bin_to_dec(biny: str) -> int:
    assert check_bin(biny)
    if len(biny) == 1:
        return int(biny)
    return int(biny[0]) * 2 ** (len(biny) - 1) + bin_to_dec(biny[1:])

def check_bin(bin: str) -> bool:
    for c in bin:
        if c != '0' and c != '1':
            return False
    return True

print(dec_to_bin(25))
print(bin_to_dec("11001"))

Dichotomy

python
def recu_dico(l : list, x : int, shift = 0):
  if len(l) <= 1:
    return None
  else:
    mid = (len(l) - 1) // 2
    if l[mid] == x:
      return mid + shift
    else:
      if x > l[mid]:
        return recu_dico(l[(mid + 1):], x, mid + 1)
      else:
        return recu_dico(l[:mid], x, 0)
      
print(recu_dico([1, 5, 6, 6, 9, 12], 3))
print(recu_dico([1, 5, 6, 6, 9, 12], 9))
print(recu_dico([1, 5, 6, 6, 9, 12], 6))

# This look slike a "linear" function, as you execute 3 
# comparison on each turn. And we now we execute log2(n)
# turns, so here is the cost I guess...

Snowflaxes

Info

This was the last exercice of an IT Mi-Partiel in 2024

python
from turtle import forward, left, right, speed, up, goto, done, down

def vonKoch(n: int, x:int) -> None:
    if n == 0:
        forward(x)
    else:
        vonKoch(n-1, x//3)
        left(60)
        vonKoch(n-1, x//3)
        right(120)
        vonKoch(n-1, x//3)
        left(60)
        vonKoch(n-1, x//3)

def KnochSnowflaxes(n : int, x : int) -> None:
    for i in range(3):
        vonKoch(n, x)
        right(120)

n = 6 #int(input("DEEEEEP"))
x = 1000 #int(input("size :)"))

speed(0)
up()
goto(- x / 2, x / 3.5)
down()
KnochSnowflaxes(n, x)
done()

Released under the GPL-3.0 License.