Posts

Showing posts with the label python

Hackerrank Modified Kaprekar Numbers Solution

Image
This is the solution to the Modified Kaprekar Numbers found in the implementation section of the algorithm domain in Hackerrank. A modified Kaprekar number is a positive whole number n with d digits, such that when we split its square into two pieces - a right hand piece r with d digits and a left hand piece l that contains the remaining d or d−1 digits, the sum of the pieces is equal to the original number (i.e. l + r = n) . Screenshot The Code def sendKap(x,s): y=x*x y=str(y) s1=y[:len(y)/2:] s2=y[len(y)/2::] s3=int(s1)+int(s2) if(s3==x): s.append(str(x)) st=input() en=input() s=[] for i in range(st,en+1): if(i>9): sendKap(i,s) elif(i==1): s.append(str(i)) elif(i==9): s.append(str(i)) if(len(s)==0): print 'INVALID RANGE' else: print ' '.join(s) Got any problems feel free to comment them here !

Hackerrank Cavity Map Solution

Image
This is the solution to the Cavity Map problem found in the the implementation section of the Algorithm domain in Hackerrank. The bellow solution is in Python2. In this you are given a square map of size n×n . Each cell of the map has a value denoting its depth. We will call a cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent to it has strictly smaller depth. Two cells are adjacent if they have a common side (edge). You need to find all the cavities on the map and depict them with the uppercase character X. Screenshot: The Code: def mapCavity(arr, n): for i in range(1, n-1): for j in range(1, n-1): if arr[i-1][j] != 'X' and int(arr[i-1][j]) < int(arr[i][j]) and \ arr[i+1][j] != 'X' and int(arr[i+1][j]) < int(arr[i][j]) and \ arr[i][j-1] != 'X' and int(arr[i][j-1]) < int(arr[i][j]) and \ arr[i][j+1] != 'X' and ...

Python Program to find the vowels and consonants from a given input

Image
This is a program in python which displays the vowels and consonants present in the given input with their frequencies. This basically uses Dictionaries in order to store the frequencies of the characters. Screenshot [OutPut] The Code v={'a':0,'e':0,'i':0,'o':0,'u':0,} k={'b':0,'c':0,'d':0,'f':0,'g':0,'h':0,'j':0,'k':0,'l':0, 'm':0,'n':0,'p':0,'q':0,'r':0,'s':0,'t':0,'v':0,'w':0, 'x':0,'y':0,'a':0,} def cle(x): for i in x: if x[i]!=0: print i,':',x[i],' ', print x=raw_input() for i in x: #print "This is :",i if i in v: v[i]+=1 elif i in k: k[i]+=1 print 'Vowels: ', cle(v) print 'Consonants: ', cle(k) Got any suggestions or doubts, drop them here !

Hackerrank Time Conversion Solution

Image
This is the solution to the problem found in the Warmup section of algorithm domain in Hackerrank. This program is done using Python 2. In this you are given time in AM/PM format. Convert this into a 24 hour format. Screenshot The Code x=raw_input() t=x.split(':') if(t[2][2]=='P' or t[2][2]=='p'): if(t[0]!='12'): t[0]=str(12+int(t[0])) elif(t[0]=='12'): t[0]='00' t=':'.join(t) print t[:-2:] Found bugs or got anything to share, do comment here !

Hackerrank Library Fine Solution

Image
This is the solution is in python to the problem found in the warmup section in algorithm domain, in Hackerrank. Screenshot The Code: import sys x=raw_input() y=raw_input() x=x.split() y=y.split() if(int(x[2])>=int(y[2])): if(int(x[2])==int(y[2]) and int(x[1])<int(y[1])): print '0' raise SystemExit if(int(x[1])==int(y[1]) and int(x[0])<int(y[0])): print '0' raise SystemExit if(int(x[2])-int(y[2])!=0): print 10000 elif(int(x[1])-int(y[1])!=0): print 500*(int(x[1])-int(y[1])) elif(int(x[0])-int(y[0])!=0): print 15*(int(x[0])-int(y[0])) else: print '0' else: print '0' Got any suggestions, drop them here !

