Skip to content

Commit 78cb20c

Browse files
authored
recursion problems (#361)
* pairs of integers whose sum is equal to number. find all pairs of integers whose sum is equal to a given number. * permutation if two strings are in permutation , they have the same characters but in different order. * add two sorted linked list add two sorted linked list and the new linked list too will be sorted. * recursion problems recursion problems
1 parent e8f8fc3 commit 78cb20c

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

Python/5 recusrion problems.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# 1..TO FIND FACTORIAL OF A NUMBER USING RECURSION
2+
3+
def factorial(n):
4+
assert n>=0 and int(n)==n , "the number must be positive integer only"
5+
if n==0 or n==1:
6+
return 1
7+
else:
8+
return n*factorial(n-1)
9+
10+
print(factorial(4))
11+
12+
13+
14+
15+
16+
# 2..TO PRINT FIBONACCI SERIES
17+
18+
def fibonacci(n):
19+
assert n>=0 and int(n)==n , "only positive integers"
20+
if n==0 or n==1:
21+
return n
22+
else:
23+
return fibonacci(n-1) + fibonacci(n-2)
24+
25+
print(fibonacci(8))
26+
27+
28+
29+
30+
31+
# 3.. TO FIND IF THE GIVEN STRING IS PALINDROME OR NOT
32+
33+
def isPalindrome(strng):
34+
if len(strng)==0:
35+
return True
36+
if strng[0]==strng[-1]:
37+
return isPalindrome(strng[1:-1])
38+
39+
else:
40+
return False
41+
print((isPalindrome('naman')))
42+
43+
44+
45+
46+
# 4..TO FIND THE SUM OF ALL DIGITS IN THE GIVEN NUMBER
47+
48+
def sum(n):
49+
assert n>=0 and int(n)==n , "only positive integers"
50+
if n==0:
51+
return 0
52+
else:
53+
return int(n%10) + sum(int(n//10))
54+
55+
print(sum(11))
56+
57+
58+
59+
60+
# 5..TO FIND THE POWER OF A NUMBER
61+
62+
def power(base,exp):
63+
assert exp>=0 and int(exp)==exp , "power can only be positive integers"
64+
if(exp==0):
65+
return 1
66+
if(exp==1):
67+
return base
68+
else:
69+
return base*power(base,exp-1)
70+
71+
print(power(2,5))

0 commit comments

Comments
 (0)