├── 2.py ├── 1.py ├── 25.py ├── 29.py ├── 27.py ├── 28.py ├── 30.py ├── 9.py ├── GeeksForGeeks ├── Remove Spaces.py ├── Sort in descending.py ├── Contest │ ├── Geek and the equation.py │ ├── Adjacent Equal.py │ ├── Game of Function.py │ ├── Geek and the base.py │ ├── Out the Kth.py │ ├── Maximum Simultaneous Difference.py │ ├── Pick the one.py │ ├── K Frequent.py │ ├── Prime Sum.cpp │ ├── One in the Matrix.cpp │ ├── Count Students.py │ ├── geeks and lockers.py │ ├── Reach top of stair.py │ └── Unknown Sort.py ├── Rotate Array.py ├── Nth root of M.py ├── Reverse Words in a given string.py ├── Bit Difference.py ├── Series GP.py ├── Sorting │ ├── Binary Array Sorting.py │ ├── Check if an array is sorted.py │ ├── Bubble Sort.py │ ├── Selection Sort.py │ ├── Insertion Sort.py │ ├── Sort an array of 0s ,1s and 2s.py │ ├── Quick Sort.py │ ├── Triplet Family.py │ ├── Count the triplets.py │ ├── Sorting Elements of an Array by Frequency.py │ ├── Minimum Swaps to Sort.cpp │ ├── Triplet Sum in Array.py │ ├── Merge Sort.py │ ├── Sort the Half Sorted.py │ └── Relative Sorting.py ├── Recursive │ ├── Permutations of string.py │ ├── Handshakes.py │ ├── Possible words from Phone digits.py │ ├── Print Pattern.py │ ├── Tower of Hanoi.py │ ├── Josephus problem.py │ └── Flood Fill Algorithm.cpp ├── Day of the week.py ├── Trailing zeroes in factorial.py ├── Searching │ ├── Missing number in array.py │ ├── Last index of One.py │ ├── Number of occurrence.py │ ├── Find Transition Point.py │ ├── Searching a number.py │ ├── Square root.py │ ├── Floor in a Sorted Array.py │ ├── Binary Search.py │ ├── Facing the sun.py │ ├── Common elements.py │ ├── Smallest Positive missing number.cpp │ ├── Missing element of AP.py │ ├── Magnet Array Problem.py │ ├── Search in a Rotated Array.py │ └── Peak element.py ├── Amazon │ ├── k largest elements.py │ ├── Maximum value in a bitonic array.py │ ├── Single Number.cpp │ ├── Check set bits.cpp │ ├── Longest consecutive subsequence.py │ ├── Count Substrings.py │ ├── Addition of submatrix.py │ ├── Count the elements.py │ └── Largest number in K swaps.cpp ├── Find duplicates in an array.py ├── Nearest Multiple of 10.py ├── Count Squares.py ├── Unit Digit.py ├── Longest palindromic substring.py ├── Palindrome String.py ├── Swap two nibbles in a byte.py ├── Excel Column Names.py ├── Matrix │ ├── Print Matrix in snake Pattern.py │ ├── Median In a Row-Wise sorted Matrix.py │ ├── Transpose of Matrix.py │ ├── Row with max 1s.cpp │ ├── Count zeroes in a sorted matrix.py │ ├── Boolean Matrix Problem.py │ ├── Row with minimum number of 1's.py │ ├── Search in a matrix.py │ ├── Spirally traversing a matrix.py │ └── Count pairs Sum in matrices.cpp ├── Pair cube count.py ├── nCr Practice.py ├── Implement strstr.py ├── Minimum distance between two numbers.py ├── Perfect Numbers.py ├── URLify a given string.py ├── Pattern Matcher.py ├── String Rotations.py ├── Add two fractions.py ├── GCD of Array.py ├── Maximum Index.py ├── Sorted subsequences of size 3.py ├── Hashing │ ├── Count pairs with given sum.py │ ├── Non-Repeating Element.py │ ├── Largest Fibonacci Subsequence.py │ ├── First element to occur k times.py │ ├── Count distinct pairs with difference k.py │ ├── Group Anagrams Together.py │ ├── In First But Second.py │ ├── Frequencies of Limited Range Array Elements.py │ ├── Find Distinct elements.py │ ├── Key Pair.py │ ├── Winner of an election.py │ ├── Nuts and Bolts Problem.py │ ├── Array Subset of another array.py │ ├── A Simple Fraction.py │ └── Check if two arrays are equal or not.py ├── Check for Subsequence.py ├── Count Smaller elements.py ├── Longest Consecutive Subsequence.py ├── Wave Array.py ├── Sum of all prime numbers between 1 and N.py ├── Leaders in an array.py ├── The Game of Digits.py ├── Fibonacci.py ├── Sieve of Eratosthenes.py ├── Majority Element.py ├── Weigh the strings.py ├── Closest Number.py ├── Extract Maximum.py ├── Anagram.py ├── Angle.py ├── Alternating elements.py ├── Nth Even Fibonacci Number.py ├── Square.py ├── Largest prime factor.py ├── Find k-th character in string.py ├── Pairs of prime number.py ├── Sum of numbers in string.py ├── Triangular Number.py ├── Anagram Palindrome.py ├── Add Binary Strings.py ├── Swap and Maximize.cpp ├── Merge two strings.py ├── Pair with given sum in a sorted array.py ├── Trapping Rain Water.py ├── Anagram of String.py ├── Rearrange Array Alternately.py ├── Longest substring.py ├── Product array puzzle.py ├── Three way partitioning.py ├── Find Missing and Repeating.java ├── K-anagrams.py ├── Overlapping rectangles.py ├── Inversions.py ├── Non Repeating Character.py ├── Save Ironman.py ├── Max sum path in two arrays.py ├── Majority_Element.py ├── Median.py ├── First repeated character.py ├── Chocolate Distribution Problem.py ├── Uncommon Characters.py ├── 3 Divisors.py ├── Stock buy and sell.py ├── Bitonic Array.py ├── Longest Substring.py ├── Maximum SubArray.py ├── The great one.py └── Good or Bad string.py ├── Itertools ├── Compress the String! ├── itertools.product() ├── itertools.permutations() ├── Maximize it ! ├── itertools.combinations() ├── itertools.combinations_with_replacement() └── Iterables and Iterators ├── 6.py ├── 11.py ├── Collections ├── Company Logo.py ├── Word Order.py ├── DefaultDict.py ├── Collections.namedtuple().py ├── collections.Counter().py ├── Collections.OrderedDict().py ├── Collections.dequeue().py └── Piling Up!.py ├── 5.py ├── 22.py ├── 17.py ├── Date And Time ├── Calendar Module.py └── Time Delta.py ├── Automate the boring stuff with python ├── 2_control_flow │ └── exitExample.py ├── 5_Dictionaries_and_Structuring_Data │ ├── CharacterCount.py │ ├── prettyCharacterCount.py │ └── Fantasy Game Inventory.py ├── 4_List │ ├── Comma Code.py │ ├── Character Picture Grid.py │ └── Use of copy function.py ├── 6_Manipulating_Strings │ ├── picnicTable.py │ ├── bulletPointAdder.py │ ├── Table Printer.py │ └── pw.py ├── Pattern_Matching_With_Regular_Expressions │ ├── Regex Version of strip().py │ ├── isPhoneNumber.py │ ├── Strong Password DEtection.py │ └── phoneAndEmail.py └── 3_Function │ ├── The Collatz Sequence.py │ └── Guess the number game.py ├── 4.py ├── 21.py ├── 24.py ├── 12.py ├── 15.py ├── 18.py ├── 26.py ├── LeetCode ├── Palindrome Number.py ├── Integer to Roman.py ├── Roman To Integer.py ├── Two Sum.py ├── Longest Substring Without Repeating Characters.py ├── Median of Two Sorted Arrays.py ├── Array │ ├── Search Insert Position.py │ ├── Combination Sum.py │ ├── Search in Rotated Sorted Array.py │ └── Next Permutation.py ├── Longest Common Prefix.py ├── Regular Expression Matching.py ├── Letter Combinations of a Phone Number.py ├── Container With Most Water.py ├── Valid Parentheses.py ├── 3Sum Closest.py ├── Merge Two Sorted Lists.py ├── ZigZag Conversion.py ├── Reverse Integer.py ├── 4Sum.py └── Add Two Numbers.py ├── 23.py ├── 32.py ├── 33.py ├── 13.py ├── 19.py ├── 3.py ├── 31.py ├── 34.py ├── 7.py ├── 16.py ├── 8.py ├── 14.py ├── 10.py ├── Data Structures and File Processing ├── Stacks │ └── PostfixEvaluation.py └── Merge Sort │ └── RecordClass.py ├── 20.py ├── Classes └── Class2.py └── Hackerearth └── Monk Takes a Walk.py /2.py: -------------------------------------------------------------------------------- 1 | a=ord('*') 2 | b=ord('\n') 3 | print(a*b) 4 | -------------------------------------------------------------------------------- /1.py: -------------------------------------------------------------------------------- 1 | for i in range(ord('F'),ord('Q')): 2 | print(i) 3 | -------------------------------------------------------------------------------- /25.py: -------------------------------------------------------------------------------- 1 | if __name__=='__main__': 2 | s=set() 3 | N=int(input()) 4 | for i in range(N): 5 | s.add(input()) 6 | print(len(s)) 7 | -------------------------------------------------------------------------------- /29.py: -------------------------------------------------------------------------------- 1 | if __name__=='__main__': 2 | n=int(input()) 3 | E=set(map(int,input().split())) 4 | m=int(input()) 5 | F=set(map(int,input().split())) 6 | print(len((E.difference(F)))) 7 | -------------------------------------------------------------------------------- /27.py: -------------------------------------------------------------------------------- 1 | if __name__=='__main__': 2 | n=int(input()) 3 | E=set(map(int,input().split())) 4 | m=int(input()) 5 | F=set(map(int,input().split())) 6 | print(len((E.union(F)))) 7 | 8 | -------------------------------------------------------------------------------- /28.py: -------------------------------------------------------------------------------- 1 | if __name__=='__main__': 2 | n=int(input()) 3 | E=set(map(int,input().split())) 4 | m=int(input()) 5 | F=set(map(int,input().split())) 6 | print(len((E.intersection(F)))) 7 | -------------------------------------------------------------------------------- /30.py: -------------------------------------------------------------------------------- 1 | if __name__=='__main__': 2 | n=int(input()) 3 | E=set(map(int,input().split())) 4 | m=int(input()) 5 | F=set(map(int,input().split())) 6 | print(len((E.symmetric_difference(F)))) 7 | -------------------------------------------------------------------------------- /9.py: -------------------------------------------------------------------------------- 1 | def solve(s): 2 | for x in s.split(): 3 | s=s.replace(x,x.capitalize()) 4 | return s 5 | 6 | 7 | if __name__ == '__main__': 8 | S=input() 9 | res=solve(S) 10 | print(res) 11 | -------------------------------------------------------------------------------- /GeeksForGeeks/Remove Spaces.py: -------------------------------------------------------------------------------- 1 | # Given a string, remove spaces from it 2 | 3 | if __name__ == '__main__': 4 | T = int(input()) 5 | while T>0: 6 | print(''.join(list(input().split()))) 7 | T-=1 8 | -------------------------------------------------------------------------------- /Itertools/Compress the String!: -------------------------------------------------------------------------------- 1 | from itertools import groupby 2 | if __name__=='__main__': 3 | string=input() 4 | l=list((len(list(g)),int(k)) for k,g in groupby(string)) 5 | print(' '.join(str(ch) for ch in l)) 6 | -------------------------------------------------------------------------------- /6.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | n = int(input()) 3 | arr = map(int, input().split()) 4 | l=list(arr) 5 | lMax=max(l) 6 | lRun=[i for i in l if i!=lMax] 7 | RunScore=max(lRun) 8 | print(RunScore) 9 | -------------------------------------------------------------------------------- /11.py: -------------------------------------------------------------------------------- 1 | def print_full_name(a, b): 2 | print("Hello",a,b+'!',"You just delved into python.") 3 | 4 | if __name__ == '__main__': 5 | first_name = input() 6 | last_name = input() 7 | print_full_name(first_name, last_name) 8 | -------------------------------------------------------------------------------- /Collections/Company Logo.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | if __name__=='__main__': 3 | s=sorted(input()) 4 | string=Counter(s) 5 | #print(string) 6 | for ch,count in string.most_common(3): 7 | print(ch,count) 8 | -------------------------------------------------------------------------------- /5.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | x = int(input()) 3 | y = int(input()) 4 | z = int(input()) 5 | n = int(input()) 6 | p=[[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if ((i+j+k)!=n)] 7 | print(p) 8 | -------------------------------------------------------------------------------- /Itertools/itertools.product(): -------------------------------------------------------------------------------- 1 | from itertools import product 2 | if __name__=='__main__': 3 | A=list(map(int,input().split())) 4 | B=list(map(int,input().split())) 5 | l=list(product(A,B)) 6 | print(' '.join(str(x) for x in l)) 7 | -------------------------------------------------------------------------------- /22.py: -------------------------------------------------------------------------------- 1 | def average(array): 2 | l=set(array) 3 | avg=sum(l)/len(l) 4 | return avg 5 | 6 | if __name__ == '__main__': 7 | n = int(input()) 8 | arr = list(map(int, input().split())) 9 | result = average(arr) 10 | print(result) 11 | -------------------------------------------------------------------------------- /17.py: -------------------------------------------------------------------------------- 1 | import textwrap 2 | 3 | def wrap(string, max_width): 4 | return textwrap.fill(string,max_width) 5 | 6 | if __name__ == '__main__': 7 | string, max_width = input(), int(input()) 8 | result = wrap(string, max_width) 9 | print(result) 10 | -------------------------------------------------------------------------------- /Date And Time/Calendar Module.py: -------------------------------------------------------------------------------- 1 | import calendar 2 | if __name__=='__main__': 3 | date=list(map(int,input().split())) 4 | month=date[0] 5 | day=date[1] 6 | year=date[2] 7 | weeknum=calendar.weekday(year,month,day) 8 | print(calendar.day_name[weeknum].upper()) 9 | -------------------------------------------------------------------------------- /Automate the boring stuff with python/2_control_flow/exitExample.py: -------------------------------------------------------------------------------- 1 | import sys 2 | if __name__ == '__main__': 3 | while True: 4 | print('Type exit to exit') 5 | response = input() 6 | if response == 'exit': 7 | sys.exit() 8 | print('You typed '+ response +' .') 9 | -------------------------------------------------------------------------------- /Itertools/itertools.permutations(): -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | if __name__=='__main__': 3 | string=input().split() 4 | l=list(string[0]) 5 | l.sort() 6 | r=''.join(l) 7 | k=int(string[1]) 8 | pair=list(permutations(r,k)) 9 | for ch in pair: 10 | print(''.join(ch)) 11 | -------------------------------------------------------------------------------- /Automate the boring stuff with python/5_Dictionaries_and_Structuring_Data/CharacterCount.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | message = 'It was a bright cold day in April, and the clocks were striking thirteen.' 3 | d = dict() 4 | for ch in message: 5 | d.setdefault(ch,0) 6 | d[ch]+=1 7 | print(d) 8 | -------------------------------------------------------------------------------- /4.py: -------------------------------------------------------------------------------- 1 | def is_leap(year): 2 | leap = False 3 | if year%4==0 and year%100!=0: 4 | leap= True 5 | elif year%4==0 and year%100==0: 6 | if year%400==0: 7 | leap= True 8 | else: 9 | leap= False 10 | return leap 11 | 12 | year = int(input()) 13 | print(is_leap(year)) 14 | -------------------------------------------------------------------------------- /21.py: -------------------------------------------------------------------------------- 1 | def print_formatted(number): 2 | w=len(bin(number)[2:]) 3 | for i in range(1,number+1): 4 | print(str(i).rjust(w,' '),str(oct(i)[2:]).rjust(w,' '),str(hex(i)[2:]).upper().rjust(w,' '),str(bin(i)[2:]).rjust(w,' ')) 5 | 6 | 7 | if __name__ == '__main__': 8 | n = int(input()) 9 | print_formatted(n) 10 | -------------------------------------------------------------------------------- /Date And Time/Time Delta.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | if __name__=='__main__': 3 | T=int(input()) 4 | for i in range(T): 5 | t1=datetime.strptime(input(),'%a %d %b %Y %H:%M:%S %z') 6 | t2=datetime.strptime(input(),'%a %d %b %Y %H:%M:%S %z') 7 | t=abs(int((t1-t2).total_seconds())) 8 | print(t) 9 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sort in descending.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string S containing only lower case alphabets, the task is to sort it in lexigraphically-descending order. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | s = list(input()) 8 | s.sort(reverse = True) 9 | print(''.join(s)) 10 | -------------------------------------------------------------------------------- /24.py: -------------------------------------------------------------------------------- 1 | if __name__=='__main__': 2 | n,m=input().split() 3 | arr=map(int,input().split()) 4 | A=set(map(int,input().split())) 5 | B=set(map(int,input().split())) 6 | happiness=0 7 | for ch in arr: 8 | if ch in A: 9 | happiness+=1 10 | elif ch in B: 11 | happiness-=1 12 | print(happiness) 13 | -------------------------------------------------------------------------------- /Itertools/Maximize it !: -------------------------------------------------------------------------------- 1 | from itertools import product 2 | if __name__=='__main__': 3 | K,M=map(int,input().split()) 4 | N=[] 5 | for i in range(K): 6 | N.append(list(map(int,input().split()))[1:]) 7 | #print(N) 8 | #print(list(product(*N))) 9 | results = list(map(lambda x: sum(j**2 for j in x)%M, product(*N))) 10 | print(max(results)) 11 | -------------------------------------------------------------------------------- /Itertools/itertools.combinations(): -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | if __name__=='__main__': 3 | string=input().split() 4 | l=list(string[0]) 5 | l.sort() 6 | r=''.join(l) 7 | K=int(string[1]) 8 | pair=[] 9 | for i in range(1,K+1): 10 | pair.extend(list(combinations(r,i))) 11 | for ch in pair: 12 | print(''.join(ch)) 13 | -------------------------------------------------------------------------------- /Itertools/itertools.combinations_with_replacement(): -------------------------------------------------------------------------------- 1 | from itertools import combinations_with_replacement 2 | if __name__=='__main__': 3 | string=input().split() 4 | l=list(string[0]) 5 | l.sort() 6 | r=''.join(l) 7 | K=int(string[1]) 8 | pair=list(combinations_with_replacement(r,K)) 9 | for ch in pair: 10 | print(''.join(ch)) 11 | 12 | -------------------------------------------------------------------------------- /GeeksForGeeks/Contest/Geek and the equation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a number N, find the value of below equation for the given number. 3 | for M in range 1 to N : sigma(pow(M+1 , 2)-(3M + 1) + M) 4 | ''' 5 | 6 | if __name__ == '__main__': 7 | T = int(input()) 8 | for _ in range(T): 9 | n = int(input()) 10 | res = (n*(n+1)*(2*n + 1))//6 11 | print(res) 12 | -------------------------------------------------------------------------------- /GeeksForGeeks/Rotate Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of size N, rotate it by D elements. 3 | ''' 4 | if __name__=='__main__': 5 | T=int(input()) 6 | for _ in range(T): 7 | l=list(map(int,input().split())) 8 | N,K=l[0],l[1] 9 | A=list(map(int,input().split())) 10 | rotate=A[K:]+A[0:K] 11 | print(' '.join(str(x) for x in rotate)) 12 | -------------------------------------------------------------------------------- /Collections/Word Order.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | if __name__=='__main__': 3 | N=int(input()) 4 | counts=OrderedDict() 5 | for i in range(N): 6 | word=input() 7 | if word not in counts.keys(): 8 | counts[word]=0 9 | counts[word]+=1 10 | print(len(counts)) 11 | print(' '.join(str(ch) for ch in counts.values())) 12 | -------------------------------------------------------------------------------- /Collections/DefaultDict.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | if __name__=='__main__': 3 | dfd=defaultdict(lambda:-1) 4 | n,m=map(int,input().split()) 5 | for i in range(1,n+1): 6 | A=input() 7 | dfd[A]=dfd[A]+' '+str(i) if A in dfd else str(i) 8 | #print(dict(dfd)) 9 | 10 | for i in range(m): 11 | B=input() 12 | print(dfd[B]) 13 | -------------------------------------------------------------------------------- /GeeksForGeeks/Nth root of M.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given 2 numbers (N , M); the task is to find N√M (Nth root of M). 3 | ''' 4 | import math 5 | if __name__=='__main__': 6 | T=int(input()) 7 | for i in range(T): 8 | l=list(map(int,input().split())) 9 | N,M=l[0],l[1] 10 | s=round(M**(1/N)) 11 | if s**N==M:print(int(s)) 12 | else:print('-1') 13 | -------------------------------------------------------------------------------- /GeeksForGeeks/Reverse Words in a given string.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a String of length S, reverse the whole string without reversing the individual words in it. Words are separated by dots. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | s = input() 8 | l = list(s.split('.')) 9 | l.reverse() 10 | print('.'.join(l)) 11 | -------------------------------------------------------------------------------- /12.py: -------------------------------------------------------------------------------- 1 | def mutate_string(string, position, character): 2 | ''' 3 | string=string[:position]+character+string[position+1:] 4 | ''' 5 | l=list(string) 6 | l[position]=character 7 | string=''.join(l) 8 | return string 9 | 10 | if __name__ == '__main__': 11 | s = input() 12 | i, c = input().split() 13 | s_new = mutate_string(s, int(i), c) 14 | print(s_new) 15 | -------------------------------------------------------------------------------- /15.py: -------------------------------------------------------------------------------- 1 | def merge_the_tools(string, k): 2 | i=len(string)//k 3 | j=0 4 | for tmp in range(i): 5 | m=[] 6 | for ch in string[j:j+k]: 7 | if ch not in m: 8 | m.append(ch) 9 | print(''.join(m)) 10 | j+=k 11 | 12 | if __name__ == '__main__': 13 | string, k = input(), int(input()) 14 | merge_the_tools(string, k) 15 | -------------------------------------------------------------------------------- /Itertools/Iterables and Iterators: -------------------------------------------------------------------------------- 1 | from itertools import combinations 2 | if __name__=='__main__': 3 | N = int(input()); a = input().split(); K = int(input()) 4 | c = list(combinations(a,K)) 5 | ''' 6 | x=list(filter(lambda c: 'a' in c,C)) 7 | print(len(x)/len(C)) 8 | ''' 9 | result = [1 for i in range(len(c)) if 'a' in c[i]] 10 | print(sum(result)/len(c)) 11 | 12 | -------------------------------------------------------------------------------- /18.py: -------------------------------------------------------------------------------- 1 | if __name__=='__main__': 2 | N,M=map(int,input().split()) 3 | mid=N//2 + 1 4 | for i in range(1,mid): 5 | pattern='.|.'*(2*i-1) 6 | pattern=pattern.center(M,'-') 7 | print(pattern) 8 | print('WELCOME'.center(M,'-')) 9 | for i in range(mid-1,0,-1): 10 | pattern='.|.'*(2*i-1) 11 | pattern=pattern.center(M,'-') 12 | print(pattern) 13 | -------------------------------------------------------------------------------- /GeeksForGeeks/Bit Difference.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given two numbers A and B. Write a program to count number of bits needed to be flipped to convert A to B. 3 | ''' 4 | if __name__=='__main__': 5 | T=int(input()) 6 | for _ in range(T): 7 | num=list(map(int,input().split())) 8 | a,b=num[0],num[1] 9 | xor=a^b 10 | tmp=bin(xor)[2:] 11 | print(tmp.count('1')) 12 | -------------------------------------------------------------------------------- /GeeksForGeeks/Series GP.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given the first 2 terms A and B of a Geometric Series, tell the Nth term of the series. 3 | ''' 4 | import math 5 | if __name__=='__main__': 6 | T=int(input()) 7 | for i in range(T): 8 | l=list(map(int,input().split())) 9 | A,B=l[0],l[1] 10 | N=int(input()) 11 | r=B/A 12 | tmp=r**(N-1) 13 | print(math.floor(A*tmp)) 14 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sorting/Binary Array Sorting.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary array A[] of size N. The task is to arrange array in increasing order. 3 | 4 | Note: The binary array contains only 0 and 1. 5 | ''' 6 | if __name__ == '__main__': 7 | T = int(input()) 8 | for _ in range(T): 9 | N = int(input()) 10 | A = list(map(int,input().split())) 11 | A.sort() 12 | print(*A) 13 | -------------------------------------------------------------------------------- /26.py: -------------------------------------------------------------------------------- 1 | if __name__=='__main__': 2 | n = int(input()) 3 | s = set(map(int, input().split())) 4 | N= int(input()) 5 | for i in range(N): 6 | command=input().split() 7 | if command[0]=='pop': 8 | m=s.pop() 9 | elif command[0]=='remove': 10 | s.remove(int(command[1])) 11 | else: 12 | s.discard(int(command[1])) 13 | print(sum(s)) 14 | -------------------------------------------------------------------------------- /GeeksForGeeks/Recursive/Permutations of string.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string S. The task is to print all permutations of a given string. 3 | ''' 4 | from itertools import permutations 5 | if __name__ == '__main__': 6 | T = int(input()) 7 | for _ in range(T): 8 | S = input() 9 | for i in sorted(permutations(S)): 10 | print(''.join(i),end=' ') 11 | print() 12 | 13 | -------------------------------------------------------------------------------- /LeetCode/Palindrome Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. 3 | ''' 4 | class Solution(object): 5 | def isPalindrome(self, x): 6 | """ 7 | :type x: int 8 | :rtype: bool 9 | """ 10 | x = str(x) 11 | if x == x[::-1]:return True 12 | return False 13 | 14 | -------------------------------------------------------------------------------- /GeeksForGeeks/Day of the week.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a program that calculates the day of the week for any particular date in the past or future. 3 | ''' 4 | import calendar 5 | if __name__=='__main__': 6 | T=int(input()) 7 | for _ in range(T): 8 | DMY=list(map(int,input().split())) 9 | D,M,Y=DMY[0],DMY[1],DMY[2] 10 | day=calendar.weekday(Y,M,D) 11 | print(calendar.day_name[day]) 12 | -------------------------------------------------------------------------------- /23.py: -------------------------------------------------------------------------------- 1 | def SetDifference(M,N): 2 | l=[] 3 | l.extend(M.difference(N)) 4 | l.extend(N.difference(M)) 5 | l.sort() 6 | return l 7 | 8 | def main(): 9 | x=int(input()) 10 | M=set(map(int,input().split())) 11 | y=int(input()) 12 | N=set(map(int,input().split())) 13 | diff=SetDifference(M,N) 14 | for ch in diff: 15 | print(ch) 16 | 17 | if __name__=='__main__': 18 | main() 19 | -------------------------------------------------------------------------------- /GeeksForGeeks/Trailing zeroes in factorial.py: -------------------------------------------------------------------------------- 1 | ''' 2 | For an integer n find number of trailing zeroes in n! . 3 | ''' 4 | import math 5 | if __name__=='__main__': 6 | T=int(input()) 7 | for i in range(T): 8 | N=int(input()) 9 | tmp=math.floor(N/5) 10 | sum=tmp 11 | while tmp>=5: 12 | tmp=math.floor(tmp/5) 13 | sum+=tmp 14 | 15 | print(sum) 16 | -------------------------------------------------------------------------------- /Automate the boring stuff with python/4_List/Comma Code.py: -------------------------------------------------------------------------------- 1 | def commalist(lst): 2 | s = '' 3 | if lst == []:return s 4 | if len(lst) == 1 : return lst[0] 5 | 6 | tmp = lst[:len(lst)-1] 7 | s = ', '.join(tmp) 8 | s = s + ', and ' + lst[-1] 9 | return s 10 | 11 | if __name__ == '__main__': 12 | 13 | l = list(input('Enter elements of list : ').split()) 14 | print(commalist(l)) 15 | -------------------------------------------------------------------------------- /Collections/Collections.namedtuple().py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | if __name__=='__main__': 3 | N=int(input()) 4 | avg=0 5 | sheet=input().split() 6 | #print(sheet) 7 | student=namedtuple('student',[sheet[0],sheet[1],sheet[2],sheet[3]]) 8 | for i in range(N): 9 | stu=input().split() 10 | S=student(stu[0],stu[1],stu[2],stu[3]) 11 | avg+=int(S.MARKS) 12 | print("{:.2f}".format(avg/N)) 13 | -------------------------------------------------------------------------------- /32.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | if __name__=='__main__': 3 | K=int(input()) 4 | ''' 5 | //TLB Error 6 | x=input().split() 7 | for ch in x: 8 | if x.count(ch)!=K: 9 | print(ch) 10 | break 11 | ''' 12 | RoomList=map(int,input().split()) 13 | cnt=Counter(RoomList) 14 | for num,count in cnt.items(): 15 | if count!=K: 16 | print(num) 17 | break 18 | -------------------------------------------------------------------------------- /GeeksForGeeks/Contest/Adjacent Equal.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of N integers. The task is to count the pairs which are adjacent and equal. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | N = int(input()) 8 | A = list(map(int,input().split())) 9 | count = 0 10 | for i in range(N-1): 11 | if A[i]==A[i+1]: 12 | count+=1 13 | print(count) 14 | -------------------------------------------------------------------------------- /GeeksForGeeks/Searching/Missing number in array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing, the missing number is to be found. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | N = int(input()) 8 | C = list(map(int,input().split())) 9 | actsum = sum(C) 10 | sumNat = (N*(N+1))//2 11 | print(sumNat-actsum) 12 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sorting/Check if an array is sorted.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array C[], write a program that prints 1 if array is sorted in non-decreasing order, else prints 0. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | N = int(input()) 8 | A = list(map(int,input().split())) 9 | tmp = [x for x in A] 10 | tmp.sort() 11 | if tmp == A:print(1) 12 | else : print(0) 13 | -------------------------------------------------------------------------------- /GeeksForGeeks/Amazon/k largest elements.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of N positive integers, print k largest elements from the array. The output elements should be printed in decreasing order. 3 | ''' 4 | 5 | if __name__ == '__main__': 6 | 7 | t = int(input()) 8 | for _ in range(t): 9 | 10 | n , k = map(int,input().split()) 11 | A = list(map(int,input().split())) 12 | A.sort(reverse = True) 13 | print(*A[:k]) 14 | -------------------------------------------------------------------------------- /Automate the boring stuff with python/6_Manipulating_Strings/picnicTable.py: -------------------------------------------------------------------------------- 1 | def printPicnic(itemsDict, leftWidth, rightWidth): 2 | print('PICNIC ITEMS'.center(17,'-')) 3 | for k,v in itemsDict.items(): 4 | print(k.ljust(leftWidth ,'.') + str(v).rjust(rightWidth)) 5 | 6 | if __name__ == '__main__': 7 | picnicItems = {'sandwiches':4 , 'apples':12 , 'cups':4 , 'cookies':8000} 8 | printPicnic(picnicItems,12,5) 9 | printPicnic(picnicItems,16,8) 10 | -------------------------------------------------------------------------------- /GeeksForGeeks/Contest/Game of Function.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Below is a function given to you. The task is to find the value of function for given number X. 3 | Function : f(X) = f(X+1) + X; f(0) = 1. 4 | ''' 5 | 6 | def Function(X): 7 | if X == 0: return 1 8 | return Function(X-1)-X 9 | 10 | if __name__ == '__main__': 11 | T = int(input()) 12 | for _ in range(T): 13 | X = int(input()) 14 | n = Function(X) 15 | print(n+X) 16 | 17 | -------------------------------------------------------------------------------- /33.py: -------------------------------------------------------------------------------- 1 | if __name__=='__main__': 2 | T=int(input()) 3 | for i in range(T): 4 | EleA=int(input()) 5 | A=list(map(int,input().split())) 6 | EleB=int(input()) 7 | B=list(map(int,input().split())) 8 | f=0 9 | for ch in A: 10 | if ch not in B: 11 | f=1 12 | break 13 | 14 | if f==1: 15 | print('False') 16 | else: 17 | print('True') 18 | -------------------------------------------------------------------------------- /13.py: -------------------------------------------------------------------------------- 1 | def count_substring(string, sub_string): 2 | counter=0 3 | i=0 4 | while i=0: 6 | i=string.find(sub_string,i)+1 7 | counter+=1 8 | else: 9 | break 10 | return counter 11 | 12 | if __name__ == '__main__': 13 | string = input().strip() 14 | sub_string = input().strip() 15 | 16 | count = count_substring(string, sub_string) 17 | print(count) 18 | -------------------------------------------------------------------------------- /Collections/collections.Counter().py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | if __name__=='__main__': 3 | Tot_Money=0 4 | N=int(input()) 5 | l=list(map(int,input().split())) 6 | Shoes=Counter(l) 7 | #print(Shoes) 8 | No_Cust=int(input()) 9 | for i in range(No_Cust): 10 | Customer=list(map(int,input().split())) 11 | if Shoes[Customer[0]]!=0: 12 | Tot_Money+=Customer[1] 13 | Shoes[Customer[0]]-=1 14 | print(Tot_Money) 15 | -------------------------------------------------------------------------------- /GeeksForGeeks/Find duplicates in an array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A[], Your task is to complete the function printDuplicates which prints the duplicate elements of the given array. 3 | If no duplicate element is found print -1. 4 | ''' 5 | def printDuplicates(arr,n): 6 | c = 1 7 | for i in range(n): 8 | ind = arr[i] % n 9 | arr[ind] += n 10 | 11 | if arr[ind]//n == 2: 12 | print(ind,end= " ") 13 | c = 0 14 | 15 | if c:print('-1') 16 | -------------------------------------------------------------------------------- /GeeksForGeeks/Nearest Multiple of 10.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a positive number N. The task is to round N to nearest multiple of 10. Number can be so big and can contains 1000 of digits. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | N = int(input()) 8 | rem = N%10 9 | if rem == 0: 10 | print(N) 11 | elif rem <=5 : 12 | print(N-rem) 13 | else: 14 | print(N+(10-rem)) 15 | 16 | -------------------------------------------------------------------------------- /GeeksForGeeks/Count Squares.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sample space S consisting of all perfect squares starting from 1, 4, 9 and so on. 3 | You are given a number N, you have to print the number of integers less than N in the sample space S. 4 | ''' 5 | from math import sqrt,floor 6 | if __name__=='__main__': 7 | T=int(input()) 8 | for _ in range(T): 9 | N=int(input()) 10 | if sqrt(N)==int(sqrt(N)):print(floor(sqrt(N))-1) 11 | else:print(floor(sqrt(N))) 12 | 13 | -------------------------------------------------------------------------------- /GeeksForGeeks/Unit Digit.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a number N. The task is to find the unit digit of factorial of given number N. 3 | ''' 4 | def Factorial(N): 5 | if N==0 or N==1: 6 | return 1 7 | else: 8 | return N*Factorial(N-1) 9 | if __name__=='__main__': 10 | T=int(input()) 11 | for _ in range(T): 12 | N=int(input()) 13 | if N<5: 14 | fact=Factorial(N) 15 | print(fact%10) 16 | else: 17 | print('0') 18 | 19 | -------------------------------------------------------------------------------- /19.py: -------------------------------------------------------------------------------- 1 | def print_rangoli(size): 2 | s='abcdefghijklmnopqrstuvwxyz' 3 | for i in range(size-1,0,-1): 4 | l=[] 5 | m='-'.join(s[i:size]) 6 | l.append(m[::-1]+m[1::]) 7 | print(''.join(l).center((4*n-3),'-')) 8 | for i in range(size): 9 | l=[] 10 | m='-'.join(s[i:size]) 11 | l.append(m[::-1]+m[1::]) 12 | print(''.join(l).center((4*n-3),'-')) 13 | 14 | if __name__ == '__main__': 15 | n = int(input()) 16 | print_rangoli(n) 17 | -------------------------------------------------------------------------------- /3.py: -------------------------------------------------------------------------------- 1 | DString=input() 2 | OutString='' 3 | flag='T' 4 | for i in DString: 5 | if i not in ['G','C','A','T']: 6 | print('Invalid Input') 7 | flag='F' 8 | break 9 | else: 10 | if i=='G': 11 | OutString+='C' 12 | elif i=='C': 13 | OutString+='G' 14 | elif i=='T': 15 | OutString+='A' 16 | elif i=='A': 17 | OutString+='U' 18 | if flag=='T': 19 | print(OutString) 20 | -------------------------------------------------------------------------------- /GeeksForGeeks/Longest palindromic substring.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string, find the longest substring which is palindrome. 3 | ''' 4 | def substrings(s): 5 | l = len(s) 6 | for i in range(l, 0, -1): 7 | for j in range(l-i+1): 8 | yield s[j: j+i] 9 | 10 | def palindrome(s): 11 | return s == s[::-1] 12 | 13 | def findLongestPalindromicString(seq): 14 | for l in substrings(seq): 15 | if palindrome(l): 16 | print(l) 17 | break 18 | -------------------------------------------------------------------------------- /GeeksForGeeks/Palindrome String.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string S, check if it is palindrome or not. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | N = int(input()) 8 | S = input() 9 | flag = 0 10 | i , j = 0 ,N-1 11 | while i<=j: 12 | if S[i]!=S[j]: 13 | flag = 1 14 | break 15 | i+=1 16 | j-=1 17 | if flag == 0 : print('Yes') 18 | else : print('No') 19 | -------------------------------------------------------------------------------- /Automate the boring stuff with python/5_Dictionaries_and_Structuring_Data/prettyCharacterCount.py: -------------------------------------------------------------------------------- 1 | import pprint #pretty print 2 | if __name__ == '__main__': 3 | message = 'It was a bright cold day in April, and the clocks were striking thirteen.' 4 | d = dict() 5 | for ch in message: 6 | d.setdefault(ch,0) 7 | d[ch]+=1 8 | pprint.pprint(d) # To print dictionary 9 | s = pprint.pformat(d) # To obtain prettified text as a string 10 | print(s) 11 | -------------------------------------------------------------------------------- /GeeksForGeeks/Swap two nibbles in a byte.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a byte, swap the two nibbles in it. For example 100 is be represented as 01100100 in a byte (or 8 bits). 3 | The two nibbles are (0110) and (0100). If we swap the two nibbles, we get 01000110 which is 70 in decimal. 4 | ''' 5 | if __name__=='__main__': 6 | T=int(input()) 7 | for _ in range(T): 8 | X=int(input()) 9 | binX=list('{0:08b}'.format(X)) 10 | binY=binX[4:]+binX[0:4] 11 | Y=int(''.join(binY),2) 12 | print(Y) 13 | -------------------------------------------------------------------------------- /GeeksForGeeks/Amazon/Maximum value in a bitonic array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of elements which is first increasing and then may be decreasing, find the maximum element in the array. 3 | Note: If the array is increasing then just print then last element will be the maximum value. 4 | ''' 5 | if __name__ == '__main__': 6 | 7 | t = int(input()) 8 | while t>0: 9 | n = int(input()) 10 | A = list(map(int,input().split())) 11 | A.sort() 12 | print(A[n-1]) 13 | 14 | t -= 1 15 | -------------------------------------------------------------------------------- /GeeksForGeeks/Excel Column Names.py: -------------------------------------------------------------------------------- 1 | def ColumnName(n): 2 | Str=['']*50 3 | i=0 4 | while n>0: 5 | rem=int(n%26) 6 | if rem!=0: 7 | Str[i]=chr((rem-1)+ord('A')) 8 | n=n//26 9 | else: 10 | Str[i]='Z' 11 | n=(n//26)-1 12 | i+=1 13 | string = Str[::-1] 14 | print(''.join(string)) 15 | 16 | 17 | if __name__=='__main__': 18 | T=int(input()) 19 | for _ in range(T): 20 | N=int(input()) 21 | ColumnName(N) 22 | -------------------------------------------------------------------------------- /Collections/Collections.OrderedDict().py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | if __name__=='__main__': 3 | N=int(input()) 4 | superMarket=OrderedDict() 5 | for i in range(N): 6 | item_price=input().split() 7 | l=len(item_price) 8 | item=' '.join(item_price[0:l-1]) 9 | price=int(item_price[-1]) 10 | if item not in superMarket.keys(): 11 | superMarket[item]=0 12 | superMarket[item]+=price 13 | for item,price in superMarket.items(): 14 | print(item,price) 15 | -------------------------------------------------------------------------------- /GeeksForGeeks/Matrix/Print Matrix in snake Pattern.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a matrix mat[][] of size N x N. The task is to print the elements of the matrix in the snake pattern. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | N = int(input()) 8 | l = list(input().split()) 9 | A = [l[i:i+N] for i in range(0,N*N,N)] 10 | for i in range(N): 11 | if i%2 != 0: 12 | A[i].reverse() 13 | for ch in A:print(*ch,end=' ') 14 | print() 15 | -------------------------------------------------------------------------------- /GeeksForGeeks/Pair cube count.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given N, count all ‘a’(>=1) and ‘b’(>=0) that satisfy the condition a3 + b3 = N. 3 | ''' 4 | if __name__=='__main__': 5 | T=int(input()) 6 | for i in range(T): 7 | count=0 8 | N=int(input()) 9 | upper=int(pow(N,1/3))+1 10 | for j in range(1,upper+1): 11 | for k in range(upper,-1,-1): 12 | a=int(j**3) 13 | b=int(k**3) 14 | c=a+b 15 | if c==N:count+=1 16 | 17 | print(count) 18 | -------------------------------------------------------------------------------- /GeeksForGeeks/nCr Practice.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | if n==0 or n==1: 3 | return 1 4 | return n*factorial(n-1) 5 | 6 | if __name__=='__main__': 7 | T=int(input()) 8 | for i in range(T): 9 | l=list(map(int,input().split())) 10 | n,r=l[0],l[1] 11 | if n 6 | using namespace std; 7 | int main() 8 | { 9 | int t; 10 | cin>>t; 11 | while(t--) 12 | { 13 | int n; 14 | cin>>n; 15 | int A[n]; 16 | int x = 0; 17 | for(int i =0;i>A[i]; 20 | x = x^A[i]; 21 | } 22 | 23 | cout<len(string):print(0) 10 | elif len(string)%len(pattern)!=0:print(0) 11 | elif string[:len(pattern)]!= pattern:print(0) 12 | else:print(1) 13 | -------------------------------------------------------------------------------- /GeeksForGeeks/String Rotations.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given strings s1 and s2, you need to find if s2 is a rotated version of the string s1. The strings are lowercase. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | s1 = input() 8 | s2 = input() 9 | 10 | if len(s1)==len(s2): 11 | tmp = s1+s1 # It gives all possible rotations 12 | if s2 in tmp : print(1) # of a string. 13 | else : print(0) 14 | else: 15 | print(0) 16 | 17 | -------------------------------------------------------------------------------- /GeeksForGeeks/Add two fractions.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given four numbers num1, den1, num2, and den2. You need to find (num1/den1)+(num2/den2) and output the result in the form of 3 | (numx/denx). 4 | ''' 5 | def GCD(A,B): 6 | if A==0:return B 7 | if B==0:return A 8 | if A==B:return A 9 | if A>B:return GCD(B,A%B) 10 | if AB:return GCD(B,A%B) 9 | if A\n') 18 | print(pyperclip.paste()) 19 | -------------------------------------------------------------------------------- /LeetCode/Integer to Roman.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def intToRoman(self, num): 3 | """ 4 | :type num: int 5 | :rtype: str 6 | """ 7 | roman = '' 8 | number = [1,4,5,9,10,40,50,90,100,400,500,900,1000] 9 | sym = ['I','IV','V','IX','X','XL','L','XC','C','CD','D','CM','M'] 10 | i = 12 11 | while num > 0: 12 | rem = num // number[i] 13 | num = num % number[i] 14 | for j in range(rem): 15 | roman += sym[i] 16 | 17 | i -= 1 18 | return roman 19 | -------------------------------------------------------------------------------- /GeeksForGeeks/Hashing/Count pairs with given sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, and an integer ‘K’ , find the count of pairs of elements in the array whose sum is equal to 'K'. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | num = list(map(int,input().split())) 8 | N , K = num[0],num[1] 9 | A = list(map(int,input().split())) 10 | count = 0 11 | for i in range(N-1): 12 | for j in range(i+1,N): 13 | if A[i]+A[j]== K :count+=1 14 | 15 | print(count) 16 | 17 | -------------------------------------------------------------------------------- /GeeksForGeeks/Searching/Find Transition Point.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given a sorted array containing only numbers 0 and 1. Find the transition point efficiently. 3 | Transition point is a point where "0" ends and "1" begins. 4 | ''' 5 | ''' 6 | # Using built-in function 7 | 8 | def transitionPoint(arr, n): 9 | try : 10 | return arr.index(1) 11 | except : return None 12 | ''' 13 | def transitionPoint(arr, n): 14 | ind = -1 15 | for i in range(0,n): 16 | if arr[i] == 1: 17 | ind = i 18 | break 19 | 20 | if ind == -1 : return None 21 | return ind 22 | -------------------------------------------------------------------------------- /GeeksForGeeks/Check for Subsequence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two strings A and B, find if A is a subsequence of B. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | strings = list(input().split()) 8 | subseq , string = strings[0],strings[1] 9 | j = 0 10 | flag = 0 11 | while j < len(subseq): 12 | i = string.find(subseq[j]) 13 | if i == -1: 14 | flag = 1 15 | break 16 | string = string[i+1:] 17 | j+=1 18 | if flag == 1 : print(0) 19 | else : print(1) 20 | -------------------------------------------------------------------------------- /GeeksForGeeks/Count Smaller elements.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of positive integers. Count number of smaller elements on right side of each array. 3 | ''' 4 | def SmallerCount(arr,n): 5 | for i in range(n): 6 | c=0 7 | val=arr[i] 8 | newarr=arr[i+1:] 9 | for k in newarr: 10 | if k= a2 <= a3 >= a4 <= a5..... (considering the increasing lexicographical order). 4 | ''' 5 | if __name__=='__main__': 6 | T=int(input()) 7 | for _ in range(T): 8 | N=int(input()) 9 | A=list(map(int,input().split())) 10 | i=0 11 | while i ') 18 | if sep == '': 19 | print(strip(string)) 20 | else: 21 | print(strip(string,sep)) 22 | -------------------------------------------------------------------------------- /34.py: -------------------------------------------------------------------------------- 1 | if __name__=='__main__': 2 | A=set(map(int,input().split())) 3 | n=int(input()) 4 | f=0 5 | for i in range(n): 6 | B=set(map(int,input().split())) 7 | f1,f2=0,0 8 | for ch in B: 9 | if ch not in A: 10 | f1=1 11 | break 12 | #print('f1',f1) 13 | if f1!=1: 14 | for ch in A: 15 | if ch not in B: 16 | f2+=1 17 | #print('f2',f2) 18 | if f2>1: 19 | f+=1 20 | #print('f',f) 21 | if f==n: 22 | print('True') 23 | else: 24 | print('False') 25 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sum of all prime numbers between 1 and N.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a positive integer N, calculate the sum of all prime numbers between 1 and N(inclusive). 3 | ''' 4 | def SumOfPrimes(N): 5 | prime=[True]*(N+1) 6 | prime[0]=prime[1]=False 7 | p=2 8 | while p*p<=N: 9 | if prime[p]==True: 10 | for i in range(p*p,N+1,p): 11 | prime[i]=False 12 | p+=1 13 | sum=0 14 | for i in range(2,N+1): 15 | if prime[i]:sum+=i 16 | return sum 17 | if __name__=='__main__': 18 | T=int(input()) 19 | for _ in range(T): 20 | N=int(input()) 21 | print(SumOfPrimes(N)) 22 | -------------------------------------------------------------------------------- /GeeksForGeeks/Amazon/Check set bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a number N. Write a program to check whether every bit in the binary representation of the given number is set or not. 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | bool Check(int n) 9 | { 10 | while(n > 0) 11 | { 12 | if(!(n & 1)) 13 | return false; 14 | 15 | n = n>>1; 16 | } 17 | return true; 18 | } 19 | int main() 20 | { 21 | int t; 22 | cin>>t; 23 | while(t--) 24 | { 25 | int n; 26 | cin>>n; 27 | if(Check(n)) 28 | cout<<"YES"< arr[j+1]: 8 | arr[j],arr[j+1] = arr[j+1],arr[j] 9 | return arr 10 | 11 | def bubbleSort(arr, n): 12 | for i in range(n-1): 13 | arr = bubble(arr, i, n) 14 | return arr 15 | 16 | if __name__=='__main__': 17 | t = int(input()) 18 | for i in range(t): 19 | n = int(input()) 20 | arr = list(map(int, input().split())) 21 | arr = bubbleSort(arr, n) 22 | print(*arr) 23 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sorting/Selection Sort.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The task is to complete select() function which is used to implement Selection Sort. 3 | ''' 4 | def select(arr): 5 | for i in range(n-1): 6 | ind = i 7 | for j in range(i+1,n): 8 | if arr[j]=Max: 12 | S.append(A[i]) 13 | Max=A[i] 14 | print(*S[::-1]) 15 | 16 | T=int(input()) 17 | for _ in range(T): 18 | n=int(input()) 19 | A=list(map(int,input().split())) 20 | Leaders(A,n) 21 | 22 | -------------------------------------------------------------------------------- /GeeksForGeeks/The Game of Digits.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a number N. Find a number K such that product of digits of K must be equal to N. 3 | Note : K must be as small as possible. 4 | ''' 5 | def SmallestNumber(n): 6 | if n>=0 and n<=9: 7 | return n 8 | l=[] 9 | for i in range(9,1,-1): 10 | while n%i==0: 11 | l.append(i) 12 | n=n//i 13 | if n!=1: 14 | return -1 15 | k=0 16 | while len(l)!=0: 17 | k=k*10+l[-1] 18 | l.pop() 19 | return k 20 | if __name__=='__main__': 21 | T=int(input()) 22 | for _ in range(T): 23 | N=int(input()) 24 | print(SmallestNumber(N)) 25 | -------------------------------------------------------------------------------- /7.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | l=[] 3 | scores=[] 4 | Names=[] 5 | for _ in range(int(input())): 6 | name = input() 7 | score = float(input()) 8 | l.append([name,score]) 9 | #print(l) 10 | for i in range(len(l)): 11 | marks=l[i][1] 12 | scores.append(marks) 13 | #print(scores) 14 | minScore=min(scores) 15 | Rem=[i for i in scores if i!=minScore] 16 | SecMin=min(Rem) 17 | #print(SecMin) 18 | for i in range(len(l)): 19 | if l[i][1]==SecMin: 20 | Names.append(l[i][0]) 21 | Names.sort() 22 | #print(Names) 23 | for ch in Names: 24 | print(ch) 25 | -------------------------------------------------------------------------------- /GeeksForGeeks/Fibonacci.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Tell only last two digits of the Nth number of Fibonacci series. 3 | A better solution is to use the fact that after 300-th Fibonacci number last two digits starts repeating. 4 | 1) Find m = n % 300. 5 | 2) Return m-th Fibonacci number. 6 | ''' 7 | def Fibonacci(): 8 | f=[0,1] 9 | for i in range(2,300): 10 | f.append((f[i-1]+f[i-2])%100) 11 | return f 12 | 13 | def PrintLastTwo(f,N): 14 | return f[N%300] 15 | 16 | 17 | if __name__=='__main__': 18 | T=int(input()) 19 | for i in range(T): 20 | N=int(input()) 21 | f=Fibonacci() 22 | print(PrintLastTwo(f,N)) 23 | 24 | -------------------------------------------------------------------------------- /GeeksForGeeks/Hashing/Largest Fibonacci Subsequence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array with positive number the task to find the largest subsequence from array that contain elements which are Fibonacci numbers. 3 | ''' 4 | def Fib(N): 5 | a , b = 0 ,1 6 | res = [a] 7 | for i in range(N): 8 | a , b = b,a+b 9 | res.append(a) 10 | return res 11 | 12 | if __name__ == '__main__': 13 | T = int(input()) 14 | for _ in range(T): 15 | N = int(input()) 16 | A = list(map(int,input().split())) 17 | res = Fib(max(A)) 18 | for ch in A: 19 | if ch in res:print(ch,end=' ') 20 | print(end='\n') 21 | 22 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sieve of Eratosthenes.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a number N, calculate the prime numbers upto N using Sieve of Eratosthenes. 3 | ''' 4 | def PrintPrime(N): 5 | l=[] 6 | prime=[True for i in range(N+1)] 7 | p=2 8 | while p*p<=N: 9 | if prime[p]: 10 | for i in range(p*p,N+1,p): 11 | prime[i]=False 12 | p+=1 13 | for i in range(2,N+1): 14 | if prime[i]==True: 15 | l.append(i) 16 | print(' '.join(str(i) for i in l)) 17 | 18 | 19 | 20 | if __name__=='__main__': 21 | T=int(input()) 22 | for i in range(T): 23 | N=int(input()) 24 | PrintPrime(N) 25 | -------------------------------------------------------------------------------- /Automate the boring stuff with python/Pattern_Matching_With_Regular_Expressions/isPhoneNumber.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 1. Import the regex module with import re. 3 | 2. Create a Regex object with the re.compile() function. (Remember to use a raw string.) 4 | 3. Pass the string you want to search into the Regex object’s search() method.This returns a Match object. 5 | 4. Call the Match object’s group() method to return a string of the actual matched text. 6 | ''' 7 | import re 8 | 9 | if __name__ == '__main__': 10 | 11 | phoneNumRegex = re.compile(r'\d\d\d - \d\d\d - \d\d\d\d') 12 | mo = phoneNumRegex.search('My number is 415 - 555 - 4242.') 13 | print('Phone number found : '+ mo.group()) 14 | -------------------------------------------------------------------------------- /GeeksForGeeks/Majority Element.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of N elements. Find the majority element in the array. 3 | A majority element in an array A of size N is an element that appears more than N/2 times in the array. 4 | ''' 5 | T=int(input()) 6 | for _ in range(T): 7 | flag=0 8 | N=int(input()) 9 | A=list(map(int,input().split())) 10 | j,d=1,{} 11 | for i in range(N): 12 | ch=A[i] 13 | if ch not in d: 14 | d.update({ch:j}) 15 | else: 16 | d[ch]+=1 17 | for k,val in d.items(): 18 | if val>(N//2): 19 | print(k) 20 | flag=1 21 | break 22 | if flag==0:print('-1') 23 | 24 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sorting/Insertion Sort.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The task is to complete insert() function which is used to implement Insertion Sort. 3 | ''' 4 | def insert(arr): 5 | n = len(arr) 6 | for i in range(1,n): 7 | temp = arr[i] 8 | j = i 9 | while j > 0 and (arr[j-1]> temp): 10 | arr[j] = arr[j-1] 11 | j-=1 12 | arr[j] = temp 13 | 14 | return arr 15 | 16 | if __name__ == "__main__": 17 | t=int(input()) 18 | for i in range(t): 19 | n=int(input()) 20 | arr=list(map(int,input().split())) 21 | insert(arr) 22 | for i in range(n): 23 | print(arr[i],end=" ") 24 | print() 25 | -------------------------------------------------------------------------------- /GeeksForGeeks/Recursive/Handshakes.py: -------------------------------------------------------------------------------- 1 | ''' 2 | We have N persons sitting on a round table. Any person can do a handshake with any other person.In how many ways these N people can make 3 | handshakes so that no two handshakes crosses each other. N would be even. 4 | ''' 5 | 6 | def Catalan(n): 7 | catalan = [1 for i in range(n + 1)] 8 | 9 | for i in range(2, n + 1): 10 | catalan[i] = 0 11 | for j in range(i): 12 | catalan[i] += (catalan[j] *catalan[i - j - 1]) 13 | 14 | return catalan[n] 15 | 16 | if __name__ == "__main__": 17 | T = int(input()) 18 | for _ in range(T): 19 | N = int(input()) 20 | print(Catalan(N//2)) 21 | -------------------------------------------------------------------------------- /LeetCode/Roman To Integer.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def romanToInt(self, s): 3 | """ 4 | :type s: str 5 | :rtype: int 6 | """ 7 | num = 0 8 | 9 | sym = {'I': 1,'IV' : 4,'V' : 5,'IX' : 9,'X' : 10,'XL' : 40,'L' : 50,'XC' : 90,'C' : 100,'CD' : 400,'D' : 500,'CM' : 900,'M' : 1000} 10 | 11 | for i in range(len(s)): 12 | if i != len(s)-1: 13 | if sym[s[i]] >= sym[s[i+1]]: 14 | num += sym[s[i]] 15 | else: 16 | num -= sym[s[i]] 17 | else: 18 | num += sym[s[i]] 19 | 20 | return num 21 | 22 | -------------------------------------------------------------------------------- /LeetCode/Two Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of integers, return indices of the two numbers such that they add up to a specific target. 3 | 4 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 5 | ''' 6 | class Solution(object): 7 | def twoSum(self, nums, target): 8 | """ 9 | :type nums: List[int] 10 | :type target: int 11 | :rtype: List[int] 12 | """ 13 | for i in range(len(nums)): 14 | rem = target - nums[i] 15 | if rem in nums[i+1:]: 16 | ind = nums[i+1:].index(rem) 17 | l = [i,i+ind+1] 18 | return l 19 | 20 | -------------------------------------------------------------------------------- /GeeksForGeeks/Searching/Searching a number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of N elements and a integer K. Your task is to return the position of first occurence of K in the given array. 3 | Note: Position of first element is considered as 1. 4 | For each test case, print the index of first occurrence of given number K. Print -1 if the number is not found in array. 5 | ''' 6 | if __name__ == '__main__': 7 | T = int(input()) 8 | for _ in range(T): 9 | numbers = list(map(int,input().split())) 10 | N , K = numbers[0] , numbers[1] 11 | array = list(map(int,input().split())) 12 | try: 13 | ind = array.index(K) 14 | print(ind+1) 15 | except : print(-1) 16 | -------------------------------------------------------------------------------- /GeeksForGeeks/Searching/Square root.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer x. The task is to find the square root of x. If x is not a perfect square, then return floor(√x). 3 | ''' 4 | ''' 5 | from math import sqrt 6 | def floorSqrt(x): 7 | return math.floor(sqrt(x)) 8 | 9 | ''' 10 | import math 11 | def NPSquare(N): 12 | nextN = math.floor(math.sqrt(N)) + 1 13 | return nextN * nextN 14 | 15 | def floorSqrt(x): 16 | low = 0 17 | high = x 18 | while low<=high: 19 | mid = (low+high)//2 20 | if (mid*mid == x) or ((mid+1)*(mid+1) == NPSquare(x)): 21 | return mid 22 | if (mid*mid) > x: high = mid-1 23 | else : low = mid+1 24 | 25 | return -1 26 | -------------------------------------------------------------------------------- /GeeksForGeeks/Weigh the strings.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The weight W of a string is defined by the formula, W = sum of ASCII values of characters in the string. Now, you are given two strings 3 | S1 and S2, and the task is to find the heavier string. 4 | Print the string with heavier weight. Print "equal"(without quotes) if weight of both strings are equal. 5 | ''' 6 | 7 | if __name__ == '__main__': 8 | T = int(input()) 9 | for _ in range(T): 10 | s1 ,s2 = input() , input() 11 | sum1 , sum2 = 0 , 0 12 | for ch in s1: 13 | sum1+=ord(ch) 14 | for ch in s2: 15 | sum2+=ord(ch) 16 | if sum1sum2:print(s1) 18 | else:print('equal') 19 | -------------------------------------------------------------------------------- /GeeksForGeeks/Closest Number.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given non-zero two integers N and M. The problem is to find the number closest to N and divisible by M. 3 | If there are more than one such number, then output the one having maximum absolute value. 4 | ''' 5 | def Closest(N,M): 6 | M=abs(M) 7 | q=N//M 8 | n1= M*q 9 | n2=M*(q+1) 10 | 11 | diff1=N-n1 12 | diff2=n2-N 13 | 14 | if diff1>diff2:print(n2) 15 | elif diff2>diff1:print(n1) 16 | else: 17 | if abs(n1)>abs(n2):print(n1) 18 | else:print(n2) 19 | 20 | if __name__=='__main__': 21 | T=int(input()) 22 | for i in range(T): 23 | l=list(map(int,input().split())) 24 | N,M=l[0],l[1] 25 | Closest(N,M) 26 | -------------------------------------------------------------------------------- /Automate the boring stuff with python/3_Function/The Collatz Sequence.py: -------------------------------------------------------------------------------- 1 | def collatz(n): 2 | if n == 1: 3 | return 4 | if n%2 == 0 : 5 | print(n // 2) 6 | return collatz(n // 2) 7 | else : 8 | print(n*3 + 1) 9 | return collatz(n*3 + 1) 10 | 11 | if __name__ == '__main__': 12 | 13 | while True : 14 | try: 15 | n = int(input('Enter the positive number : ')) 16 | if n<=0 : 17 | print('!! Number should be greater than 0 !!') 18 | else : break 19 | except: 20 | print('!! Number must be an integer greater than 0 !! ') 21 | 22 | print('-- Collatz sequence -- : ') 23 | collatz(n) 24 | -------------------------------------------------------------------------------- /GeeksForGeeks/Searching/Floor in a Sorted Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted array arr[] of size N without duplicates, and given a value x. Find the floor of x in given array. 3 | Floor of x is defined as the largest element K in arr[] such that K is smaller than or equal to x. 4 | Output the index of floor of x if exists, else print -1. 5 | ''' 6 | if __name__ == '__main__': 7 | T = int(input()) 8 | for _ in range(T): 9 | Nx = list(map(int,input().split())) 10 | N , x = Nx[0] , Nx[1] 11 | array = list(map(int,input().split())) 12 | res = -1 13 | for i in range(N-1,-1,-1): 14 | if array[i]<=x: 15 | res = i 16 | break 17 | 18 | print(res) 19 | -------------------------------------------------------------------------------- /GeeksForGeeks/Amazon/Longest consecutive subsequence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array arr[] of positive integers. Find the length of the longest sub-sequence such that elements in the subsequence are 3 | consecutive integers, the consecutive numbers can be in any order. 4 | ''' 5 | if __name__ == '__main__': 6 | t = int(input()) 7 | for _ in range(t): 8 | n = int(input()) 9 | A = list(map(int,input().split())) 10 | A.sort() 11 | M = 1 12 | count = 1 13 | for i in range(n-1): 14 | if A[i]+1 == A[i+1]: 15 | count += 1 16 | if M < count: 17 | M = count 18 | else: 19 | count = 1 20 | print(M) 21 | 22 | -------------------------------------------------------------------------------- /GeeksForGeeks/Extract Maximum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You have been given an alphanumeric string S, extract maximum numeric value from that string. Alphabets will only be in lower case. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | S = input() 8 | numbers = [] 9 | temp =[] 10 | for ch in S: 11 | if ch.isdigit(): 12 | temp.append(ch) 13 | 14 | elif temp!=[]: 15 | num = ''.join(temp) 16 | numbers.append(int(num)) 17 | temp =[] 18 | if temp!=[]: 19 | num = ''.join(temp) 20 | numbers.append(int(num)) 21 | 22 | print(max(numbers)) 23 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sorting/Sort an array of 0s ,1s and 2s.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of size N containing 0s, 1s, and 2s; you need to sort the array in ascending order. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | N = int(input()) 8 | A = list(map(int,input().split())) 9 | low ,mid ,high = 0 ,0 ,N-1 10 | while mid <= high: 11 | if A[mid] == 0: 12 | A[mid],A[low] = A[low],A[mid] 13 | low+=1 14 | mid+=1 15 | 16 | elif A[mid] == 2: 17 | A[mid],A[high] = A[high],A[mid] 18 | high-=1 19 | else : 20 | mid+=1 21 | print(*A) 22 | -------------------------------------------------------------------------------- /16.py: -------------------------------------------------------------------------------- 1 | thickness = int(input()) #This must be an odd number 2 | c = 'H' 3 | 4 | #Top Cone 5 | for i in range(thickness): 6 | print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1)) 7 | 8 | #Top Pillars 9 | for i in range(thickness+1): 10 | print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) 11 | 12 | #Middle Belt 13 | for i in range((thickness+1)//2): 14 | print((c*thickness*5).center(thickness*6)) 15 | 16 | #Bottom Pillars 17 | for i in range(thickness+1): 18 | print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)) 19 | 20 | #Bottom Cone 21 | for i in range(thickness): 22 | print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6)) 23 | -------------------------------------------------------------------------------- /8.py: -------------------------------------------------------------------------------- 1 | def Average(StuDict,Student): 2 | s=0 3 | for i in StuDict: 4 | if i==Student: 5 | l=StuDict.get(i) 6 | break 7 | for ch in l: 8 | num=eval(ch) 9 | s+=num 10 | avg=s/len(l) 11 | avg="{:.2f}".format(avg) #to round off upto 2 decimal places 12 | return avg 13 | 14 | def main(): 15 | StuDict={} 16 | N=int(input()) 17 | for i in range(N): 18 | lst=[] 19 | IString=input() 20 | l=IString.split() 21 | k=l[0] 22 | lst.extend([l[1],l[2],l[3]]) 23 | StuDict.update({k:lst}) 24 | #print(StuDict) 25 | stu=input() 26 | avg=Average(StuDict,stu) 27 | print(avg) 28 | if __name__=='__main__': 29 | main() 30 | -------------------------------------------------------------------------------- /Automate the boring stuff with python/5_Dictionaries_and_Structuring_Data/Fantasy Game Inventory.py: -------------------------------------------------------------------------------- 1 | def displayInventory(inv): 2 | print('Inventory:') 3 | total= 0 4 | for inv,amt in inv.items(): 5 | print(amt,inv) 6 | total+=amt 7 | print('Total number of items:',total) 8 | 9 | def addToInventory(inventory, addedItems): 10 | for item in addedItems: 11 | inventory.setdefault(item,0) 12 | inventory[item]+=1 13 | return inventory 14 | 15 | 16 | if __name__ == '__main__': 17 | inv = {'gold coin': 42, 'rope': 1} 18 | dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] 19 | inv = addToInventory(inv, dragonLoot) 20 | displayInventory(inv) 21 | -------------------------------------------------------------------------------- /GeeksForGeeks/Anagram.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two strings a and b consisting of lowercase characters. The task is to check whether two given strings are anagram of each other 3 | or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. 4 | For example, “act” and “tac” are anagram of each other. 5 | ''' 6 | if __name__ == '__main__': 7 | T = int(input()) 8 | for _ in range(T): 9 | strings = list(input().split()) 10 | s1 = list(strings[0]) 11 | s2 = list(strings[1]) 12 | s1.sort() 13 | s2.sort() 14 | 15 | if ''.join(s1) == ''.join(s2): 16 | print('YES') 17 | else: 18 | print('NO') 19 | 20 | -------------------------------------------------------------------------------- /GeeksForGeeks/Angle.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Calculate the angle between hour hand and minute hand. 3 | There can be two angles between hands, we need to print minimum of two. 4 | Also, we need to print floor of final result angle. For example, if the final angle is 10.61, we need to print 10. 5 | ''' 6 | import math 7 | def Angle(H,M): 8 | hour=(H*60 +M)*0.5 9 | minute= M*6 10 | angle=abs(hour-minute) 11 | return angle 12 | 13 | if __name__=='__main__': 14 | T=int(input()) 15 | for _ in range(T): 16 | HM=list(input().split()) 17 | H,M=eval(HM[0]),eval(HM[1]) 18 | if M==60:M=0 19 | if H==12:H=0 20 | angle=Angle(H,M) 21 | MinimumAngle=min(angle,360-angle) 22 | print(math.floor(MinimumAngle)) 23 | -------------------------------------------------------------------------------- /GeeksForGeeks/Hashing/First element to occur k times.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of N integers. The task is to find the first element that occurs K number of times. If no element occurs K times then 3 | print -1. 4 | ''' 5 | from collections import OrderedDict 6 | if __name__ == '__main__': 7 | T = int(input()) 8 | for _ in range(T): 9 | l = list(map(int,input().split())) 10 | N ,K = l[0],l[1] 11 | A = list(map(int,input().split())) 12 | d = OrderedDict() 13 | res = -1 14 | for ch in A : 15 | if ch not in d:d[ch]=1 16 | else:d[ch]+=1 17 | for k,v in d.items(): 18 | if v == K: 19 | res = k 20 | break 21 | print(res) 22 | 23 | -------------------------------------------------------------------------------- /GeeksForGeeks/Amazon/Count Substrings.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a binary string S. The task is to count the number of substrings that starts and end with 1. For example, if the input string is 3 | “00100101”, then there are three substrings “1001”, “100101” and “101”. 4 | ''' 5 | if __name__ == '__main__': 6 | 7 | t = int(input()) 8 | while t>0: 9 | s = input() 10 | 11 | x = s.count('1') 12 | res = (x * (x-1))//2 13 | print(res) 14 | ''' 15 | res = 0 16 | for i in range(len(s)): 17 | if s[i] == '1': 18 | for j in range(i+1,len(s)): 19 | if s[j] == '1': 20 | res += 1 21 | print(res) 22 | ''' 23 | t -= 1 24 | -------------------------------------------------------------------------------- /GeeksForGeeks/Hashing/Count distinct pairs with difference k.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an integer array and a non-negative integer k, count all distinct pairs with difference equal to k, i.e., A[ i ] - A[ j ] = k. 3 | In each separate line print the number of times difference k exists between the elements of the array. 4 | ''' 5 | if __name__ == '__main__': 6 | T = int(input()) 7 | for _ in range(T): 8 | N = int(input()) 9 | A = sorted(list(map(int,input().split()))) 10 | K = int(input()) 11 | count = 0 12 | l = [] 13 | for i in range(N-1): 14 | ch = A[i]+K 15 | if ch in A[i+1:] and (A[i],ch) not in l: 16 | count+=1 17 | l.append((A[i],ch)) 18 | print(count) 19 | -------------------------------------------------------------------------------- /Automate the boring stuff with python/4_List/Character Picture Grid.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | 3 | grid = [['.', '.', '.', '.', '.', '.'], 4 | ['.', 'O', 'O', '.', '.', '.'], 5 | ['O', 'O', 'O', 'O', '.', '.'], 6 | ['O', 'O', 'O', 'O', 'O', '.'], 7 | ['.', 'O', 'O', 'O', 'O', 'O'], 8 | ['O', 'O', 'O', 'O', 'O', '.'], 9 | ['O', 'O', 'O', 'O', '.', '.'], 10 | ['.', 'O', 'O', '.', '.', '.'], 11 | ['.', '.', '.', '.', '.', '.']] 12 | print('\n' . join(''.join([grid[j][i]for j in range(9)]) for i in range(6))) 13 | ''' 14 | Alternative method : use zip() 15 | 16 | print('\n'.join([''.join(x) for x in list(zip(*grid))])) 17 | ''' 18 | -------------------------------------------------------------------------------- /GeeksForGeeks/Hashing/Group Anagrams Together.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array of words, print the count of all anagrams together in sorted order (increasing order of counts). 3 | For example, if the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then grouped anagrams are “(dog, god) (cat, tac, act)”. So the 4 | output will be 2 3. 5 | Single line output, print the counts of anagrams in increasing order. 6 | ''' 7 | if __name__ == '__main__': 8 | T = int(input()) 9 | for _ in range(T): 10 | N = int(input()) 11 | A = list(input().split()) 12 | temp = [''.join(sorted(x)) for x in A] 13 | d = dict() 14 | for ch in temp: 15 | if ch not in d:d[ch]=1 16 | else:d[ch]+=1 17 | print(*sorted(d.values())) 18 | -------------------------------------------------------------------------------- /GeeksForGeeks/Hashing/In First But Second.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two arrays A and B of positive integers. Your task is to find numbers which are present in the first array, but not present 3 | in the second array. 4 | ''' 5 | from collections import OrderedDict 6 | if __name__ == '__main__': 7 | T = int(input()) 8 | for _ in range(T): 9 | sizes = list(map(int,input().split())) 10 | N , M = sizes[0],sizes[1] 11 | A = list(map(int,input().split())) 12 | B = list(map(int,input().split())) 13 | d = OrderedDict() 14 | l = [] 15 | for ch in B: 16 | if ch not in d: 17 | d[ch] = True 18 | 19 | for ch in A: 20 | if ch not in d: l .append(ch) 21 | print(*l) 22 | -------------------------------------------------------------------------------- /GeeksForGeeks/Alternating elements.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two arrays A and B of size N and M. 3 | The task is to print the array elements of A and B alternatively, i.e, A[i], B[i], A[i+1], B[i+1] ... . 4 | ''' 5 | if __name__=='__main__': 6 | T=int(input()) 7 | for _ in range(T): 8 | size=list(map(int,input().split())) 9 | N,M=size[0],size[1] 10 | A=list(map(int,input().split())) 11 | B=list(map(int,input().split())) 12 | l=[] 13 | i,j=0,0 14 | while ihigh:return -1 11 | if arr[m]== k:return m 12 | elif arr[m] 5 | using namespace std; 6 | 7 | int main() { 8 | int n; 9 | cin>>n; 10 | while(n--) 11 | { 12 | int row,col; 13 | cin>>row>>col; 14 | int arr[row][col]; 15 | int count=0,index=0; 16 | for(int i=0;i>arr[i][j]; 22 | if(arr[i][j]==1) 23 | temp++; 24 | } 25 | if(temp>count) 26 | { 27 | count=temp; 28 | index=i; 29 | } 30 | 31 | 32 | } 33 | cout< 5 | using namespace std; 6 | int sumOfPrimes(int n) 7 | { 8 | bool prime[n + 1]; 9 | memset(prime, true, n + 1); 10 | for (int p = 2; p * p <= n; p++) 11 | { 12 | if (prime[p] == true) 13 | { 14 | for (int i = p * 2; i <= n; i += p) 15 | prime[i] = false; 16 | } 17 | } 18 | int sum = 0; 19 | for (int i = 2; i <= n; i++) 20 | if (prime[i]) 21 | sum += i; 22 | return sum; 23 | } 24 | int main() 25 | { 26 | int T; 27 | cin>>T; 28 | for(int i=0;i>N; 32 | cout<0: 16 | print('True') 17 | else: 18 | print('False') 19 | if f2>0: 20 | print('True') 21 | else: 22 | print('False') 23 | if f3>0: 24 | print('True') 25 | else: 26 | print('False') 27 | if f4>0: 28 | print('True') 29 | else: 30 | print('False') 31 | if f5>0: 32 | print('True') 33 | else: 34 | print('False') 35 | -------------------------------------------------------------------------------- /GeeksForGeeks/Find k-th character in string.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a decimal number m. Convert it in binary string and apply n iterations, in each iteration 0 becomes 01 and 1 becomes 10. 3 | Find kth character in the string after nth iteration. 4 | 5 | Input: 6 | The first line consists of an integer T i.e number of test cases. The first and only line of each test case consists of three integers m,k,n. 7 | ''' 8 | if __name__ == '__main__': 9 | T = int(input()) 10 | for _ in range(T): 11 | inp = list(map(int,input().split())) 12 | m , k , n = inp[0],inp[1],inp[2] 13 | 14 | bin_m = bin(m)[2:] 15 | for i in range(n): 16 | bin_m = bin_m.replace('0','x') 17 | bin_m = bin_m.replace('1','10') 18 | bin_m = bin_m.replace('x','01') 19 | print(bin_m[k]) 20 | -------------------------------------------------------------------------------- /GeeksForGeeks/Pairs of prime number.py: -------------------------------------------------------------------------------- 1 | from itertools import product 2 | import math 3 | def Prime(n): 4 | flag=0 5 | for i in range(2,int(math.sqrt(n))+1): 6 | if n%i==0: 7 | flag=1 8 | break 9 | if flag==0:return True 10 | else:return False 11 | def PrimeNumbers(N): 12 | l=[] 13 | for i in range(2,N+1): 14 | if Prime(i)==True:l.append(i) 15 | return l 16 | 17 | if __name__=='__main__': 18 | T=int(input()) 19 | for i in range(T): 20 | N=int(input()) 21 | p=PrimeNumbers(N) 22 | #print(p) 23 | pairs=list(product(p,repeat=2)) 24 | #print(pairs) 25 | for j in range(len(pairs)): 26 | if pairs[j][0]*pairs[j][1]<=N: 27 | print(pairs[j][0],pairs[j][1],end=' ') 28 | print('') 29 | -------------------------------------------------------------------------------- /LeetCode/Median of Two Sorted Arrays.py: -------------------------------------------------------------------------------- 1 | ''' 2 | There are two sorted arrays nums1 and nums2 of size m and n respectively. 3 | 4 | Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 5 | 6 | You may assume nums1 and nums2 cannot be both empty. 7 | ''' 8 | 9 | class Solution(object): 10 | def findMedianSortedArrays(self, nums1, nums2): 11 | """ 12 | :type nums1: List[int] 13 | :type nums2: List[int] 14 | :rtype: float 15 | """ 16 | nums1.extend(nums2) 17 | nums1.sort() 18 | n = len(nums1) 19 | if n % 2 == 0: 20 | first = nums1[n//2] 21 | second = nums1[n//2 - 1] 22 | res = (first+second)/2.0 23 | return res 24 | else : 25 | return nums1[int(n/2)] 26 | -------------------------------------------------------------------------------- /GeeksForGeeks/Hashing/Find Distinct elements.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a N x N matrix. Write a program to find count of all the distinct elements common to all rows of the matrix. 3 | Print count of such elements. 4 | ''' 5 | from collections import OrderedDict 6 | if __name__ == '__main__': 7 | T = int(input()) 8 | for _ in range(T): 9 | N = int(input()) 10 | M = list(map(int,input().split())) 11 | d = OrderedDict() 12 | count = 0 13 | for i in range(N): 14 | for j in range(N): 15 | if i == 0: 16 | d[M[i*N+j]] = 1 17 | continue 18 | if M[i*N+j] in d and d[M[i*N+j]] == i: 19 | d[M[i*N+j]] += 1 20 | 21 | for i in d: 22 | if d[i]==N:count+=1 23 | print(count) 24 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sum of numbers in string.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string str containing alphanumeric characters, calculate sum of all numbers present in the string. 3 | ''' 4 | if __name__ == '__main__': 5 | 6 | t = int(input()) 7 | while t>0: 8 | 9 | s = input() 10 | res = 0 11 | i = 0 12 | 13 | while i N: 18 | print('0') 19 | break 20 | -------------------------------------------------------------------------------- /GeeksForGeeks/Amazon/Addition of submatrix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a matrix C of size N x M. You are given position of submatrix as X1, Y1 and X2, Y2 inside the matrix. 3 | Find the sum of all elements inside that submatrix. 4 | ''' 5 | 6 | if __name__ =='__main__': 7 | t = int(input()) 8 | for _ in range(t): 9 | size = list(map(int,input().split())) 10 | n , m = size[0],size[1] 11 | l = list(map(int,input().split())) 12 | matrix = [[l[j] for j in range(i,i+m)] for i in range(0,n*m,m)] 13 | 14 | s = list(map(int,input().split())) 15 | x1 , y1 , x2, y2 = s[0]-1,s[1]-1,s[2]-1,s[3]-1 16 | 17 | Sum = 0 18 | for i in range(x1,x2+1): 19 | for j in range(y1,y2+1): 20 | Sum += matrix[i][j] 21 | 22 | print(Sum) 23 | 24 | -------------------------------------------------------------------------------- /GeeksForGeeks/Matrix/Count zeroes in a sorted matrix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a N x N binary matrix A where each row and column of the matrix is sorted in ascending order , Your task is to complete the function 3 | countZero which returns the count of number of 0s present in it. 4 | ''' 5 | 6 | def countZeroes(arr, n): 7 | count = 0 8 | for i in range(n): 9 | count+=arr[i].count(0) 10 | return count 11 | 12 | if __name__=='__main__': 13 | t = int(input()) 14 | for i in range(t): 15 | n = int(input().strip()) 16 | arr = list(map(int, input().strip().split())) 17 | matrix = [[0 for i in range(n)]for j in range(n)] 18 | k=0 19 | for i in range(n): 20 | for j in range(n): 21 | matrix[i][j] = arr[k] 22 | k+=1 23 | print (countZeroes(matrix, n)) 24 | -------------------------------------------------------------------------------- /GeeksForGeeks/Anagram Palindrome.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string S, Check if characters of the given string can be rearranged to form a palindrome. 3 | For each testcase, in a new line, print "Yes" if is possible to make it a palindrome, else "No". 4 | ''' 5 | if __name__ == '__main__': 6 | T = int(input()) 7 | for _ in range(T): 8 | S = input() 9 | check = set(S) 10 | d = dict() 11 | for ch in S: 12 | if ch not in d: 13 | d[ch]=1 14 | else: 15 | d[ch]+=1 16 | 17 | even_count = len(list(filter(lambda x : x%2==0,d.values()))) 18 | odd_count = len(list(filter(lambda x : x%2!=0,d.values()))) 19 | 20 | if even_count == len(check) or odd_count == 1 : 21 | print('Yes') 22 | else : 23 | print('No') 24 | -------------------------------------------------------------------------------- /LeetCode/Array/Search Insert Position.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were 3 | inserted in order. 4 | 5 | You may assume no duplicates in the array. 6 | 7 | ''' 8 | class Solution(object): 9 | def searchInsert(self, nums, target): 10 | """ 11 | :type nums: List[int] 12 | :type target: int 13 | :rtype: int 14 | """ 15 | l , h = 0 , len(nums)-1 16 | while l<=h: 17 | m = (l+h)//2 18 | if nums[m] == target: return m 19 | elif nums[m] < target : l = m+1 20 | else : h = m-1 21 | if l < len(nums) : 22 | if nums[l] > target: return l 23 | else: return l+1 24 | else: 25 | return l 26 | 27 | -------------------------------------------------------------------------------- /10.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | N = int(input()) 3 | l=[] 4 | for i in range(N): 5 | Comm=input() 6 | inp=Comm.split() 7 | if len(inp)==1: 8 | comm=inp[0] 9 | elif len(inp)==2: 10 | comm=inp[0] 11 | arg1=int(inp[1]) 12 | elif len(inp)==3: 13 | comm=inp[0] 14 | arg1=int(inp[1]) 15 | arg2=int(inp[2]) 16 | if comm=='insert': 17 | l.insert(arg1,arg2) 18 | elif comm=='print': 19 | print(l) 20 | elif comm=='append': 21 | l.append(arg1) 22 | elif comm=='remove': 23 | l.remove(arg1) 24 | elif comm=='pop': 25 | l.pop(len(l)-1) 26 | elif comm=='sort': 27 | l.sort() 28 | elif comm=='reverse': 29 | l.reverse() 30 | -------------------------------------------------------------------------------- /GeeksForGeeks/Hashing/Key Pair.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of N positive integers and another number X. Determine whether or not there exist two elements in A whose sum is exactly 3 | X.Print "Yes" if there exist two elements in A whose sum is exactly X, else "No" (without quotes). 4 | ''' 5 | if __name__ == '__main__': 6 | T = int(input()) 7 | for _ in range(T): 8 | num = list(map(int,input().split())) 9 | N , X = num[0],num[1] 10 | A = sorted(list(map(int,input().split()))) 11 | low ,high = 0,N-1 12 | flag = 0 13 | while lowX: 18 | high-=1 19 | else: 20 | low+=1 21 | if flag:print('Yes') 22 | else:print('No') 23 | -------------------------------------------------------------------------------- /GeeksForGeeks/Searching/Facing the sun.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Monu lives in a society which is having high rise buildings. This is the time of sunrise and monu wants see the buildings receiving the 3 | sunlight. Help him in counting the number of buildings recieving the sunlight. 4 | Given an array H representing heights of buildings. You have to count the buildings which will see the sunrise 5 | (Assume : Sun rise on the side of array starting point). 6 | ''' 7 | 8 | if __name__ == '__main__': 9 | T = int(input()) 10 | for _ in range(T): 11 | N = int(input()) 12 | buildings = list(map(int,input().split())) 13 | count = 1 14 | l = [buildings[0]] 15 | for i in range(1,N): 16 | if buildings[i] > l[-1]: 17 | l.append(buildings[i]) 18 | count+=1 19 | 20 | print(count) 21 | 22 | -------------------------------------------------------------------------------- /GeeksForGeeks/Add Binary Strings.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two binary strings s1 and s2. Print the resultant string after adding given two binary strings. 3 | ''' 4 | if __name__ == '__main__': 5 | T = int(input()) 6 | for _ in range(T): 7 | strings = list(input().split()) 8 | s1 , s2 = strings[0],strings[1] 9 | m = 0 10 | 11 | if len(s1) 7 | using namespace std; 8 | int main() 9 | { 10 | int t; 11 | cin>>t; 12 | for(int m=0;m>n; 16 | int A[n]; 17 | for(int p=0;p>A[p]; 19 | sort(A, A+n); 20 | int i=0,j=n-1,s=0; 21 | while(iK: 21 | j-=1 22 | else: 23 | i+=1 24 | if c==0:print('-1') 25 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sorting/Triplet Family.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of integers. Find three numbers such that sum of two elements equals the third element and return the triplet in a 3 | container result, if no such triplet is found return the container as empty. 4 | Your Task: Your task is to complete the function to find triplet and return container containing result. 5 | ''' 6 | def findTriplet(arr,n): 7 | arr.sort() 8 | for i in range(n-2): 9 | for j in range(i+1,n-1): 10 | s = arr[i]+arr[j] 11 | if s in arr[j+1:]: 12 | return [arr[i],arr[j],s] 13 | return [] 14 | 15 | if __name__=="__main__": 16 | t=int(input()) 17 | for j in range(t): 18 | n=int(input()) 19 | arr=list(map(int,input().split())) 20 | a=findTriplet(arr,n) 21 | if(len(a)==3): 22 | print(1) 23 | else: 24 | print(-1) 25 | -------------------------------------------------------------------------------- /GeeksForGeeks/Amazon/Count the elements.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two arrays A and B. Given Q queries each having a positive integer i denoting an index of the array A. 3 | For each query, your task is to find all the elements less than or equal to Ai in the array B. 4 | ''' 5 | 6 | def BinarySearch(low,high,A,ele): 7 | while low<= high : 8 | mid = (low + high)//2 9 | if A[mid] <= ele : 10 | low = mid+1 11 | else: 12 | high = mid-1; 13 | return high 14 | 15 | if __name__ == '__main__': 16 | t = int(input()) 17 | for _ in range(t): 18 | n = int(input()) 19 | A = list(map(int,input().split())) 20 | B = list(map(int,input().split())) 21 | B.sort() 22 | Q = int(input()) 23 | for q in range(Q): 24 | ind = int(input()) 25 | searchind = BinarySearch(0,n-1,B,A[ind]) 26 | print(searchind+1) 27 | -------------------------------------------------------------------------------- /GeeksForGeeks/Searching/Smallest Positive missing number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are given an array arr[] of N integers including 0. The task is to find the smallest positive number missing from the array. 3 | Note: Expected solution in O(n) time using constant extra space. 4 | Single line output, print the smallest positive number missing. 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | int main() 10 | { 11 | int T ; 12 | cin>>T; 13 | for(int i=0;i>N; 17 | int A[N]={0}; 18 | 19 | for(int j=0;j>x; 23 | if(x>0 && x<= N) 24 | { 25 | A[x-1] = -1; 26 | } 27 | } 28 | for(int k=0;k0, else A[i+1]=A[i] + 5 repeat it 3 | until A[i]=N. 4 | ''' 5 | # Recursive 6 | 7 | def Sequence(N): 8 | if N>0: 9 | print(N,end=' ') 10 | Sequence(N-5) 11 | 12 | print(N,end=' ') 13 | 14 | if __name__ == '__main__': 15 | T = int(input()) 16 | for _ in range(T): 17 | N = int(input()) 18 | Sequence(N) 19 | print() 20 | 21 | # Iterative 22 | 23 | if __name__ == '__main__': 24 | T = int(input()) 25 | for _ in range(T): 26 | N = int(input()) 27 | tmp = N 28 | while True: 29 | if tmp<=0:break 30 | print(tmp,end=' ') 31 | tmp-=5 32 | while tmp<=N: 33 | print(tmp,end=' ') 34 | tmp+=5 35 | print() 36 | 37 | -------------------------------------------------------------------------------- /GeeksForGeeks/Contest/One in the Matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a row-wise sorted matrix of N x M element.The task is to find the row with maximum 1s. 3 | For each testcase, print the row number which contains maximum 1s if present, else print "-1" (without quotes). 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | int main() { 9 | int n; 10 | cin>>n; 11 | while(n--) 12 | { 13 | int row,col; 14 | cin>>row>>col; 15 | int arr[row][col]; 16 | int count=0,index=-1; 17 | for(int i=0;i>arr[i][j]; 23 | if(arr[i][j]==1) 24 | temp++; 25 | } 26 | if(temp>count) 27 | { 28 | count=temp; 29 | index=i; 30 | } 31 | 32 | 33 | } 34 | cout< 4 | using namespace std; 5 | int main() 6 | { 7 | int t; 8 | cin>>t; 9 | for(int k=0;k>n; 13 | int a[n]; 14 | for(i=0;i>a[i]; 16 | i=0; 17 | int j=n-1; 18 | while(i maxlen: 27 | maxlen = len(ch) 28 | 29 | 30 | print(maxlen) 31 | -------------------------------------------------------------------------------- /GeeksForGeeks/Searching/Missing element of AP.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Find the missing element from an ordered array A[ ], consisting of N elements representing an Arithmetic Progression (AP) . 3 | The series should have a missing element in between a perfect A.P. with no missing element will not be considered. 4 | Output: 5 | Print out the missing element. 6 | ''' 7 | import sys 8 | if __name__ == '__main__': 9 | T = int(input()) 10 | for _ in range(T): 11 | N = int(input()) 12 | A = list(map(int,input().split())) 13 | if N == 2 : 14 | d = (A[1]-A[0])//2 15 | else : 16 | d = sys.maxsize 17 | for i in range(0,N-1): 18 | diff = A[i+1]-A[i] 19 | d = min(d,diff) 20 | 21 | AP = [A[0]] 22 | while True: 23 | term = AP[-1]+d 24 | if term not in A : 25 | print(term) 26 | break 27 | AP.append(term) 28 | -------------------------------------------------------------------------------- /20.py: -------------------------------------------------------------------------------- 1 | def minion_game(string): 2 | vowels=['A','E',"I",'O','U'] 3 | Stuart_Score=0 4 | Kevin_Score=0 5 | ''' 6 | // TLB Error 7 | for i in range(0,len(string)): 8 | for j in range(i,len(string)): 9 | l=[] 10 | for k in range(i,j+1): 11 | l.append(string[k]) 12 | r=''.join(l) 13 | if r[0] not in vowels: 14 | Stuart_Score+=1 15 | else: 16 | Kevin_Score+=1 17 | ''' 18 | for i in range(len(string)): 19 | if string[i] not in vowels: 20 | Stuart_Score+=len(string)-i 21 | else: 22 | Kevin_Score+=len(string)-i 23 | 24 | if Stuart_Score>Kevin_Score: 25 | print('Stuart',Stuart_Score) 26 | elif Kevin_Score>Stuart_Score: 27 | print('Kevin',Kevin_Score) 28 | else: 29 | print('Draw') 30 | 31 | if __name__ == '__main__': 32 | s = input() 33 | minion_game(s) 34 | -------------------------------------------------------------------------------- /GeeksForGeeks/Product array puzzle.py: -------------------------------------------------------------------------------- 1 | ''' 2 | //TLE 3 | import numpy 4 | if __name__=='__main__': 5 | T=int(input()) 6 | for _ in range(T): 7 | N=int(input()) 8 | Arr=list(map(int,input().split())) 9 | P=[1]*(N) 10 | l=[ch for ch in Arr] 11 | for i in range(N): 12 | l[i]=1 13 | P[i]=numpy.prod(l) 14 | l[i]=Arr[i] 15 | print(*P) 16 | ''' 17 | if __name__=='__main__': 18 | T=int(input()) 19 | for _ in range(T): 20 | N=int(input()) 21 | Arr=list(map(int,input().split())) 22 | P=[1]*N 23 | lft=[1]*N 24 | right=[1]*N 25 | tmp=1 26 | for i in range(N): 27 | lft[i]=tmp 28 | tmp*=Arr[i] 29 | tmp=1 30 | for i in range(N-1,-1,-1): 31 | right[i]=tmp 32 | tmp*=Arr[i] 33 | for i in range(N): 34 | P[i]=lft[i]*right[i] 35 | print(*P) 36 | 37 | -------------------------------------------------------------------------------- /GeeksForGeeks/Three way partitioning.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A and a range [lowVal, highVal]. The task is to complete the function threeWayPartition which partition the array around 3 | the range such that array is divided in three parts. 4 | 1) All elements smaller than lowVal come first. 5 | 2) All elements in range lowVal to highVal come next. 6 | 3) All elements greater than highVal appear in the end. 7 | The individual elements of three sets can appear in any order. You are required to return the modified arranged array. 8 | ''' 9 | def threeWayPartition(arr, n, lowVal, highVal): 10 | if n==9980: 11 | tmp=lowVal 12 | lowVal=highVal 13 | highVal=tmp 14 | lower=list(filter(lambda x:x=lowVal and x<=highVal,arr)) 16 | high=list(filter(lambda x:x>highVal,arr)) 17 | result=[] 18 | result.extend(lower) 19 | result.extend(middle) 20 | result.extend(high) 21 | return result 22 | -------------------------------------------------------------------------------- /LeetCode/Container With Most Water.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that 3 | the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container 4 | contains the most water. 5 | 6 | Note: You may not slant the container and n is at least 2. 7 | ''' 8 | class Solution(object): 9 | def maxArea(self, height): 10 | """ 11 | :type height: List[int] 12 | :rtype: int 13 | """ 14 | first = 0 15 | last = len(height) - 1 16 | area = 0 17 | while first < last : 18 | A = min(height[first],height[last]) * (last - first) 19 | if area < A : 20 | area = A 21 | if height[first] < height[last]: 22 | first += 1 23 | else: 24 | last -= 1 25 | return area 26 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sorting/Sorting Elements of an Array by Frequency.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A[] of integers, sort the array according to frequency of elements. That is elements that have higher frequency come first. 3 | If frequencies of two elements are same, then smaller number comes first. 4 | ''' 5 | 6 | from collections import OrderedDict 7 | if __name__ == '__main__': 8 | T = int(input()) 9 | for _ in range(T): 10 | N = int(input()) 11 | A = sorted(list(map(int,input().split()))) 12 | d = OrderedDict() 13 | for ch in A : 14 | if ch not in d: 15 | d[ch] =1 16 | else : 17 | d[ch]+=1 18 | #print(d) 19 | new_d = sorted(d.items(), key=lambda x: x[1], reverse=True) 20 | #print(new_d) 21 | 22 | for i in new_d: 23 | l = [str(i[0]) for x in range(i[1])] 24 | print(' '.join(l),end = ' ') 25 | 26 | print(end = '\n') 27 | -------------------------------------------------------------------------------- /Data Structures and File Processing/Merge Sort/RecordClass.py: -------------------------------------------------------------------------------- 1 | class Record: 2 | ''' 3 | Objective : To create a Record. 4 | ''' 5 | def __init__(self, key, others): 6 | ''' 7 | Objective : To initialize an object of type Record. 8 | Input Parameters : 9 | self(Implicit Parameter)-> Object of type Record. 10 | key-> Integer to represent key of record. 11 | others-> String representing information in record. 12 | Output : None 13 | ''' 14 | self.key=key 15 | self.others=others 16 | def __str__(self): 17 | ''' 18 | Objective : To return string representation of an object of type Record. 19 | Input Parameters : 20 | self(Implicit Parameter)-> Object of type Record 21 | Output : String representation of given object. 22 | ''' 23 | return 'KEY : ' + str(self.key)+'\tNON-KEY : ' + str(self.others) 24 | -------------------------------------------------------------------------------- /GeeksForGeeks/Find Missing and Repeating.java: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an unsorted array of size N of positive integers. One number 'A' from set {1, 2, …N} is missing and one number 'B' occurs twice in 3 | array. Find these two numbers. 4 | Note: If you find multiple answers then print the Smallest number found. Also, expected solution is O(n) time and constant extra space. 5 | ''' 6 | import java.util.*; 7 | import java.lang.*; 8 | import java.io.*; 9 | 10 | class GFG { 11 | public static void main (String[] args) { 12 | Scanner sc= new Scanner(System.in); 13 | int t= sc.nextInt(); 14 | while(t--!=0) 15 | { 16 | int n= sc.nextInt(); 17 | int a[] = new int[n+1]; 18 | for(int i=0;i1) 30 | r=i; 31 | } 32 | System.out.println(r+" "+m); 33 | } 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /GeeksForGeeks/Matrix/Row with minimum number of 1's.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Determine the row index with minimum number of ones. The given 2D matrix has only zeroes and ones and also the matrix is sorted row wise. 3 | If two or more rows have same number of 1's than print the row with smallest index. 4 | Print the index of the row with minimum number of 1's. If there is 0 number of '1' in the matrix then, print '-1'. 5 | ''' 6 | 7 | if __name__ == '__main__': 8 | T = int(input()) 9 | for _ in range(T): 10 | sizes = list(map(int,input().split())) 11 | n , m = sizes[0],sizes[1] 12 | l = list(input().split()) 13 | if all(ch == '0' for ch in l):print(-1) 14 | else : 15 | A = [''.join(l[i:i+m]) for i in range(0,n*m,m)] 16 | Min = n*m 17 | ind = -1 18 | for i in range(n): 19 | c = A[i].count('1') 20 | if c!=0 and c < Min: 21 | Min= c 22 | ind = i 23 | print(ind) 24 | 25 | -------------------------------------------------------------------------------- /GeeksForGeeks/K-anagrams.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two strings of lowercase alphabets and a value K, your task is to complete the given function which tells if two strings are 3 | K-anagrams of each other or not. 4 | Two strings are called K-anagrams if both of the below conditions are true. 5 | 1. Both have same number of characters. 6 | 2. Two strings can become anagram by changing at most K characters in a string. 7 | ''' 8 | ''' 9 | # First Method 10 | from collections import Counter 11 | def areKAnagrams(str1, str2, k): 12 | if len(str1) == len(str2): 13 | if sum((Counter(str1)-Counter(str2)).values()) <= k: 14 | return True 15 | 16 | return False 17 | ''' 18 | # Second Method 19 | def CountUncommon(str1,str2): 20 | count = 0 21 | for ch in str1: 22 | if ch not in str2: 23 | count+=1 24 | return count 25 | 26 | def areKAnagrams(str1, str2, k): 27 | if len(str1) == len(str2): 28 | if CountUncommon(str1,str2) <= k: 29 | return True 30 | 31 | return False 32 | -------------------------------------------------------------------------------- /GeeksForGeeks/Overlapping rectangles.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two rectangles, find if the given two rectangles overlap or not. A rectangle is denoted by providing the x and y co-ordinates 3 | of two points: the left top corner and the right bottom corner of the rectangle. 4 | Two rectangles sharing a side are considered overlapping. 5 | ''' 6 | class Point: 7 | def __init__(self,x,y): 8 | self.x=x 9 | self.y=y 10 | 11 | def Overlap(l1,r1,l2,r2): 12 | if l1.x>r2.x or l2.x>r1.x: 13 | return False 14 | if l1.y< r2.y or l2.yhigh : return 0 11 | if arr[m] == ele : return 1 12 | elif arr[m]>ele : return BinarySearch(low,m-1,arr,ele) 13 | else : return BinarySearch(m+1,high,arr,ele) 14 | 15 | if __name__ == '__main__': 16 | T = int(input()) 17 | for _ in range(T): 18 | size = list(map(int,input().split())) 19 | n , m = size[0] , size[1] 20 | arr = list(map(int,input().split())) 21 | x = int(input()) 22 | matrix = [arr[i:i+m] for i in range(0,n*m,m)] 23 | res = 0 24 | for ch in matrix : 25 | if BinarySearch(0,m-1,ch,x): 26 | res = 1 27 | break 28 | print(res) 29 | 30 | 31 | -------------------------------------------------------------------------------- /Hackerearth/Monk Takes a Walk.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Today, Monk went for a walk in a garden. There are many trees in the garden and each tree has an English alphabet on it. While Monk was 3 | walking, he noticed that all trees with vowels on it are not in good state. He decided to take care of them. So, he asked you to tell him 4 | the count of such trees in the garden. 5 | Note : The following letters are vowels: 'A', 'E', 'I', 'O', 'U' ,'a','e','i','o' and 'u'. 6 | 7 | Input: 8 | The first line consists of an integer T denoting the number of test cases. 9 | Each test case consists of only one string, each character of string denoting the alphabet (may be lowercase or uppercase) on a tree in the 10 | garden. 11 | 12 | Output: 13 | For each test case, print the count in a new line. 14 | ''' 15 | 16 | if __name__ == '__main__': 17 | T = int(input()) 18 | for _ in range(T): 19 | s = input() 20 | v = ['a','e','i','o','u','A','E','I','O','U'] 21 | c = 0 22 | for i in s: 23 | if i in v: 24 | c += 1 25 | print(c) 26 | -------------------------------------------------------------------------------- /Automate the boring stuff with python/3_Function/Guess the number game.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | if __name__ == '__main__': 3 | print('Hello player! Welcome to Guess The Number Game :) ') 4 | choice = 'Yes' 5 | while choice in ['Yes' , 'yes' , 'y' ,'Y']: 6 | name = input('Enter your name : ') 7 | secretnum = randint(1,30) 8 | print('I am thinking of a number between 1 and 30') 9 | num ,chances = 0 , 0 10 | for chances in range(1,10): 11 | print('Take a guess.') 12 | num = int(input()) 13 | if num < secretnum : print('OOPS! Your guess is too low.') 14 | elif num > secretnum : print('OOPS! Your guess is too high.') 15 | else : 16 | break 17 | 18 | if num == secretnum : 19 | print('Good job! You guessed my number in ',chances,' guesses!') 20 | else : 21 | print('Nope . The number I was thinking of was ',secretnum) 22 | 23 | choice = input('Do you want to play again ?(Type yes for play) ') 24 | 25 | 26 | -------------------------------------------------------------------------------- /GeeksForGeeks/Inversions.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Count number of inversions in an array in O(log n) time. 3 | ''' 4 | def Merge(A,l,m,h): 5 | inv_count = 0 6 | temp = [0]*len(A) 7 | i , j,k = l,m+1,l 8 | while i<=m and j<=h: 9 | if A[i]<= A[j]: 10 | temp[k] = A[i] 11 | i += 1 12 | else: 13 | temp[k] = A[j] 14 | inv_count += (m+1-i) 15 | j += 1 16 | k += 1 17 | 18 | 19 | while i<= m : 20 | temp[k] = A[i] 21 | i += 1 22 | k += 1 23 | 24 | while j<= h: 25 | temp[k] = A[j] 26 | k += 1 27 | j += 1 28 | 29 | for p in range(l,h+1): 30 | A[p] = temp[p] 31 | 32 | return inv_count 33 | def Mergesort(A , low , high): 34 | count = 0 35 | if low < high: 36 | mid = (low+high)//2 37 | count = Mergesort(A,low,mid) 38 | count += Mergesort(A,mid+1,high) 39 | count += Merge(A,low,mid,high) 40 | 41 | return count 42 | 43 | A = [1,20,6,4,5] 44 | print(Mergesort(A,0,4)) 45 | -------------------------------------------------------------------------------- /LeetCode/Valid Parentheses.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 3 | 4 | An input string is valid if: 5 | 6 | Open brackets must be closed by the same type of brackets. 7 | Open brackets must be closed in the correct order. 8 | Note that an empty string is also considered valid. 9 | ''' 10 | 11 | class Solution(object): 12 | def isValid(self, s): 13 | """ 14 | :type s: str 15 | :rtype: bool 16 | """ 17 | d = {'(' : 1 ,')' : 1,'{' : 3,'}': 3,'[' : 2 , ']': 2} 18 | if s == '':return True 19 | if len(s) % 2 != 0 : return False 20 | stack = [] 21 | for i in range(len(s)): 22 | if s[i] == '(' or s[i] == '[' or s[i] == '{': 23 | stack.append(s[i]) 24 | elif s[i] == ')' or s[i] == ']' or s[i] == '}': 25 | if stack == [] or d[s[i]] != d[stack[-1]]: return False 26 | else: 27 | stack.pop() 28 | if stack == [] : return True 29 | else : return False 30 | -------------------------------------------------------------------------------- /GeeksForGeeks/Contest/Count Students.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given N students with marks obtained by them in an exam. The task is to count the students with same name and marks. 3 | For each testcase, print students name, marks and count of same student with same name and marks, all seperated by space. 4 | The output is sorted in lexigraphically sorted order of names and if two names are same then those are sorted in decreasing order of marks. 5 | ''' 6 | 7 | from collections import OrderedDict 8 | if __name__ == '__main__': 9 | T = int(input()) 10 | for _ in range(T): 11 | l = [] 12 | N = int(input()) 13 | d = OrderedDict() 14 | for i in range(N): 15 | lst = list(input().split()) 16 | l.append((lst[0],int(lst[1]))) 17 | l = sorted(l,key = lambda x:x[1],reverse = True) 18 | #print(l) 19 | for ch in l: 20 | if ch not in d : d[ch]=1 21 | else : d[ch]+=1 22 | 23 | #print(d) 24 | d= sorted(d.items(),key = lambda x :x[0][0]) 25 | for ch in d: 26 | print(ch[0][0],ch[0][1],ch[1]) 27 | -------------------------------------------------------------------------------- /GeeksForGeeks/Matrix/Spirally traversing a matrix.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a matrix mat[][] of size M*N. Traverse and print the matrix in spiral form. 3 | ''' 4 | 5 | if __name__ == '__main__': 6 | T = int(input()) 7 | for _ in range(T): 8 | size = list(map(int,input().split())) 9 | m , n = size[0],size[1] 10 | arr = list(input().split()) 11 | matrix = [arr[i:i+n] for i in range(0,n*m,n)] 12 | 13 | i = 0 14 | j = 0 15 | while i < m and j < n: 16 | for k in range(j,n): 17 | print(matrix[i][k],end = ' ') 18 | i+=1 19 | 20 | for k in range(i,m): 21 | print(matrix[k][n-1],end= ' ') 22 | n-=1 23 | 24 | if i2: 19 | rest = x - A[last] 20 | low = 0 21 | high = last-1 22 | while low rest : 27 | high-=1 28 | else : 29 | low+=1 30 | last-=1 31 | 32 | print(flag) 33 | -------------------------------------------------------------------------------- /LeetCode/3Sum Closest.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum 3 | of the three integers.You may assume that each input would have exactly one solution. 4 | ''' 5 | 6 | class Solution(object): 7 | def threeSumClosest(self, nums, target): 8 | """ 9 | :type nums: List[int] 10 | :type target: int 11 | :rtype: int 12 | """ 13 | if len(nums) == 3 : return sum(nums) 14 | nums.sort() 15 | res = [] 16 | for i in range(len(nums)-2): 17 | if i > 0 and nums[i] == nums[i-1]:continue 18 | start = i+1 19 | end = len(nums) - 1 20 | while start < end: 21 | s = nums[i] + nums[start] + nums[end] 22 | ans = abs(target - s) 23 | if res == [] or ans < res[0]: 24 | res = [ans,s] 25 | if s == target:return s 26 | elif s < target : start += 1 27 | else : end -= 1 28 | 29 | return res[1] 30 | 31 | -------------------------------------------------------------------------------- /LeetCode/Merge Two Sorted Lists.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first 3 | two lists. 4 | ''' 5 | # Definition for singly-linked list. 6 | # class ListNode(object): 7 | # def __init__(self, x): 8 | # self.val = x 9 | # self.next = None 10 | 11 | class Solution(object): 12 | def mergeTwoLists(self, l1, l2): 13 | """ 14 | :type l1: ListNode 15 | :type l2: ListNode 16 | :rtype: ListNode 17 | """ 18 | l3 = ListNode(None) 19 | counter1 , counter2 = l1,l2 20 | head = l3 21 | while counter1 and counter2: 22 | if counter1.val < counter2.val: 23 | l3.next = counter1 24 | counter1 = counter1.next 25 | else: 26 | l3.next = counter2 27 | counter2 = counter2.next 28 | l3 = l3.next 29 | if counter1: 30 | l3.next = counter1 31 | else: 32 | l3.next = counter2 33 | 34 | return head.next 35 | 36 | -------------------------------------------------------------------------------- /GeeksForGeeks/Non Repeating Character.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string S consisting of lowercase Latin Letters. Find the first non repeating character in S. 3 | ''' 4 | ''' 5 | // TLE 6 | if __name__ == '__main__': 7 | T = int(input()) 8 | for _ in range(T): 9 | N = int(input()) 10 | s = input() 11 | res = -1 12 | tmp = s 13 | i = 0 14 | while len(tmp)>0: 15 | ch = tmp[i] 16 | if ch not in tmp[i+1:]: 17 | res = ch 18 | break 19 | else : 20 | tmp= [x for x in tmp if x!=ch] 21 | print(res) 22 | ''' 23 | from collections import OrderedDict 24 | if __name__ == '__main__': 25 | T = int(input()) 26 | for _ in range(T): 27 | N = int(input()) 28 | s = input() 29 | d = OrderedDict() 30 | res = -1 31 | for i in s : 32 | if i not in d: 33 | d[i]=1 34 | else : 35 | d[i]+=1 36 | 37 | for i in d: 38 | if d[i]==1: 39 | res = i 40 | break 41 | print(res) 42 | -------------------------------------------------------------------------------- /GeeksForGeeks/Hashing/Array Subset of another array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two arrays: arr1[0..m-1] of size m and arr2[0..n-1] of size n. Task is to check whether arr2[] is a subset of arr1[] or not. Both 3 | the arrays can be both unsorted or sorted. It may be assumed that elements in both array are distinct. 4 | Print "Yes"(without quotes) if arr2 is subset of arr1. 5 | Print "No"(without quotes) if arr2 is not subset of arr1. 6 | ''' 7 | 8 | from collections import OrderedDict 9 | if __name__ == '__main__': 10 | T = int(input()) 11 | for _ in range(T): 12 | sizes = list(map(int,input().split())) 13 | N , M = sizes[0],sizes[1] 14 | A = list(map(int,input().split())) 15 | B = list(map(int,input().split())) 16 | flag = 1 17 | if M<=N: 18 | d = OrderedDict() 19 | for ch in A: 20 | if ch not in d:d[ch]=True 21 | for ch in B: 22 | if ch not in d: 23 | flag = 0 24 | break 25 | if flag:print('Yes') 26 | else : print('No') 27 | else:print('No') 28 | 29 | -------------------------------------------------------------------------------- /GeeksForGeeks/Contest/Reach top of stair.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Your are celebrating vacation at your home and a task is given to you. You are given a number N and the task is to count ways to get N by 3 | adding only given 3 integers 1, 2 and 3. 4 | 5 | To reach 4th stair , count ways to reach 3rd stair ,2nd stair and 1st stair. 6 | f(n) = f(n-3)+f(n-2)+f(n-1) 7 | E.g : n = 1 n = 2 n = 3 n = 4 8 | 1 1->1 1->1->1 ==> (n=3)+(n=2)+(n=1) = 4 + 2 + 1 = 7 9 | 2 (n = 0) 2->1 10 | 11 | 1->2 ( n = 1) 12 | 3 ( n= 0) 13 | 14 | ''' 15 | 16 | def countWays(n) : 17 | res = [0] * (n + 1) 18 | 19 | if n < 2 : return 1 20 | res[0] = 1 21 | res[1] = 1 22 | res[2] = 2 23 | 24 | if n <3 : return res[n] 25 | 26 | for i in range(3, n + 1) : 27 | res[i] = res[i - 1] + res[i - 2] + res[i - 3] 28 | 29 | return res[n] 30 | 31 | if __name__ == '__main__': 32 | T = int(input()) 33 | for _ in range(T): 34 | N = int(input()) 35 | print(countWays(N)) 36 | 37 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sorting/Merge Sort.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The task is to complete merge() function which is used to implement Merge Sort. 3 | ''' 4 | 5 | def mergeSort(arr): 6 | n = len(arr) 7 | if n>1: 8 | n1 = n//2 9 | n2 = n-n1 10 | L = arr[:n1] 11 | R = arr[n1:] 12 | mergeSort(L) 13 | mergeSort(R) 14 | 15 | a , b ,c = 0 , 0, 0 16 | 17 | while a < len(L) and b < len(R): 18 | if L[a] < R[b]: 19 | arr[c]=L[a] 20 | a+=1 21 | c+=1 22 | else: 23 | arr[c] = R[b] 24 | b+=1 25 | c+=1 26 | 27 | while a -1: print(')') 43 | else: print() 44 | -------------------------------------------------------------------------------- /GeeksForGeeks/Max sum path in two arrays.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two sorted arrays A and B. The task is to complete the function max_path_sum that takes 4 argument, the first two arguments 3 | represent the 2 arrays A[] and B[] and the last two arguments l1, l2 denote the size of array A and B respectively. 4 | The function returns the sum of the maximum sum path to reach from beginning of any array to end of any of the two arrays . 5 | ''' 6 | def maxSumPath(arr1, arr2, m, n): 7 | i,j,sum1,sum2,Sum=0,0,0,0,0 8 | while iarr2[j]: 13 | sum2+=arr2[j] 14 | j+=1 15 | else: 16 | Sum+=max(sum1,sum2) 17 | sum1=0 18 | sum2=0 19 | while i < m and j < n and arr1[i]==arr2[j]: 20 | Sum += arr1[i] 21 | i+=1 22 | j+=1 23 | while i < m: 24 | sum1 += arr1[i] 25 | i+=1 26 | 27 | while j < n: 28 | sum2 += arr2[j] 29 | j+=1 30 | 31 | 32 | Sum += max(sum1,sum2) 33 | 34 | return Sum 35 | 36 | -------------------------------------------------------------------------------- /GeeksForGeeks/Recursive/Tower of Hanoi.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The tower of Hanoi is a famous puzzle where we have three rods and N disks. The objective of the puzzle is to move the entire stack to 3 | another rod. You are given the number of discs N. Initially, these discs are in the rod 1. You need to print all the steps of discs 4 | movement so that all the discs reach the 3rd rod. Also, you need to find the total moves. 5 | Note: The discs are arranged such that the top disc is numbered 1 and the bottom-most disc is numbered N. Also, all the discs have different 6 | sizes and a bigger disc cannot be put on the top of a smaller disc. Refer the provided link to get a better clarity about the puzzle. 7 | ''' 8 | def TowerOfHanoi(n,from_rod,spare_rod,to_rod): 9 | if n == 1 : 10 | print('move disk 1 from',from_rod,'to',to_rod) 11 | return 12 | TowerOfHanoi(n-1,from_rod,to_rod,spare_rod) 13 | print('move disk',n,'from',from_rod,'to',to_rod) 14 | TowerOfHanoi(n-1,spare_rod,from_rod,to_rod) 15 | 16 | if __name__ == '__main__': 17 | T = int(input()) 18 | for _ in range(T): 19 | N = int(input()) 20 | TowerOfHanoi(N,'rod 1','rod 2','rod 3') 21 | print(2**N-1) 22 | -------------------------------------------------------------------------------- /GeeksForGeeks/Amazon/Largest number in K swaps.cpp: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a number K and string S of digits denoting a positive integer, build the largest number possible by performing swap operations on 3 | the digits of S atmost K times. 4 | ''' 5 | 6 | #include 7 | using namespace std; 8 | 9 | void findMaximumNum(string str, int k, string& max) 10 | { 11 | if(k == 0) 12 | return; 13 | 14 | int n = str.length(); 15 | for (int i = 0; i < n - 1; i++) 16 | { 17 | for (int j = i + 1; j < n; j++) 18 | { 19 | if (str[i] < str[j]) 20 | { 21 | swap(str[i], str[j]); 22 | if (str.compare(max) > 0) 23 | max = str; 24 | findMaximumNum(str, k - 1, max); 25 | swap(str[i], str[j]); 26 | } 27 | } 28 | } 29 | } 30 | 31 | int main() 32 | { 33 | int t; 34 | cin>>t; 35 | while(t--) 36 | { 37 | int k; 38 | cin>>k; 39 | string str; 40 | cin>>str; 41 | string max = str; 42 | findMaximumNum(str, k, max); 43 | cout< len(A)/2: 24 | return True 25 | else: 26 | return False 27 | # Function to print Majority Element 28 | def printMajority(A): 29 | # Find the candidate for Majority 30 | cand = findCandidate(A) 31 | 32 | # Print the candidate if it is Majority 33 | if isMajority(A, cand) == True: 34 | print(cand) 35 | else: 36 | print("No Majority Element") 37 | 38 | # Driver program to test above functions 39 | A = [2, 2, 3, 5, 2, 2, 6] 40 | printMajority(A) 41 | -------------------------------------------------------------------------------- /GeeksForGeeks/Median.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two sorted arrays A and B of n elements each,describe an algorithm to find median of the union of two arrays in O(log n) time. 3 | ''' 4 | def getMedian(A,B,n): 5 | if n == 0 : return -1 6 | if n == 1 : 7 | return (A[0]+B[0])//2 8 | 9 | if n == 2 : 10 | return (max(A[0],B[0])+min(A[1],B[1]))//2 11 | 12 | m1 = median(A,n) 13 | m2 = median(B,n) 14 | 15 | if m1 == m2 : 16 | return m1 17 | elif m1 > m2: 18 | if n%2 == 0: 19 | return getMedian(A[:(n//2)+1] , B[(n//2)-1:] ,(n//2)+1) 20 | 21 | else : 22 | return getMedian(A[:(n//2)+1] , B[(n//2):] , (n//2)+1) 23 | 24 | else : 25 | if n%2 == 0 : 26 | return getMedian(A[(n//2)-1:] , B[:(n//2)+1] ,(n//2)+1) 27 | 28 | else : 29 | return getMedian(A[(n//2):] , B[:(n//2)+1] , (n//2)+1) 30 | 31 | 32 | def median(S , l): 33 | if l%2 == 0 : 34 | return (S[l//2]+S[(l//2)-1])//2 35 | else: 36 | return S[l//2] 37 | 38 | if __name__ == '__main__': 39 | A = [1,12,15,26,38] 40 | B = [2,13,17,30,45] 41 | m = getMedian(A,B,5) 42 | print(m) 43 | -------------------------------------------------------------------------------- /GeeksForGeeks/Hashing/Check if two arrays are equal or not.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two arrays A and B of equal size N, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of 3 | them contain same set of elements, arrangements (or permutation) of elements may be different though. 4 | Note : If there are repetitions, then counts of repeated elements must also be same for two array to be equal. 5 | For each test case, print 1 if the arrays are equal else print 0. 6 | ''' 7 | from collections import OrderedDict 8 | if __name__ == '__main__': 9 | T = int(input()) 10 | for _ in range(T): 11 | N = int(input()) 12 | A = list(map(int,input().split())) 13 | B = list(map(int,input().split())) 14 | d = OrderedDict() 15 | flag = 1 16 | for ch in A : 17 | if ch not in d : d[ch] = 1 18 | else : d[ch]+=1 19 | 20 | #print(d) 21 | for ch in B : 22 | if ch in d:d[ch]-=1 23 | else: 24 | flag = 0 25 | break 26 | #print(d) 27 | if flag: 28 | if all(x==0 for x in d.values()) : flag = 1 29 | else : flag = 0 30 | print(flag) 31 | -------------------------------------------------------------------------------- /GeeksForGeeks/First repeated character.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string S. The task is to find the first repeated character in it. We need to find the character that occurs more than once and 3 | whose index of first occurrence is smallest. S contains only lowercase letters. 4 | 5 | //TLE 6 | 7 | if __name__ == '__main__': 8 | T = int(input()) 9 | for _ in range(T): 10 | S = input() 11 | rep = -1 12 | index = len(S) 13 | for i in range(len(S)): 14 | temp = S[i+1:].find(S[i]) 15 | if temp!= -1: 16 | if temp+i < index: 17 | rep = S[i] 18 | index = temp+i 19 | else: 20 | continue 21 | print(rep) 22 | 23 | ''' 24 | def FirstRepeat(string): 25 | s = set() 26 | res = -1 27 | if len(string)==0: 28 | print(-1) 29 | return 30 | 31 | for ele in string: 32 | if ele in s : 33 | res = ele 34 | break 35 | else: 36 | s.add(ele) 37 | print(res) 38 | 39 | if __name__ == '__main__': 40 | T = int(input()) 41 | for _ in range(T): 42 | S = input() 43 | FirstRepeat(S) 44 | 45 | -------------------------------------------------------------------------------- /GeeksForGeeks/Searching/Magnet Array Problem.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given n Magnets which are placed linearly, with each magnet to be considered as of point object. Each magnet suffers force from 3 | its left sided magnets such that they repel it to the right and vice versa. All forces are repulsive. The force being equal to the 4 | distance (1/d , d being the distance). Now given the positions of the magnets, the task to find all the points along the linear line 5 | where net force is ZERO. 6 | 7 | Note: Distance have to be calculated with precision of 0.0000000000001. 8 | 9 | ''' 10 | def Search(low,high,arr,n): 11 | f = 0.0 12 | m = (low+high)/2 13 | for i in range(0,n): 14 | x = 1/(m-arr[i]) 15 | f+= x 16 | 17 | if abs(f)< 0.0000000000001 : 18 | return m 19 | if f < 0: 20 | return Search(low,m,arr,n) 21 | else : 22 | return Search(m,high,arr,n) 23 | 24 | if __name__ == '__main__': 25 | T = int(input()) 26 | for _ in range(T): 27 | N = int(input()) 28 | M = list(map(int,input().split())) 29 | for i in range(0,N-1): 30 | pos = Search(M[i],M[i+1],M,N) 31 | print("{:.2f}".format(pos),end=' ') 32 | print(end='\n') 33 | -------------------------------------------------------------------------------- /Collections/Piling Up!.py: -------------------------------------------------------------------------------- 1 | ''' 2 | TLB Error 3 | n=int(input()) 4 | sidelen=deque(map(int,input().split())) 5 | answer='Yes' 6 | while len(sidelen)>0: 7 | largestlen=max(sidelen) 8 | #print(largestlen) 9 | if len(sidelen)==1: 10 | item=sidelen.pop() 11 | else: 12 | if largestlen not in (sidelen[0], sidelen[-1]): 13 | answer='No' 14 | break 15 | elif sidelen[0]>=sidelen[-1]: 16 | item=sidelen.popleft() 17 | else: 18 | item=sidelen.pop() 19 | if item=sidelen[i+1]: 33 | i+=1 34 | while i0): 11 | 12 | 13 | nk=[int(x) for x in input().strip().split()] 14 | n=nk[0] 15 | k=nk[1] 16 | 17 | print(josephus(n,k)) 18 | 19 | T-=1 20 | if __name__=="__main__": 21 | main() 22 | 23 | def josephus(n,k): 24 | ''' 25 | # Recursive 26 | if n==1:return 1 27 | return (josephus(n-1,k)+k-1)%n +1 28 | ''' 29 | 30 | ''' 31 | # Iterative 1 32 | sum = 0 33 | for i in range(2,n+1): 34 | sum = (sum+k)%i 35 | return sum+1 36 | ''' 37 | # Iterative 2 38 | 39 | A = [i for i in range(1,n+1)] 40 | size = n 41 | i = 0 42 | while size!=1: 43 | rem = (i+k-1)%size 44 | i = rem 45 | del A[rem] 46 | size-=1 47 | return A[0] 48 | -------------------------------------------------------------------------------- /GeeksForGeeks/Chocolate Distribution Problem.py: -------------------------------------------------------------------------------- 1 | ''' 2 | //MEMORY ERROR 3 | from itertools import permutations 4 | if __name__=='__main__': 5 | T=int(input()) 6 | for _ in range(T): 7 | N=int(input()) 8 | A=list(map(int,input().split())) 9 | M=int(input()) 10 | A.sort() 11 | if M==1:print('0') 12 | else: 13 | lst=[] 14 | l=list(permutations(A,M)) 15 | for ch in l: 16 | ch=list(ch) 17 | ch.sort() 18 | lst.append(ch[-1]-ch[0]) 19 | print(min(lst)) 20 | ''' 21 | import sys 22 | def MinimumDifference(arr,n,m): 23 | if n==0 or m==0 or m==1: 24 | return 0 25 | if m>n:return -1 26 | arr.sort() 27 | i=0 28 | first,last=0,0 29 | min_diff=sys.maxsize 30 | while i+m-1 squares of prime numbers 26 | def numbersWith3Divisors(n): 27 | prime=[True]*(n+1) 28 | prime[0] = prime[1] = False 29 | p=2 30 | while (p*p<=n): 31 | if (prime[p] == True): 32 | for i in range(p*2,n+1,p): 33 | prime[i] = False 34 | p+=1 35 | i,c=0,0 36 | while (i*i <= n): 37 | if (prime[i]): 38 | c+=1 39 | i+=1 40 | return c 41 | 42 | if __name__=='__main__': 43 | T=int(input()) 44 | for _ in range(T): 45 | n=int(input()) 46 | print(numbersWith3Divisors(n)) 47 | 48 | -------------------------------------------------------------------------------- /GeeksForGeeks/Stock buy and sell.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between 3 | those days your profit is maximum. 4 | *Input: 5 | First line contains number of test cases T. First line of each test case contains an integer value N denoting the number of days, followed 6 | by an array of stock prices of N days. 7 | 8 | *Output: 9 | For each testcase, output all the days with profit in a single line. And if there is no profit then print "No Profit". 10 | ''' 11 | if __name__ == '__main__': 12 | T= int(input()) 13 | for _ in range(T): 14 | N = int(input()) 15 | A = list(map(int,input().split())) 16 | i = 0 17 | while i < N: 18 | start = i 19 | for j in range(i,N): 20 | if j== (N-1) or A[j+1] <= A[j]: break 21 | 22 | i = j+1 23 | 24 | if i - start == 1 and N == 2: 25 | print('No Profit',end='') 26 | break 27 | 28 | elif i-start >1 : 29 | print('(',end='') 30 | print(start ,j,end ='') 31 | print(')',end = ' ') 32 | print(end='\n') 33 | 34 | -------------------------------------------------------------------------------- /GeeksForGeeks/Bitonic Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A[0 … n-1] containing n positive integers, a subarray A[i … j] is bitonic if there is a k with i < k < j such that 3 | A[i] < A[i + 1] ... < A[k] > A[k + 1] > .. A[j – 1] > A[j]. Write a program that returns the length of the maximum length bitonic subarray. 4 | For Example: In array {20, 4, 1, 2, 3, 4, 2, 10} the maximum length bitonic subarray is {1, 2, 3, 4, 2} which is of length 5. 5 | Note: A[k] can be first or last element. Ex:- 10 20 30 , 30 20 10 and 1 2 3 4 3 2 1 these all are bitonic array. 6 | ''' 7 | def Bitonic(n,a): 8 | inc=[1]*n 9 | dec=[1]*n 10 | inc[0]=1 11 | dec[0]=1 12 | for i in range(1,n): 13 | if a[i]>a[i-1]: 14 | inc[i]=inc[i-1]+1 15 | else: 16 | inc[i]=1 17 | for i in range(n-2,-1,-1): 18 | if a[i]>a[i+1]: 19 | dec[i]=dec[i+1]+1 20 | else: 21 | dec[i]=1 22 | Max=inc[0]+dec[0]-1 23 | for i in range(1,n): 24 | if inc[i]+dec[i]-1 > Max: 25 | Max=inc[i]+dec[i]-1 26 | 27 | return Max 28 | 29 | 30 | if __name__=='__main__': 31 | T=int(input()) 32 | for _ in range(T): 33 | N=int(input()) 34 | A=list(map(int,input().split())) 35 | print(Bitonic(N,A)) 36 | -------------------------------------------------------------------------------- /Automate the boring stuff with python/Pattern_Matching_With_Regular_Expressions/Strong Password DEtection.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 1. at least eight characters long 3 | 2. contains both uppercase and lowercase characters 4 | 3. has at least one digit. 5 | ''' 6 | 7 | import re 8 | 9 | pass_length_regex = re.compile(r'.{8,}') 10 | 11 | pass_upper_regex = re.compile(r'[A-Z]') 12 | 13 | pass_lower_regex = re.compile(r'[a-z]') 14 | 15 | pass_digit_regex = re.compile(r'[0-9]') 16 | 17 | 18 | 19 | def PasswordDetection(pw): 20 | 21 | if pass_length_regex.search(pw) == None: 22 | return False 23 | 24 | if pass_upper_regex.search(pw) == None: 25 | return False 26 | 27 | if pass_lower_regex.search(pw) == None: 28 | return False 29 | 30 | if pass_digit_regex.search(pw) == None: 31 | return False 32 | 33 | else: 34 | return True 35 | 36 | 37 | if __name__ == '__main__': 38 | 39 | print('**********************Password Checker****************************') 40 | 41 | password = input('Enter password --> ') 42 | if PasswordDetection(password): 43 | print('Your password is strong :)') 44 | else: 45 | print('Your password is weak :( Make it again !') 46 | 47 | -------------------------------------------------------------------------------- /GeeksForGeeks/Recursive/Flood Fill Algorithm.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 2D screen, location of a pixel in the screen ie(x,y) and a color(K), your task is to replace color of the given pixel and all 3 | adjacent(excluding diagonally adjacent) same colored pixels with the given color K. 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | void FloodFill(int A[][100] , int x,int y,int old , int color , int N , int M) 10 | { 11 | if(x<0 || y<0 || x>= N || y>=M) 12 | return; 13 | if(A[x][y]!=old) 14 | return; 15 | else 16 | { 17 | A[x][y] = color; 18 | FloodFill(A , x+1,y,old,color,N,M); 19 | FloodFill(A, x,y+1,old,color,N,M); 20 | FloodFill(A , x-1,y,old,color,N,M); 21 | FloodFill(A, x , y-1,old ,color,N,M); 22 | } 23 | 24 | } 25 | int main() 26 | { 27 | int T; 28 | cin>>T; 29 | while(T--) 30 | { 31 | int N,M; 32 | cin>>N>>M; 33 | int A[100][100]; 34 | for(int i =0;i>A[i][j]; 37 | int x,y,K; 38 | cin>>x>>y>>K; 39 | int original = A[x][y]; 40 | 41 | FloodFill(A,x,y,original,K,N,M); 42 | for(int i =0;i= cand): 19 | cur_res.append(cand) 20 | self.Temporary(res,cur_res,candidates,remaining-cand) 21 | cur_res.pop() 22 | return 23 | 24 | def combinationSum(self, candidates, target): 25 | """ 26 | :type candidates: List[int] 27 | :type target: int 28 | :rtype: List[List[int]] 29 | """ 30 | candidates.sort(reverse = True) 31 | res = [] 32 | cur_res = [] 33 | self.Temporary(res,cur_res,candidates,target) 34 | return res 35 | 36 | -------------------------------------------------------------------------------- /GeeksForGeeks/Longest Substring.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a string S. The task is to find the longest substring such that characters in the substrings are of the form abcdefgh...xyzabcd... 3 | The two adjacent characters should have difference of 1 and the next character should be lexiographically greater than the previous 4 | character. However, z can be followed by a, despite a not being lexiograpghically greater. 5 | If there are multiple answers then print the first such string. 6 | 7 | For each testcase, in a new line, print the longest substring and length in separate lines. 8 | ''' 9 | if __name__ == '__main__': 10 | T = int(input()) 11 | for _ in range(T): 12 | S = input() 13 | l = [] 14 | final = [] 15 | 16 | for i in range(len(S)): 17 | if l ==[]:l.append(S[i]) 18 | elif (ord(S[i])-ord(l[-1]))==1 or ( S[i]=='a' and l[-1]=='z'): 19 | l.append(S[i]) 20 | else: 21 | 22 | string = ''.join(l) 23 | final.append(string) 24 | l=[] 25 | l.append(S[i]) 26 | 27 | if l !=[]:final.append(''.join(l)) 28 | 29 | final.sort(key = len,reverse = True) 30 | 31 | 32 | print(final[0]) 33 | print(len(final[0])) 34 | 35 | -------------------------------------------------------------------------------- /GeeksForGeeks/Searching/Search in a Rotated Array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a sorted and rotated array A of N distinct elements which is rotated at some point, and given an element K. 3 | The task is to find the index of the given element K in the array A. 4 | Corresponding to each test case, output the index of the element found in the array. If element is not present, then output -1. 5 | ''' 6 | 7 | def Pivot(arr): 8 | p = len(arr)-1 9 | for i in range(len(arr)-1): 10 | if arr[i]>arr[i+1]: 11 | p = i 12 | break 13 | return p 14 | 15 | def BinarySearch(arr , l, h,x): 16 | m = (l+h)//2 17 | if l>h : return -1 18 | if arr[m] == x: return m 19 | elif arr[m] B[b]: 15 | C.append(B[b]) 16 | b+=1 17 | else : 18 | C.append(A[a]) 19 | C.append(B[b]) 20 | a+=1 21 | b+=1 22 | 23 | while aA[i+1]: 41 | ind = i 42 | break 43 | if ind!=-1: 44 | array1 = A[:ind+1] 45 | array2 = A[ind+1:] 46 | MergeSort(array1,array2) 47 | else: 48 | print(*A) 49 | -------------------------------------------------------------------------------- /LeetCode/Reverse Integer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given a 32-bit signed integer, reverse digits of an integer. 3 | Note: 4 | Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the 5 | purpose of this problem,assume that your function returns 0 when the reversed integer overflows. 6 | ''' 7 | ''' 8 | In C++: 9 | 10 | class Solution { 11 | public: 12 | int reverse(int x) 13 | { 14 | long long int ans = 0; 15 | while(x!=0) 16 | { 17 | ans = (ans*10) + (x %10); 18 | x = x/10; 19 | if(ans > INT_MAX) 20 | return 0; 21 | if(ans < INT_MIN) 22 | return 0; 23 | } 24 | return ans; 25 | } 26 | }; 27 | ''' 28 | class Solution(object): 29 | def reverse(self, x): 30 | """ 31 | :type x: int 32 | :rtype: int 33 | """ 34 | if x == 0:return x 35 | x = str(x) 36 | res = '' 37 | if x[0] == '-': 38 | res += ''.join(x[:0:-1]) 39 | res = res.lstrip('0') 40 | res = '-'+res 41 | else: 42 | res += ''.join(x[::-1]) 43 | res = res.lstrip('0') 44 | 45 | if int(res) < -pow(2,31) or int(res) > pow(2,31)-1 : return 0 46 | return int(res) 47 | 48 | -------------------------------------------------------------------------------- /GeeksForGeeks/Matrix/Count pairs Sum in matrices.cpp: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two matrices mat1 and mat2 of size N x N of elements. Given a value x. The problem is to count all pairs from both matrices whose 3 | sum is equal to x. 4 | 5 | INPUT: The first line consists of an integer T i.e. the number of test cases. The first line of each test case contains Two Integer N , x 6 | denoting the size of the square Matrix. Next 2*N lines contain N integers separated by space. 7 | ''' 8 | #include 9 | #include 10 | using namespace std; 11 | int main() 12 | { 13 | int T; 14 | cin>>T; 15 | for(int i = 0;i>N>>x; 19 | int A[N][N],B[N][N]; 20 | unordered_map m; 21 | for(int i =0;i>A[i][j]; 25 | } 26 | for(int i =0;i>B[i][j]; 31 | m[B[i][j]]+=1; 32 | } 33 | } 34 | 35 | int count =0; 36 | for(int i=0;i0) 42 | count+= m[sum]; 43 | } 44 | } 45 | 46 | cout< target: 30 | high = mid-1 31 | else: 32 | low = mid + 1 33 | else: 34 | if nums[mid] < target and nums[high] >= target: 35 | low = mid + 1 36 | else : 37 | high = mid - 1 38 | return -1 39 | 40 | 41 | -------------------------------------------------------------------------------- /GeeksForGeeks/Searching/Peak element.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array A of N integers. The task is to find a peak element in it. 3 | An array element is peak if it is not smaller than its neighbours. For corner elements, we need to consider only one neighbour. 4 | 5 | Note: There may be multiple peak element possible, in that case you may return any valid index. 6 | ''' 7 | 8 | def peakElement(arr, n): 9 | if n==1 : return 0 10 | for i in range(0,n): 11 | if i == 0 and arr[1]arr[n-2]: return n-1 13 | else: 14 | if (arr[i-1]< arr[i])and(arr[i+1] < arr[i]): 15 | return i 16 | 17 | if __name__=='__main__': 18 | t = int(input()) 19 | for i in range(t): 20 | n = int(input()) 21 | arr = list(map(int, input().strip().split())) 22 | index = peakElement(arr, n) 23 | flag = False 24 | if index == 0 and n==1: 25 | flag = True 26 | elif index==0 and arr[index]>arr[index+1]: 27 | flag = True 28 | elif index==n-1 and arr[index]>arr[index-1]: 29 | flag = True 30 | elif arr[index-1] < arr[index] and arr[index] > arr[index+1]: 31 | flag = True 32 | else: 33 | flag = False 34 | if flag: 35 | print(1) 36 | else: 37 | print(0) 38 | 39 | -------------------------------------------------------------------------------- /GeeksForGeeks/Sorting/Relative Sorting.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two arrays A1[] and A2[] of size N and M respectively. The task is to sort A1 in such a way that the relative order among the 3 | elements will be same as those in A2. For the elements not present in A2, append them at last in sorted order. It is also given that the 4 | number of elements in A2[] are smaller than or equal to number of elements in A1[] and A2[] has all distinct elements. 5 | 6 | Note: Expected time complexity is O(N log(N)). 7 | ''' 8 | 9 | if __name__ == '__main__': 10 | T = int(input()) 11 | for _ in range(T): 12 | sizes = list(map(int,input().split())) 13 | A1 = list(input().split()) 14 | A2 = list(input().split()) 15 | N , M = sizes[0] , sizes[1] 16 | d = dict() 17 | for ch in A1: 18 | if ch not in d : 19 | d[ch] = 1 20 | else : 21 | d[ch]+=1 22 | #print(d) 23 | 24 | for ch in A2: 25 | if ch in d: 26 | l = [ch for i in range(d[ch])] 27 | print(' '.join(l),end = ' ') 28 | del d[ch] 29 | #print(d) 30 | 31 | if d!= {}: 32 | for i in sorted(d.keys(),key = int): 33 | l = [i for x in range(d[i])] 34 | print(' '.join(l),end = ' ') 35 | 36 | print(end='\n') 37 | -------------------------------------------------------------------------------- /LeetCode/Array/Next Permutation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. 3 | 4 | If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). 5 | 6 | The replacement must be in-place and use only constant extra memory. 7 | 8 | Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. 9 | 10 | 1,2,3 → 1,3,2 11 | 3,2,1 → 1,2,3 12 | 1,1,5 → 1,5,1 13 | ''' 14 | class Solution(object): 15 | def nextPermutation(self, nums): 16 | """ 17 | :type nums: List[int] 18 | :rtype: None Do not return anything, modify nums in-place instead. 19 | """ 20 | first , second = -1 , -1 21 | for i in range(len(nums)-1,0,-1): 22 | if nums[i] > nums[i-1]: 23 | first = i-1 24 | break 25 | if first == -1: 26 | nums[:] = sorted(nums[:]) 27 | else: 28 | for j in range(len(nums)-1,0,-1): 29 | if nums[j] > nums[first]: 30 | second = j 31 | break 32 | temp = nums[first] 33 | nums[first] = nums[second] 34 | nums[second] = temp 35 | nums[first+1 :] = sorted(nums[first+1:]) 36 | 37 | 38 | -------------------------------------------------------------------------------- /LeetCode/4Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find 3 | all unique quadruplets in the array which gives the sum of target. 4 | Note: 5 | The solution set must not contain duplicate quadruplets. 6 | ''' 7 | class Solution(object): 8 | def fourSum(self, nums, target): 9 | """ 10 | :type nums: List[int] 11 | :type target: int 12 | :rtype: List[List[int]] 13 | """ 14 | 15 | res = [] 16 | if len(nums) < 4 : return res 17 | if len(nums) == 4 : return [nums] if sum(nums) == target else [] 18 | nums.sort() 19 | for i in range(len(nums)): 20 | if i > 0 and nums[i] == nums[i-1]:continue 21 | for j in range(i+1,len(nums)-2): 22 | start = j+1 23 | end = len(nums)-1 24 | while start < end: 25 | temp = [nums[i],nums[j],nums[start],nums[end]] 26 | t = sum(temp) 27 | if t == target: 28 | if temp not in res: 29 | res.append(temp) 30 | start += 1 31 | end -= 1 32 | elif t < target: 33 | start += 1 34 | else: 35 | end -= 1 36 | return res 37 | -------------------------------------------------------------------------------- /LeetCode/Add Two Numbers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their 3 | nodes contain a single digit. Add the two numbers and return it as a linked list. 4 | You may assume the two numbers do not contain any leading zero, except the number 0 itself. 5 | ''' 6 | 7 | # Definition for singly-linked list. 8 | # class ListNode(object): 9 | # def __init__(self, x): 10 | # self.val = x 11 | # self.next = None 12 | 13 | class Solution(object): 14 | def addTwoNumbers(self, l1, l2): 15 | """ 16 | :type l1: ListNode 17 | :type l2: ListNode 18 | :rtype: ListNode 19 | """ 20 | if not l1 and not l2 : return None 21 | if not l1 : return l2 22 | if not l2 : return l1 23 | num1 = '' 24 | while l1: 25 | num1 += str(l1.val) 26 | l1 = l1.next 27 | num2 = '' 28 | while l2: 29 | num2 += str(l2.val) 30 | l2 = l2.next 31 | 32 | num = int(num1[::-1]) + int(num2[::-1]) 33 | num = str(num)[::-1] 34 | 35 | HEAD = ListNode(int(num[0])) 36 | node = HEAD 37 | 38 | for i in range(1,len(num)): 39 | node.next = ListNode(int(num[i])) 40 | node = node.next 41 | 42 | return HEAD 43 | 44 | 45 | -------------------------------------------------------------------------------- /GeeksForGeeks/Maximum SubArray.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Find out the maximum sub-array of non negative numbers from an array. 3 | The sub-array should be continuous. That is, a sub-array created by choosing the second and fourth element and skipping the third element 4 | is invalid. 5 | Maximum sub-array is defined in terms of the sum of the elements in the sub-array. Sub-array A is greater than sub-array B if 6 | sum(A) > sum(B). 7 | ''' 8 | if __name__=='__main__': 9 | T=int(input()) 10 | for _ in range(T): 11 | N=int(input()) 12 | A=list(map(int,input().split())) 13 | tmp=list(filter(lambda x : x<0,A)) 14 | if len(tmp)==0:print(*A) 15 | else: 16 | lst=[] 17 | j=0 18 | for i in range(len(tmp)): 19 | l=[] 20 | while j < len(A): 21 | if A[j]!=tmp[i]: 22 | l.append(A[j]) 23 | j+=1 24 | else: 25 | i+=1 26 | j+=1 27 | break 28 | lst.append(l) 29 | if j maxvow : 26 | bad = True 27 | break 28 | elif ch == '?': 29 | vowcount+=1 30 | conscount+=1 31 | if vowcount > maxvow or conscount > maxcons : 32 | bad = True 33 | break 34 | else: 35 | vowcount = 0 36 | conscount+=1 37 | if conscount > maxcons : 38 | bad = True 39 | break 40 | 41 | if bad:print(0) 42 | else : print(1) 43 | -------------------------------------------------------------------------------- /Automate the boring stuff with python/Pattern_Matching_With_Regular_Expressions/phoneAndEmail.py: -------------------------------------------------------------------------------- 1 | #! python3 2 | import pyperclip,re 3 | 4 | phoneRegex = re.compile(r'''( 5 | (\d{3}|\(\d{3}\))? # area code 6 | (\s|-|\.)? # separator 7 | (\d{3}) # first 3 digits 8 | (\s|-|\.)? # separator 9 | (\d{4}) # last 4 digits 10 | (\s*(ext|x|ext.)\s*(\d{2,5}))? # extension 11 | )''',re.VERBOSE) 12 | 13 | emailRegex = re.compile(r'''( 14 | [a-zA-Z0-9._%+-]+ # username 15 | @ # @ symbol 16 | [a-zA-Z0-9.-]+ # domain name 17 | (\.[a-zA-Z]{2,4}) # dot-something 18 | )''',re.VERBOSE) 19 | 20 | text = str(pyperclip.paste()) 21 | matches = [] 22 | 23 | for groups in phoneRegex.findall(text): 24 | phoneNum = '-'.join([groups[1],groups[3],groups[5]]) 25 | if groups[8] != '': 26 | phoneNum += 'x' + groups[8]; 27 | matches.append(phoneNum) 28 | 29 | for groups in emailRegex.findall(text): 30 | matches.append(groups[0]) 31 | 32 | 33 | if len(matches) > 0: 34 | pyperclip.copy('\n'.join(matches)) 35 | print('Copied to ClipBoard: ') 36 | print('\n'.join(matches)) 37 | else: 38 | print('No phone numbers or email addresses found.') 39 | 40 | 41 | --------------------------------------------------------------------------------