File Handling in Python

Image
This is the post in which you will learn about the Files in Python. Basically you can, by using this post learn how to create a file, write data and read data from it ! Screenshot Things this code will do: Create a Folder Test Changes the Current Working Directory Creates a file as per your given name Stores the Data you give as input Shows the Data you gave as input The Code: import os # Create a Directory and make it as working dir. os.mkdir("test") os.chdir("test") print "current working Dir: ",os.getcwd() name=raw_input("Give the Name: ") # Open a file and writing into it fo = open(name, "w+") fo.write(raw_input("Give the Data : ")) fo.close() # Open a file and reading it fo = open(name, "r+") str = fo.read(); print "Read The Data :",str fo.close() Got problems ? Ask us anything anytime, we will help you soon !

Matrix Rotation Hackerrank Solution

Image
This is the solution for the problem Matrix Rotation  in Python, found in the algorithm domain of Hackerrank. You are given a 2D matrix, A , of dimension MxN and a positive integer R . You have to rotate the matrix R times and print the resultant matrix. Rotation should be in anti-clockwise direction. Screenshot[Demo] The Code def rotateMat(N,M,l,rot,rin,mat): # rotate each layer for level in range(l): r = rot % len(rin[level]) rin[level] = rin[level][r:] + rin[level][:r] # fill the array with the rotated elements for level in range(l): top = (N-1) - 2 * level side = (M-1) - 2 * level for i in range(top): mat[level][level + i] = rin[level].pop(0) # right for j in range(side): mat[level + j][level + top] = rin[level].pop(0) # down for i in range(top): mat[lev...

Hackerrank Sherlock and Anagram Solution

Image
This is the solution to the Sherlock and Anagram problem found in the strings section of the algorithm domain. Screenshot The Code import collections def solve(x): d = collections.defaultdict(int) lst = list(x) n = len(lst) for i in xrange(n): for l in xrange(1, n-i+1): sub = lst[i: i+l] sub.sort() d["".join(sub)] += 1 s = 0 for v in d.values(): s += v*(v-1)/2 return s for t in xrange(input()): print solve(map(str,raw_input())) Have any Feedback, drop them here !

Bubble Sort In Python

Image
This is a simple program which demonstrates the implementation of the bubble sort algorithm in python. The complexity of the program is O(n 2 ) . The Input is taken from the console and then appended to a list, which is further processed . Output Screen: Program : print 'Enter the list of elements followed by space:' x=raw_input(); x=map(int,x.split()) for i in range(0, len(x)-1): for j in range(0,len(x)-i-1): if(x[j]>x[j+1]): swp=x[j] x[j]=x[j+1] x[j+1]=swp print x Found suggestions, Please comment them here !

Hackerrank String Reduction Solution

