Python Material Installation Dokumentation PythonKara Grundlagen Namensräume Funktionen Testen Strings Dictionary Listen Zeitmessungen Zufall Bits+Bytes Module Sockets xml serielle Schnittstelle Python in HTML Turtle xturtle Tkinter OOP Threads Zusicherungen exe Patterns GnuPlot Goto MySQL CGI Dateien Exceptions Grafik Mathematik Fischertechnik Unicode funktional Iterator Sound C Debugger regex Pfade Docstrings Django Bluetooth format Bytecode signal
Pfad: Startseite / Fächer / Informatik / Python / Zusicherungen
Autor: mk
06.06.2008 15:23
1155
Zusicherungen

Beispiel 1

Das Beispiel zeigt, dass die fehlende Typvereinbarung in Python mehr als wettgemacht werden kann. Wenn eine Zusicherung verletzt ist, wird ein Laufzeitfehler (AssertionError) ausgelöst.

# -*- coding: iso-8859-1 -*-
# Autor: Klaus Merkert, Datum: 6.6.08

def primfac(zahl):
    # ---------- Vorbedingung -------------
    assert (type(zahl) == int) and zahl > 0
    # -------------------------------------
    n = zahl
    F = []
    while n%2 == 0:
        F.append(2)
        n = n/2
    while n%3 == 0:
        F.append(3)
        n = n/3
    t = 5
    diff = 2
    while t*t <= n:
        while n%t == 0:
            F.append(t)
            n = n/t
        t = t + diff
        diff = 6 - diff
    if n > 1:
        F.append(n)
    # ---------- Nachbedingung ------------
    p = 1
    for i in F:
        p = p*i
    assert p == zahl
    # -------------------------------------
    return F

if __name__ == '__main__':
    print primfac(6936)
    print primfac(-42)

Links

Valid XHTML 1.0! lokal