Recursion, Iterators & Generators

Recursion is defined in terms of itself or of its type and is used in a variety of disciplines. Mostly used in mathematics and computer science, where a function being defined is applied within its own definition.

#Recursion Example1

Nums = [2,4,6,8,10]

def Nums_sum(Nums):
    if len(Nums) == 0:
        return 0
    First_Value = Nums[0]
    Rest_Values = Nums[1:]
    return First_Value + Nums_sum(Rest_Values)

print("Recursion Example1 result: ", Nums_sum(Nums))
#Recursion Example2

def fun(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fun(n - 1) + fun(n - 2)

res = fun(25)
print("Recursion Example2 result: ",res)
#Recursion Example3
snake = {1:2, 2:6, 3:9, 4:12, 5:15, 6:18, 7:21, 8:24, 9:27, 10:30}

elems = list(snake.values())
elems.reverse()
print("Recursion Example3 result: ", elems)

print("Recursion Example3 loop result: ")
for x in range(len(elems)-3):
    print(elems[x]*elems[x+1])
results

Iterator – an object that allows sequential access to all elements or parts contained in another object, usually a container or list.

#Iter Example1

days = ("monday", "tuesday","wednesday" ,"thursday", "friday", "saturday", "sunday")
it_days = iter(days)
print(next(it_days))
print(next(it_days))
print(next(it_days))
print(next(it_days))
print(next(it_days))
print(next(it_days))
#Iter Example2
nums = (1,2,3)
it_nums = iter(nums)

print(next(it_nums))
print(next(it_nums))
print(next(it_nums))
#Iter Example2 modified
class Nums:
    def __iter__(self):
        self.x = 1
        return self
    def __next__(self):
        if self.x < 4:
            y = self.x
            self.x +=1
            return y
        else:
            raise StopIteration

Nums_vals = Nums()
NumsIt = iter(Nums_vals)

for i in NumsIt:
    print(i)

Generators familiar with iterators, allow to create functions returning successive values ​​from a certain sequence. With directive yield let the generator to pause until it is retrieved values ​​by the next function.

#Gen Example1
def Nums(val):
    x = 1
    score = 2
    while x <= val:
        yield score
        x +=1
        score = x**3

for i in Nums(3):
    print(i)
result
#Gen Example2
def Nums(val):
    x = 1
    score = 1
    while x <= val:
        yield score
        x +=1
        score = x*2

for i in Nums(5):
    print(i)
result

How about this:

for n in [i for i in range ( 10 ) if i % 2 == 0 ]:
    print (n)