Image
This is the solution to the program, solved in python. The Question can be found in the Algorithm domain of Hackerrank. Problem Statement: Given a string consisting of letters, a, b and c, we can perform the following operation: Take any two adjacent distinct characters and replace them with the third character. For example, if 'a' and 'c' are adjacent, they can replaced by 'b'. Find the smallest string which we can obtain by applying this operation repeatedly? Screenshots[Demo] The Code: def cnt(x): m={} m['a']=0;m['b']=0;m['c']=0 for c in x: if c not in m: m[c]=1 else: m[c]+=1 return m def red(x): xm=cnt(x) print x,xm if((xm['a']==0 and xm['b']==0 ) or (xm['a']==0 and xm['c']==0 ) or (xm['b']==0 and xm['c']==0)): return len(x); if((xm['a']%2==0 and xm['b']%2==0 and xm['c']%2==0) or (...

Hackerrnak Common Child Solution

Image
This is the solution to the problem found in the algorithm domain. This solution is made using Python. Screenshots The Code def cc(x,y): z=[[0 for j in range(len(y)+1)] for i in range(len(x)+1)] for i, a in enumerate(x): for j, b in enumerate(y): if a == b: z[i+1][j+1] = z[i][j] + 1 else: z[i+1][j+1] = \ max(z[i+1][j], z[i][j+1]) return z[-1][-1] x = raw_input() y = raw_input() print cc(x,y) Got Bugs, Suggestions, Drop them here !

Hackerrank Palindrome Index Solution

Image
This is the solution to the problem Palindrome Index, which can be found in the Algorithm domain. The bellow solution is coded in python. Screenshots The Code def isPal(s): for i in xrange(len(s)/2): if s[i] != s[len(s)-i-1]: return False return True def solve(s): for i in xrange((len(s)+1)/2): if s[i] != s[len(s)-i-1]: if isPal(s[:i]+s[i+1:]): return i else: return len(s)-i-1 return -1 for i in range(0,input()): x=raw_input() print solve(x) Got any comments, drop them here !

Hackerrank Two Strings Solution

Image
This is the solution to the problem found in the Strings section of the Algorithm Domain. The problem statement is we need to print YES if there is at least a substring of length 1 in both the strings, else we need to print NO. The bellow program is done using python. Screenshots[Demo] The Code: def sen(x,y): cnt=0 j=0 for i in range(0,len(x)): for j in range(0,len(y)): if (x[i]==y[j]): cnt=cnt+1 break if(cnt!=0): print "YES" else: print "NO" for i in range(0,input()): x=map(str,set(raw_input())) y=map(str,set(raw_input())) sen(x,y) Found Bugs, Report Us !

Represent any number in Indian Format

Image
This program can convert any given number into the format of Indian Number system. This program is done using python. Basically first the input is passed to a function fix() in which it reverse the number, then if the number's length is less then 3 then it is directly printed or else for first 3 digits of the reversed string a comma is printed and at every even position the comma is printed ! Screenshots The Code def fix(x): z='' i=0 x=x[::-1] if(len(x)<=3): print x[::-1] else: while(i<len(x)): z=z+x[i] if(i==2): z=z+',' elif(i>2 and i<len(x)-1): if((i)%2==0): z=z+',' i=i+1 print z[::-1] for i in range(0, input()): #print '12' x=raw_input() fix(x) Found Suggestions ? Ping them here !

Time In Words Hackerrank Solution

Image
This is the solution to the Time in words in the Implementation section of the Algorithm domain. In this Given the time in numerals we may convert it into wods. Screenshots[Demo] The Code mins = { 1:"one minute", 2:"two minutes", 3:"three minutes", 4:"four minutes", 5:"five minutes", 6:"six minutes", 7:"seven minutes", 8:"eight minutes", 9:"nine minutes", 10:"ten minutes", 11:"eleven minutes", 12:"twelve minutes", 13:"thirteen minutes", 14:"fourteen minutes", 15:"quarter", 16:"sixteen minutes", 17:"seventeen minutes", 18:"eighteen minutes", 19:"nineteen minutes", 20:"twenty minutes", 21:"twenty one minutes", 22:"twenty two minutes", 23:"twenty three minutes",...

Encryption Hackerrank Solution

Image
This is the solution for the Encryption problem in the implementation section of the Algorithm domain. In this An English text needs to be encrypted using the following encryption scheme. First, the spaces are removed from the text. Let L be the length of this text. Then, characters are written into a grid, whose rows and columns have the following constraints: ⌊L−−√⌋≤rows≤column≤⌈L−−√⌉, where ⌊x⌋ is floor function and ⌈x⌉ is ceil function Screenshots[Demo] The Code: import math def perform(x,row,col): row=int(row) col=int(col) mat=[['' for i in range(0,col)]for j in range(0,row)] str='' k=0 for i in range(0,row): for j in range(0,col): #print mat if(k<len(x)): mat[i][j]=x[k] k+=1 k=0 for i in range(0,col): for j in range(0,row): str=str+mat[j][k] k+=1 str=str+' ' print str def calc(x): row=math.floor(math.sqrt(len(x))); col=math.ceil(math.sqrt(len(x))); while(1==1): if((row*col)>=len(x)): bre...

Hackerrank Taum and B'day Solution

Image
This is the solution for the Taum and B'day problem in python 2, which can be found in the implementation section of the Algorithm domain. In this problem you will have T test cases,There are two types of gifts that Diksha wants from Taum: one is black and the other is white. To make her happy, Taum has to buy B number of black gifts and W number of white gifts. The cost of each black gift is X units. The cost of every white gift is Y units. The cost of converting each black gift into white gift or vice versa is Z units. You need to help Taum by deducing the minimum amount he needs to spend on Diksha's gifts. Screenshots[Demo] The Code: def bday(x,y): if(y[2]+y[1]<y[0]): print (x[0]*(y[2]+y[1]))+(x[1]*y[1]) elif(y[2]+y[0]<y[1]): print (x[1]*(y[2]+y[0]))+(x[0]*y[0]) else: print (x[0]*y[0])+(x[1]*y[1]) for i in range(0,input()): x=map(int,raw_input().split()) y=map(int,raw_input().split()); bday(x,y) Found Bugs, Please Report ! We ...

Hackerrank Fibonacci Modified Recursive Solution

Image
This is the solution for the Fibonacci Modified Problem found under the dynamic programming section at hackerrank. You need to find the (n+k)th term of the generated series, where nth and (n+1)th term will be supplied as input. The nth and (n+1)th terms, the (n+2)th can be computed by the following relation : Tn+2 = (Tn+1)2 + Tn So, if the first two terms of the series are 0 and 1 and k is 5 then the third term = 1 2 + 0 = 1 fourth term = 1 2 + 1 = 2 fifth term = 2 2 + 1 = 5 Screenshots[Demo] The Code def fibo(a,b,n): if(n==0): return b; else: return fibo(b,b**2+a,n-1) x=raw_input() x=x.split() print fibo(int(x[0]),int(x[1]),int(x[2])-2) Found Bugs, feel free to report them !

Find Optimum number of coins for a given money input

Image
This is a post in which you can use the bellow program to find the optimum number of coins which can substitute the given money. You can infinite 1re, 2rs and 5 rs coin and you want to arrange the input in such a way that you will carry less number of coin with u. This program is not a knapsack implementaion. This program is also not done using the Greedy Approach. This code works fine for all input case. The below program is done using python 2.7 Screenshots/ Demo Above is the screenshot showing the various test cases  The Code: def coins(x): fi=0 tw=0 on=0 while(x>0): if(x>=5): x=x-5; fi=fi+1 elif (x>=2): x=x-2; tw=tw+1 else: x=x-1; on=on+1; print "five: "+str(fi)+"\ntwo:"+str(tw)+"\none:"+str(on) x=input() coins(x) Found Problems, Do place your comment ! ;)

Python program to find the binary equivalent of any decimal

Image
This is a simple program in python to find the binary equivalent of any given decimal base number. This basically takes input as a decimal base number and coverts it into binary base and prints it. Sample Outputs: The Code: def bin(x): b="" if(x==0): #The Binary equivalent of decimal 0 is 0 b=str(0) while(x>0): b=b+str(x%2) #Typecasting an Integer to String x=x/2 b=b[::-1] #Reverse the String print b inp=input() bin(inp) Description: firstly input is taken from the keyboard and stored in inp variable. Then this variable is passed to bin() from where operations are performed and the result is then concatenated in a null string. The concatenation is done by type casting the integer to string i.e. str(x%2) and finally the string b is reversed and then displayed in the console. If helpful, share the code :)