Python Practice Recursion Patterns

In this class, We do Python Practice Recursion Patterns.

For Complete YouTube Video: Click Here

The examples discussed are significantly helpful for the reader to improve coding skills.

These examples are helpful to crack any campus placement exam.

Check the question given below. Try to solve on your own. Then check for solutions for better practice.

Q1)
# what is the output of the code given below
def func(var1,var2):
    count=0
    if var1==0:
        count+=var2//2
        return 0
    elif var1%2:
        return count+func(var1//2,2*var2)+var2
    else:
        count+=2
        return count+func(var1//2,2*var2)-var2
print(func(20,1))

The above program is working on the recursion concept.

The ‘if’ condition is used to stop the recursion. The condition is given var1==0.

The program is recursively calling the function till var1 ==0.

Suppose the value in var1 is even. The ‘else if’ condition will be true. Then call the function again by dividing the variable var1 with 2. and multiplying var2 with 2.

If the value in var1 is odd, then else part will get executed.

The final output displayed by the program is 15.

The concept of recursion with examples. Click here.

Q2)
What is the pattern displayed by the below code?
def displaypattern(num):
    ch=65
    for i in range(1,num+1):
        prin=ch
        for j in range(1,i+1):
            char=chr(prin)
            print(char,end=" ")
            prin+=1
        print()
displaypattern(5)

In the above example, the integer value is converted to a character using the chr function.

The program taking value 65. and converted it to the character.

The ASCII value of 65 is A.

Each time it went into the first for loop. The value 65 is assigned to the variable prin.

The second for loop is converting the prin value to the character and displaying.

The value in the variable prin is incremented.

So the output displayed by the second program is shown below.

A 
A B 
A B C 
A B C D 
A B C D E