Extra: periodieke tshirt

Deze pagina bevat uitvoerbare code.

Periodieke tshirt

Opdracht: Periodieke tshirt

De gegeven code uit de opgave:

ELEMENTS = (
    "H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni "
    "Cu Zn Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I "
    "Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os Ir Pt "
    "Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr "
    "Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og"
).split()

Stap 1: is_element(s)

def is_element(s):
    """Geeft True als s, zonder op hoofdletters te letten, een elementsymbool is."""
    return s in [symbol.lower() for symbol in ELEMENTS]


assert is_element("k") == True
assert is_element("kr") == True
assert is_element("a") == False
assert is_element("an") == False

Stap 2: can_spell(word)

De tweede keuze controleert eerst of het woord minstens twee letters heeft. Anders zou word[:2] het hele woord van één letter zijn, en die keuze is dan al de eerste.

def can_spell(word):
    """Geeft True als word te maken is met symbolen van elementen."""
    if word == "":  # basisgeval
        return True

    one = is_element(word[:1]) and can_spell(word[1:])
    two = len(word) >= 2 and is_element(word[:2]) and can_spell(word[2:])
    return one or two


assert can_spell("kranten") == True
assert can_spell("spuwers") == True
assert can_spell("caesar") == True
assert can_spell("uitdaging") == False
assert can_spell("kaas") == False
assert can_spell("") == True

Stap 3: count_spellings(word)

def count_spellings(word):
    """Geeft het aantal manieren om word te maken met symbolen van elementen."""
    if word == "":  # basisgeval
        return 1

    one = 0
    if is_element(word[:1]):
        one = count_spellings(word[1:])

    two = 0
    if len(word) >= 2 and is_element(word[:2]):
        two = count_spellings(word[2:])

    return one + two


assert count_spellings("kranten") == 1
assert count_spellings("spuwers") == 2
assert count_spellings("basis") == 3
assert count_spellings("sinas") == 5
assert count_spellings("uitdaging") == 0
assert count_spellings("") == 1