From 8978dde1df849e908a1304e4abc244f2ca86b5bc Mon Sep 17 00:00:00 2001 From: piyushP7pravin Date: Tue, 21 Jul 2020 23:25:28 +0530 Subject: [PATCH] Add Recursion --- data_structures/Recursion/Check AB.py | 49 +++++++++++++++++ .../Recursion/Check Number in Array.py | 52 ++++++++++++++++++ .../Recursion/Check Palindrome (recursive).py | 42 +++++++++++++++ data_structures/Recursion/Count Zeros.py | 42 +++++++++++++++ .../Recursion/First Index of Number.py | 47 ++++++++++++++++ data_structures/Recursion/Geometric Sum.py | 34 ++++++++++++ .../Recursion/Last Index Of Number.py | 53 +++++++++++++++++++ .../Recursion/Multiplication (Recursive).py | 46 ++++++++++++++++ data_structures/Recursion/Pair star.py | 38 +++++++++++++ .../Recursion/Power Of A Number.py | 38 +++++++++++++ .../Remove Duplicates Recursively.py | 40 ++++++++++++++ data_structures/Recursion/Remove X.py | 32 +++++++++++ data_structures/Recursion/Staircase.py | 38 +++++++++++++ .../Recursion/String to Integer.py | 37 +++++++++++++ data_structures/Recursion/Sum Of Array.py | 42 +++++++++++++++ .../Recursion/Sum of digits (recursive).py | 36 +++++++++++++ .../Recursion/Tower Of Hanoi - Problem.py | 52 ++++++++++++++++++ 17 files changed, 718 insertions(+) create mode 100644 data_structures/Recursion/Check AB.py create mode 100644 data_structures/Recursion/Check Number in Array.py create mode 100644 data_structures/Recursion/Check Palindrome (recursive).py create mode 100644 data_structures/Recursion/Count Zeros.py create mode 100644 data_structures/Recursion/First Index of Number.py create mode 100644 data_structures/Recursion/Geometric Sum.py create mode 100644 data_structures/Recursion/Last Index Of Number.py create mode 100644 data_structures/Recursion/Multiplication (Recursive).py create mode 100644 data_structures/Recursion/Pair star.py create mode 100644 data_structures/Recursion/Power Of A Number.py create mode 100644 data_structures/Recursion/Remove Duplicates Recursively.py create mode 100644 data_structures/Recursion/Remove X.py create mode 100644 data_structures/Recursion/Staircase.py create mode 100644 data_structures/Recursion/String to Integer.py create mode 100644 data_structures/Recursion/Sum Of Array.py create mode 100644 data_structures/Recursion/Sum of digits (recursive).py create mode 100644 data_structures/Recursion/Tower Of Hanoi - Problem.py diff --git a/data_structures/Recursion/Check AB.py b/data_structures/Recursion/Check AB.py new file mode 100644 index 00000000..8194fae8 --- /dev/null +++ b/data_structures/Recursion/Check AB.py @@ -0,0 +1,49 @@ +""" +---------------------------------------------- Check AB ---------------------------------------- + +Suppose you have a string, S, made up of only 'a's and 'b's. Write a recursive function that checks +if the string was generated using the following rules: + a. The string begins with an 'a' + b. Each 'a' is followed by nothing or an 'a' or "bb" + c. Each "bb" is followed by nothing or an 'a' +If all the rules are followed by the given string, return true otherwise return false. + +#### Input format : + String S + +#### Output format : + 'true' or 'false' + +#### Constraints : + 0 <= |S| <= 1000 + where |S| represents length of string S. + +#### Sample Input 1 : + abb +#### Sample Output 1 : + true + +#### Sample Input 2 : + abababa +#### Sample Output 2 : + false +""" + +def checkAB(str) : + if(len(str) == 0): + return True + + if(str[0] == 'a') : + if(len(str[1:]) > 1 and str[1:3] == 'bb') : + return checkAB(str[3:]) + else: + return checkAB(str[1:]) + else : + return False + +# Main +str=input() +if(checkAB(str)): + print("true") +else: + print("false") \ No newline at end of file diff --git a/data_structures/Recursion/Check Number in Array.py b/data_structures/Recursion/Check Number in Array.py new file mode 100644 index 00000000..41fb8eab --- /dev/null +++ b/data_structures/Recursion/Check Number in Array.py @@ -0,0 +1,52 @@ +""" +------------------------------------ Check Number in Array --------------------------------------------- + +Given an array of length N and an integer x, you need to find if x is present in the array or not. +Return true or false. + +Do this recursively. + +#### Input Format : + Line 1 : An Integer N i.e. size of array + Line 2 : N integers which are elements of the array, separated by spaces + Line 3 : Integer x + +#### Output Format : + 'true' or 'false' + +#### Constraints : + 1 <= N <= 10^3 + +#### Sample Input 1 : + 3 + 9 8 10 + 8 +#### Sample Output 1 : + true + +#### Sample Input 2 : + 3 + 9 8 10 + 2 +#### Sample Output 2 : + false +""" + +def checkNumber(arr, x): + size=len(arr) + if size == 1: + return x==arr[0] + + smallAns = checkNumber(arr[:size-1], x) + return smallAns or (x==arr[size-1]) + +# Main +from sys import setrecursionlimit +setrecursionlimit(11000) +n=int(input()) +arr=list(int(i) for i in input().strip().split(' ')) +x=int(input()) +if checkNumber(arr, x): + print('true') +else: + print('false') diff --git a/data_structures/Recursion/Check Palindrome (recursive).py b/data_structures/Recursion/Check Palindrome (recursive).py new file mode 100644 index 00000000..ebde7c8e --- /dev/null +++ b/data_structures/Recursion/Check Palindrome (recursive).py @@ -0,0 +1,42 @@ +""" +---------------------------- Check Palindrome (recursive) ----------------------------- + +Check whether a given String S is a palindrome using recursion. Return true or false. + +#### Input Format : + String S + +#### Output Format : + 'true' or 'false' + +#### Constraints : + 0 <= |S| <= 1000 + where |S| represents length of string S. + +#### Sample Input 1 : + racecar +#### Sample Output 1: + true + +#### Sample Input 2 : + ninja +#### Sample Output 2: + false +""" + +def RcheckPalindrome(str): + size=len(str) + if size <= 1: + return True + if str[0]!=str[size-1]: + return False + return RcheckPalindrome(str[1:-1]) + +# Main +from sys import setrecursionlimit +setrecursionlimit(11000) +str=input() +if RcheckPalindrome(str): + print('true') +else: + print('false') \ No newline at end of file diff --git a/data_structures/Recursion/Count Zeros.py b/data_structures/Recursion/Count Zeros.py new file mode 100644 index 00000000..7039b51d --- /dev/null +++ b/data_structures/Recursion/Count Zeros.py @@ -0,0 +1,42 @@ +""" +-------------------------------------- Count Zeros ------------------------------------------- + +Given an integer N, count and return the number of zeros that are present in the given integer using recursion. + +#### Input Format : + Integer N + +#### Output Format : + Number of zeros in N + +#### Constraints : + 0 <= N <= 10^9 + +#### Sample Input 1 : + 10204 +#### Sample Output 1 : + 2 + +#### Sample Input 2 : + 708000 +#### Sample Output 2 : + 4 +""" + +def countZeros(n): + if n<0: + n *= -1 # Make n positive + if n<10: + if n == 0: + return 1 + return 0 + smallAns = countZeros(n // 10) + if n%10==0: + smallAns += 1 + return smallAns + +# Main +from sys import setrecursionlimit +setrecursionlimit(11000) +n=int(input()) +print(countZeros(n)) \ No newline at end of file diff --git a/data_structures/Recursion/First Index of Number.py b/data_structures/Recursion/First Index of Number.py new file mode 100644 index 00000000..73df86dd --- /dev/null +++ b/data_structures/Recursion/First Index of Number.py @@ -0,0 +1,47 @@ +""" +-------------------------------------- First Index of Number ----------------------------------------------- + +Given an array of length N and an integer x, you need to find and return the first index of integer x present +in the array. Return -1 if it is not present in the array. + +First index means, the index of first occurrence of x in the input array. +Do this recursively. Indexing in the array starts from 0. + +#### Input Format : + Line 1 : An Integer N i.e. size of array + Line 2 : N integers which are elements of the array, separated by spaces + Line 3 : Integer x + +#### Output Format : + first index or -1 + +#### Constraints : + 1 <= N <= 10^3 + +#### Sample Input : + 4 + 9 8 10 8 + 8 +#### Sample Output : + 1 +""" + +def firstIndex(arr, x): + size=len(arr) + if size <= 0: + return -1 + if x==arr[0]: + return 0 + smallAns = firstIndex(arr[1:], x) + if smallAns == -1: + return -1 + else: + return smallAns+1 + +# Main +from sys import setrecursionlimit +setrecursionlimit(11000) +n=int(input()) +arr=list(int(i) for i in input().strip().split(' ')) +x=int(input()) +print(firstIndex(arr, x)) \ No newline at end of file diff --git a/data_structures/Recursion/Geometric Sum.py b/data_structures/Recursion/Geometric Sum.py new file mode 100644 index 00000000..a939057e --- /dev/null +++ b/data_structures/Recursion/Geometric Sum.py @@ -0,0 +1,34 @@ +""" +----------------------- Geometric Sum --------------------------- + +Given k, find the geometric sum i.e. +1 + 1/2 + 1/4 + 1/8 + ... + 1/(2^k) +using recursion. + +#### Input format : + Integer k + +#### Output format : + Geometric sum + +#### Constraints : + 0 <= k <= 1000 + +#### Sample Input 1 : + 3 +#### Sample Output 1 : + 1.875 + +#### Sample Input 2 : + 4 +#### Sample Output 2 : + 1.93750 +""" +def gp(k): + if k<0: + return 0 + return 1/(2**k) + gp(k-1) + +# Main +k=int(input()) +print("%.5f"%gp(k)) \ No newline at end of file diff --git a/data_structures/Recursion/Last Index Of Number.py b/data_structures/Recursion/Last Index Of Number.py new file mode 100644 index 00000000..58b412f4 --- /dev/null +++ b/data_structures/Recursion/Last Index Of Number.py @@ -0,0 +1,53 @@ +""" +----------------------------------------- Last Index Of Number --------------------------------------------- + +Given an array of length N and an integer x, you need to find and return the last index of integer x present in +the array. Return -1 if it is not present in the array. +Last index means - if x is present multiple times in the array, return the index at which x comes last in the +array. + +You should start traversing your array from 0, not from (N - 1). +Do this recursively. Indexing in the array starts from 0. + +#### Input Format : + Line 1 : An Integer N i.e. size of array + Line 2 : N integers which are elements of the array, separated by spaces + Line 3 : Integer x + +#### Output Format : + last index or -1 + +#### Constraints : + 1 <= N <= 10^3 + +#### Sample Input : + 4 + 9 8 10 8 + 8 +#### Sample Output : + 3 +""" + +def lastIndex(arr, x): + + size=len(arr) + if size <= 0: + return -1 + + smallAns = lastIndex(arr[1:], x) + + if smallAns == -1: + if x==arr[0]: + return 0 + else: + return -1 + else: + return smallAns+1 + +# Main +from sys import setrecursionlimit +setrecursionlimit(11000) +n=int(input()) +arr=list(int(i) for i in input().strip().split(' ')) +x=int(input()) +print(lastIndex(arr, x)) \ No newline at end of file diff --git a/data_structures/Recursion/Multiplication (Recursive).py b/data_structures/Recursion/Multiplication (Recursive).py new file mode 100644 index 00000000..802ec7af --- /dev/null +++ b/data_structures/Recursion/Multiplication (Recursive).py @@ -0,0 +1,46 @@ +"""" +----------------------------------- Multiplication (Recursive) ------------------------------------------- + +Given two integers M & N, calculate and return their multiplication using recursion. You can only use subtraction +and addition for your calculation. No other operators are allowed. + +#### Input format : + Line 1 : Integer M + Line 2 : Integer N + +#### Output format : + M x N + +#### Constraints : + 0 <= M <= 1000 + 0 <= N <= 1000 + +#### Sample Input 1 : + 3 + 5 +#### Sample Output 1 : + 15 + +#### Sample Input 2 : + 4 + 0 +#### Sample Output 2 : + 0 +""" + +def multiplyNumbers(m, n): + if m==0 or n==0: + return 0 + if n>0: + smallAns = multiplyNumbers(m,n-1) + return smallAns + m + else: + smallAns = multiplyNumbers(m,n+1) + return smallAns - m + +# Main +from sys import setrecursionlimit +setrecursionlimit(11000) +m=int(input()) +n=int(input()) +print(multiplyNumbers(m,n)) \ No newline at end of file diff --git a/data_structures/Recursion/Pair star.py b/data_structures/Recursion/Pair star.py new file mode 100644 index 00000000..d924c6c5 --- /dev/null +++ b/data_structures/Recursion/Pair star.py @@ -0,0 +1,38 @@ +""" +-------------------------------------------- Pair star ----------------------------------------- + +Given a string S, compute recursively a new string where identical chars that are adjacent in the original +string are separated from each other by a "*". + +#### Input format : + String S + +#### Output format : + Modified string + +#### Constraints : + 0 <= |S| <= 1000 + where |S| represents length of string S. + +#### Sample Input 1 : + hello +#### Sample Output 1: + hel*lo + +#### Sample Input 2 : + aaaa +#### Sample Output 2 : + a*a*a*a +""" + +def pair_star(s,start,end): + if start==end: + return s[start] + if s[start]==s[start+1]: + return s[start]+"*"+pair_star(s,start+1,end) + else: + return s[start]+pair_star(s,start+1,end) + +# Main +s=input() +print(pair_star(s,0,len(s)-1)) diff --git a/data_structures/Recursion/Power Of A Number.py b/data_structures/Recursion/Power Of A Number.py new file mode 100644 index 00000000..0ad3cab0 --- /dev/null +++ b/data_structures/Recursion/Power Of A Number.py @@ -0,0 +1,38 @@ +""" +----------------------------------------- Power Of A Number --------------------------------------------- + +Write a program to find x to the power n (i.e. x^n). Take x and n from the user. You need to print the answer. + +Note : For this question, you can assume that 0 raised to the power of 0 is 1 + +#### Input format : + Two integers x and n (separated by space) + +#### Output Format : + x^n (i.e. x raise to the power n) + +#### Constraints: + 0 <= x <= 8 + 0 <= n <= 9 + +#### Sample Input 1 : + 3 4 +#### Sample Output 1 : + 81 + +#### Sample Input 2 : + 2 5 +#### Sample Output 2 : + 32 +""" + + +def power(x,n): + if n==0: + return 1 + return x*power(x,n-1) + +li=[int(i) for i in input().split()] +x=li[0] +n=li[1] +print(power(x,n)) diff --git a/data_structures/Recursion/Remove Duplicates Recursively.py b/data_structures/Recursion/Remove Duplicates Recursively.py new file mode 100644 index 00000000..4373ec21 --- /dev/null +++ b/data_structures/Recursion/Remove Duplicates Recursively.py @@ -0,0 +1,40 @@ +""" +----------------------------- Remove Duplicates Recursively -------------------------- + +Given a string S, remove consecutive duplicates from it recursively. + +#### Input Format : + String S +#### Output Format : + Output string + +#### Constraints : + 1 <= |S| <= 10^3 + where |S| represents the length of string + +#### Sample Input 1 : + aabccba +#### Sample Output 1 : + abcba + +#### Sample Input 2 : + xxxyyyzwwzzz +#### Sample Output 2 : + xyzwz +""" + +def removeConsecutiveDuplicates(string): + + if len(string)<=1: + return string + + string2 = removeConsecutiveDuplicates(string[1:]) + + if string[0]==string[1]: + return string2 + else: + return string[0]+string2 + +# Main +string = input().strip() +print(removeConsecutiveDuplicates(string)) \ No newline at end of file diff --git a/data_structures/Recursion/Remove X.py b/data_structures/Recursion/Remove X.py new file mode 100644 index 00000000..27bdb416 --- /dev/null +++ b/data_structures/Recursion/Remove X.py @@ -0,0 +1,32 @@ +""" +-------------------------------------- Remove X ------------------------------------- + +Given a string, compute recursively a new string where all 'x' chars have been removed. + +#### Input format : + String S +#### Output format : + Modified String +#### Constraints : + 1 <= |S| <= 10^3 + where |S| represents the length of string S. +#### Sample Input 1 : + xaxb +#### Sample Output 1: + ab +#### Sample Input 2 : + abc +#### Sample Output 2: + abc +""" + +def removeX(string): + if len(string)==0: + return string + if string[0]=='x': + return removeX(string[1:]) + return string[0]+removeX(string[1:]) + +# Main +string = input() +print(removeX(string)) \ No newline at end of file diff --git a/data_structures/Recursion/Staircase.py b/data_structures/Recursion/Staircase.py new file mode 100644 index 00000000..015b011b --- /dev/null +++ b/data_structures/Recursion/Staircase.py @@ -0,0 +1,38 @@ +"""" +-------------------------------------------- Staircase ---------------------------------------------- + +A child is running up a staircase with N steps, and can hop either 1 step, 2 steps or 3 steps at a time. +Implement a method to count how many possible ways the child can run up to the stairs. You need to return +number of possible ways W. + +#### Input format : + Integer N + +#### Output Format : + Integer W + +#### Constraints : + 1 <= N <= 30 + +#### Sample Input 1 : + 4 +#### Sample Output 1 : + 7 + +#### Sample Input 2 : + 5 +#### Sample Output 2 : + 13 +""" + +def staircase(n): + if(n<3): + return n + if(n==3): + return 4 + return staircase(n-1)+staircase(n-2)+staircase(n-3) + +# Main +n=int(input()) +count=staircase(n) +print(count) diff --git a/data_structures/Recursion/String to Integer.py b/data_structures/Recursion/String to Integer.py new file mode 100644 index 00000000..7e29bfef --- /dev/null +++ b/data_structures/Recursion/String to Integer.py @@ -0,0 +1,37 @@ +""" +--------------------------------------- String to Integer -------------------------------------------- + +Write a recursive function to convert a given string into the number it represents. That is input will +be a numeric string that contains only numbers, you need to convert the string into corresponding integer +and return the answer. + +#### Input format : + Numeric string S (string, Eg. "1234") + +#### Output format : + Corresponding integer N (int, Eg. 1234) + +#### Constraints : + 0 <= |S| <= 9 + where |S| represents length of string S. + +#### Sample Input 1 : + 1231 +#### Sample Output 1 : + 1231 + +#### Sample Input 2 : + 12567 +#### Sample Output 2 : + 12567 +""" + +def string_int(s,end): + if end==0: + return ord(s[0])-48 + b=ord(s[end])-48 + return b + 10*string_int(s,end-1) + +# Main +s=input() +print(string_int(s,len(s)-1)) \ No newline at end of file diff --git a/data_structures/Recursion/Sum Of Array.py b/data_structures/Recursion/Sum Of Array.py new file mode 100644 index 00000000..b1e5085e --- /dev/null +++ b/data_structures/Recursion/Sum Of Array.py @@ -0,0 +1,42 @@ +""" +--------------------------------------- Sum Of Array ------------------------------------------ + +Given an array of length N, you need to find and return the sum of all elements of the array. +Do this recursively. + +#### Input Format : + Line 1 : An Integer N i.e. size of array + Line 2 : N integers which are elements of the array, separated by spaces + +#### Output Format : + Sum + +#### Constraints : + 1 <= N <= 10^3 + +#### Sample Input 1 : + 3 + 9 8 9 +#### Sample Output 1 : + 26 + +#### Sample Input 2 : + 3 + 4 2 1 +#### Sample Output 2 : + +""" + +def sumArray(arr): + n=len(arr) + if(n == 1): + return arr[0] + smallAns = sumArray(arr[:n-1]) + return smallAns + arr[n-1] + +# Main +from sys import setrecursionlimit +setrecursionlimit(11000) +n=int(input()) +arr=list(int(i) for i in input().strip().split(' ')) +print(sumArray(arr)) \ No newline at end of file diff --git a/data_structures/Recursion/Sum of digits (recursive).py b/data_structures/Recursion/Sum of digits (recursive).py new file mode 100644 index 00000000..69307bd3 --- /dev/null +++ b/data_structures/Recursion/Sum of digits (recursive).py @@ -0,0 +1,36 @@ +""" +---------------------------- Sum of digits (recursive) ---------------------------- + +Write a recursive function that returns the sum of the digits of a given integer. + +#### Input format : + Integer N + +#### Output format : + Sum of digits of N + +#### Constraints : + 0 <= N <= 10^9 + +#### Sample Input 1 : + 12345 +#### Sample Output 1 : + 15 + +#### Sample Input 2 : + 9 +#### Sample Output 2 : + 9 +""" + +def sumOfDigits(n): + if n == 0: + return 0 + smallAns = sumOfDigits(n // 10) + return smallAns + n%10 + +# Main +from sys import setrecursionlimit +setrecursionlimit(11000) +n=int(input()) +print(sumOfDigits(n)) \ No newline at end of file diff --git a/data_structures/Recursion/Tower Of Hanoi - Problem.py b/data_structures/Recursion/Tower Of Hanoi - Problem.py new file mode 100644 index 00000000..610ba50e --- /dev/null +++ b/data_structures/Recursion/Tower Of Hanoi - Problem.py @@ -0,0 +1,52 @@ +""" +--------------------------------------- Tower Of Hanoi - Problem ------------------------------------------------ + +Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to +move all disks from source rod to destination rod using third rod (say auxiliary). + +The rules are : + 1) Only one disk can be moved at a time. + 2) A disk can be moved only if it is on the top of a rod. + 3) No disk can be placed on the top of a smaller disk. + +Print the steps required to move n disks from source rod to destination rod. + +Source Rod is named as 'a', auxiliary rod as 'b' and destination rod as 'c'. + +#### Input Format : + Integer n +#### Output Format : + Steps in different lines (in one line print source and destination rod name separated by space) + +#### Constraints : + 0 <= n <= 20 + +#### Sample Input 1 : + 2 +#### Sample Output 1 : + a b + a c + b c + +#### Sample Input 2 : + 3 +#### Sample Output 2 : + a c + a b + c b + a c + b a + b c + a c +""" + +def towerofhanoi(n, source, aux, dest): + if n<=0: + return + towerofhanoi(n-1, source, dest, aux) + print(source, dest) + towerofhanoi(n-1, aux, source, dest) + +# Main +n=int(input()) +towerofhanoi(n, 'a', 'b', 'c')