Oct-10-2020, 03:40 AM
(This post was last modified: Oct-10-2020, 03:40 AM by Drone4four.)
So I’ve been learning about symmetric differences between lists which can be accomplished in a number of different ways using for loops, list comprehension, sets the exclusive or carat. Pretty neat stuff.
Now I am exploring recursion. Wrapping my head around this programming concept is difficult because it’s like a whole different paradigm. Haskell apparently doesn’t have any loops. If you need to iterate over a list, Haskell programmers call a function from within a function. w3schools address function recursion in Python and so does programiz using factorials as an example but the sample code in both tutorials escape my understanding.
Could someone here re-write the for loops (below) but using recursion?
Say I want to create a list of multiples of 2 up to 16. Here is the desired output:
There are many ways of doing this in Python. Here are two:
Now I am exploring recursion. Wrapping my head around this programming concept is difficult because it’s like a whole different paradigm. Haskell apparently doesn’t have any loops. If you need to iterate over a list, Haskell programmers call a function from within a function. w3schools address function recursion in Python and so does programiz using factorials as an example but the sample code in both tutorials escape my understanding.
Could someone here re-write the for loops (below) but using recursion?
Say I want to create a list of multiples of 2 up to 16. Here is the desired output:
Quote:[0, 4, 8, 12, 16]
There are many ways of doing this in Python. Here are two:
>>> S = [2*n for n in range(0,9) if ( (n % 2) == 0)] >>>print(S)And:
>>> def multiples_of_four(n): ... newlist = [] ... for n in range(0,n*2): ... if n % 4 == 0: ... newlist.append(n) ... return newlist ... >>> multiples_of_four(9)That’s great. But how might experienced Python developers such as all of you achieve the same output but by using recursion?