Iteration und Rekursion am Beispiel von "2 hoch n"
This commit is contained in:
parent
b281d61fb5
commit
7906360a15
29
algorithmen/iteration_rekursion_exp2.py
Normal file
29
algorithmen/iteration_rekursion_exp2.py
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
|
||||||
|
# Iteration
|
||||||
|
|
||||||
|
def exp2(n):
|
||||||
|
""" Berechne "2 hoch n" über eine Schleife
|
||||||
|
"""
|
||||||
|
if n == 0:
|
||||||
|
return 1
|
||||||
|
else:
|
||||||
|
result = 1
|
||||||
|
for i in range(n): # Die Berechnung erfolgt in einer Schleife
|
||||||
|
result = result * 2
|
||||||
|
print(result)
|
||||||
|
return result
|
||||||
|
|
||||||
|
# Rekursion
|
||||||
|
def exp2rek(n):
|
||||||
|
""" Berechne "2 hoch n" über Rekursiven Aufruf
|
||||||
|
"""
|
||||||
|
if n == 0:
|
||||||
|
return 1
|
||||||
|
else:
|
||||||
|
result = exp2rek(n-1) * 2 # Die Funktion ruft sich selbst wieder auf
|
||||||
|
print(result)
|
||||||
|
return result
|
||||||
|
|
||||||
|
exp2(20)
|
||||||
|
print("-"*10)
|
||||||
|
exp2rek(20)
|
Loading…
Reference in New Issue
Block a user