0% found this document useful (0 votes)
51 views5 pages

Int Fact (Int X) (If (X 1) Return 1 Else Return N Fact (n-1) )

Document 1 discusses recursion, including an example of a recursive factorial function, advantages like reducing code length and disadvantages like increased memory usage and slower speed compared to iterative functions. Document 2 presents a recursive algorithm to check if a string represents a multiple of 3. Document 3 describes using recursion to calculate subtree sums in a tree data structure by traversing nodes depth-first.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views5 pages

Int Fact (Int X) (If (X 1) Return 1 Else Return N Fact (n-1) )

Document 1 discusses recursion, including an example of a recursive factorial function, advantages like reducing code length and disadvantages like increased memory usage and slower speed compared to iterative functions. Document 2 presents a recursive algorithm to check if a string represents a multiple of 3. Document 3 describes using recursion to calculate subtree sums in a tree data structure by traversing nodes depth-first.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

1.

a)
int fact(int x)
{
if (x = 1)
return 1;
else
return n*fact(n-1);
}

1.b.) Advantages of Recursion:


1. Reduces unnecessary calling of function.
2. It is extremely useful when applying the same solution.
3. Recursion reduces the length of the code.
4. It is very useful in solving the data structure problem.

Disadvantages of Recursion:
1. They are generally slower than non-recursive functions.
2. It requires a lot of memory space to hold intermediate results on the system
stacks.
3. It is inefficient in terms of space and time complexity.
4. The computer will run out of memory if the recursive calls are not properly
checked.

2.)
def isMultiple3(c, size):
     
    state = '0'
     
    for i in range(size):
         
                digit = c[i]
         
                if state == '0':
            if (digit == '1'):
                state = '1'
         
               
        elif state == '1':
            if (digit == '0'):
                state = '2'
            else:
                state = '0'
         
          
        elif state == '2':
            if (digit == '0'):
                state = '1'
   
       if (state == '0'):
        return True
         
    return False
 
if __name__=="__main__":
     
        size = 5;
  
    
    c = [ '1', '0', '1', '0', '1']
  
        if (isMultiple3(c, size)):
        print("YES")
    else:
        print("NO")

3.)
p = []
adj = [0] * 10000
for i in range(10000):
    adj[i] = []
subtree_sum, visit, visit2 = [0] * 10000, [0] * 10000, [0] * 10000
 
def dfs1(root: int) -> int:
 
        if len(adj[root]) == 0:
 
       
        p[root][0] += p[root][1]
        return 0
 
    summ = 0
    for i in range(len(adj[root])):
        if visit[adj[root][i]] == 0:
            dfs1(adj[root][i])
 
            p[root][1] += p[adj[root][i]][1]
            visit[adj[root][i]] = 1
 
    p[root][0] += p[root][1]
 
    return 0
 
def dfs2(root: int) -> int:
    if len(adj[root]) == 0:
 
        
        subtree_sum[root] = p[root][0]
        return p[root][0]
 
    summ = p[root][0]
 
    for i in range(len(adj[root])):
        if visit2[adj[root][i]] == 0:
            summ += dfs2(adj[root][i])
            visit2[adj[root][i]] = 1
 
    
    subtree_sum[root] = summ
    return summ
 
if __name__ == "__main__":
 
    nodes, m, qu = 7, 4, 5
    a = [0, 1, 2, 2, 2, 1, 2]
 
        p.append([0, 0])
 
    for i in range(nodes):
        if a[i] != 0:
            adj[a[i]].append(i + 1)
 
                p.append([0, 0])
 
    v = []
    v.append(("ADD", [6, 76]))
    v.append(("ADDUP", [1, 49]))
    v.append(("ADD", [4, 48]))
    v.append(("ADDUP", [2, 59]))
 
    for i in range(m):
        s = v[i][0]
        a = v[i][1][0]
        b = v[i][1][1]
 
        if s == "ADD":
 
            p[a][0] += b
        else:
 
            
            p[a][1] += b
 
       dfs1(1)
 
        dfs2(1)
 
    q = []
    q.append(["VALTREE", 1])
    q.append(["VALTREE", 5])
    q.append(["VAL", 5])
    q.append(["VALTREE", 2])
    q.append(["VAL", 2])
    for i in range(qu):
        s = q[i][0]
        a = q[i][1]
 
        if s == "VAL":
            print(p[a][0])
        else:
            print(subtree_sum[a])

4.)
from collections import defaultdict

class Graph:

def __init__(self, num_of_v):


self.num_of_v = num_of_v
self.edges = defaultdict(list)

def add_edge(self, u, v):


self.edges[u].append(v)

class Subset:
def __init__(self, parent, rank):
self.parent = parent
self.rank = rank

def find(subsets, node):


if subsets[node].parent != node:
subsets[node].parent = find(subsets, subsets[node].parent)
return subsets[node].parent

def union(subsets, u, v):

if subsets[u].rank > subsets[v].rank:


subsets[v].parent = u
elif subsets[v].rank > subsets[u].rank:
subsets[u].parent = v

else:
subsets[v].parent = u
subsets[u].rank += 1

def isCycle(graph):

subsets = []

for u in range(graph.num_of_v):
subsets.append(Subset(u, 0))

for u in graph.edges:
u_rep = find(subsets, u)

for v in graph.edges[u]:
v_rep = find(subsets, v)

if u_rep == v_rep:
return True
else:
union(subsets, u_rep, v_rep)

g = Graph(3)

g.add_edge(0, 1)

g.add_edge(1, 2)

g.add_edge(0, 2)

if isCycle(g):
print('Graph contains cycle')
else:
print('Graph does not contain cycle')

5.) Option 4

6.) Option 3

7.) def reverse(str, k):

if k == len(str):

return

reverse(str, k + 1)

print(str[k], end='')

if _name_ == '_main_':

str = "“Mukesh Patel School of Technology Management and Engineering"

print("Reverse of the given string is", end=' ')

reverse(str, 0)

You might also like