Beruflich Dokumente
Kultur Dokumente
Gps object-> should contain coordinates, when Generally, Recursion is a method where the
location change happens, should update people solution to a problem is based on solving
who needs to read info. Interface/core idea of smaller instances of the same problem.
gps
Powerful approach for complicated problems
Button->want to contain some text to label,
Ex: factorial=fact(n)
know if button got clicked (click event), once
clicked way to arrange action(behavior) 5! Is 5x4x3x2x1
Action=Behavior/status in object fact(n)=n x fact(n-1)
Recursion (ch15) could write for loop
Recursion is a way of programming or coding a but more complicated topics could be used with
problem, in which a function calls itself one or recursion
more times in its body
for loop faster, but some concepts not possible
Usually, it is returning the return value of this to solve without recursion
function call
recursion should finish at some point
If a function definition fulfils the condition of
recursion, we call this function a recursive if write function:
function
def factorial(n):
Termination condition: if n == 1:
return 1
A recursive function has to terminate to be used else:
in a program return n*factorial(n-1)
A recursive function terminates, if with every
before call function, need to make sure n is
recursive call the solution of the problem is
positive integer, don’t want to start a negative
downsized and moves towards a base case
integer
A base case is a case, where the problem can be trust factorial will take care of problem
solved without further recursion
factorial(4) goes to else and will return n times
A recursion can lead to an infinite loop, if the factorial (4-1)
base case is not met in the calls. returns 4 x factorial (3)
for i in range(1,10):
print(mult3(i))
Solution to our second exercise:
def sum_n(n):
if n== 0:
return 0
else:
return n + sum_n(n-1)
Solution for creating the Pacal triangle:
def pascal(n):
if n == 1:
return [1]
else:
line = [1]
previous_line = pascal(n-1)
for i in range(len(previous_line)-1):
line.append(previous_line[i] +
previous_line[i+1])
line += [1]
return line
print(pascal(6))
Alternatively, we can write a function using list
comprehension:
def pascal(n):
if n == 1:
return [1]
else:
p_line = pascal(n-1)
line = [ p_line[i]+p_line[i+1] for i in
range(len(p_line)-1)]