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)

Catch The Error

When we meet an error or an exception while our code is running, Python will normally stop and generate an error message in red.
We can handle it using try, if statement, except & raise our own error methodology.

Example #1

lucky_nums = [9,66,12,89,21,46,90]
print(lucky_nums[10])

We will get an error message, that mifght be not clear for us or final user:

lucky_nums = [9,66,12,89,21,46,90]
print(lucky_nums)
min = 0
try:
    lucky_nums[10]
except IndexError:
    print('list index out of range')
much better 🙂
lucky_nums = [9,66,12,89,21,46,90]
print(lucky_nums)
min = 0
try:
    lucky_nums(10)
except IndexError:
    print('list index out of range')
except Exception as Ex:
    print('Warning',Ex,type(Ex))
else:
    print("good shot! this is your lucky number!")

Example #2

Let’s create a simple functions at first.

def Login(FirstName, LastName, BDate):
    return '{}{}{}'.format(FirstName[0:3],LastName[0:4],BDate[2:])

FirstName = input("First Name: ")
LastName = input("Last Name: ")
BDate = input ("Year of Birth: ")

print("Login: ", Login(FirstName,LastName,BDate))

Inside we need to declare possible error that we might get while someone put wrong Name, Surname or Year:

class WrongInputs(Exception):
    pass
def Login(FirstName, LastName, BDate):
    try:
        Login_FirstName = FirstName[0]
    except:
        raise WrongInputs("Incorrect Name")
    if len(LastName) <1:
        raise WrongInputs("Incorrect Surname")
    Login_FirstName = LastName[0]
    if not BDate.isnumeric():
        raise WrongInputs("Incorrect Value for Year of Birth")
    Login_Bdate = BDate[0]

    return '{}{}{}'.format(FirstName[0:3], LastName[0:4], BDate[2:])

FirstName = input("First Name: ")
LastName = input("Last Name: ")
BDate = input ("Year of Birth: ")
try:
    print("Login: ", Login(FirstName, LastName, BDate))
except WrongInputs as Ex:
    print("Error while Login creating: ",Ex)
except IndexError:
    print('list index out of range')