Skip to main content

Posts

Showing posts with the label Python

Find all the existing paths in graph from source to destination node - BFS and DFS

#!/usr/bin/env python import collections graph = {'A': ['B', 'C'],              'B': ['C', 'D'],              'C': ['D'],              'D': ['C'],              'E': ['F'],              'F': ['C']} #Using DFS algorithm #Ref -   https://www.python.org/doc/essays/graphs/ def find_all_paths_dfs(graph, start, end, path = []):   path = path + [start]   #Reachd end return path   if start == end:         return [path]   #No path found found   if not graph.has_key(start):         return []   paths = []   for node in graph[start]:     if node not in path:       new_paths = find_all_paths_dfs(graph, node, end, path)       for new...

Python Program to Print Directory Structure Recursively

os.walk - Recursively Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). Reference - https://docs.python.org/2/library/os.html Python Program - #!/usr/bin/python3 #Python Program to Print Directory and Files Recursively import os def print_dir(path):   for dirName,subdirList,fileList in os.walk(path):     nw_path = dirName.split('/')     print("|",(len(nw_path))*"---","[",os.path.basename(dirName),"]")     for fl in fileList:       print("|",len(nw_path)*"---","->",str(fl)) if __name__ == "__main__":   path = input("Enter the directory path :-")   print_dir(path) Output - surendra@Surendra:~/workspace/Python_Programs$ python3 recurse_print.py Enter the directory path :-/home/surendra...

Program to validate IPv4 Private Address and print the class

#!/usr/bin/python3  #Program to Validate the IP Address and Print the class of the IPV4 Address #  - 10.0.0.0 - 10.255.255.255 -Class A - NetId 8 Bits , Host Id 24 Bits  #   - 172.16.0.0 - 172.31.255.255 - Class B - NetID 12 Bits, Host ID 20 Bits  #   - 192.168.0.0 - 192.168.255.255 - Class C - NetID 16 Bits , Host ID 16 Bits  #   - 127.0.0.0 to 127.255.255.255 - LocalHost / LoopBack  ''' Steps -         Read Input         Validate IP         split and map the input to integer         From list items 0 to 3 , check for IP Range Conditions ''' import re def validate_ip(ip_addr):  if re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',ip_addr):           lst = list(map(int,ip_addr.split('.')))                      #CLASS A Range - 10.0.0.0 - 10.255.255.255 ...

Best Time to Buy and Sell Stock

Program to Implement - Best Time to Buy and Sell Stock  Say you have an array for which the ith element is the price of a given stock on day i.  If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.  Example 1:  Input: [7, 1, 5, 3, 6, 4]  Output: 5  max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)  Example 2:  In this case, no transaction is done, i.e. max profit = 0.  Input: [7, 6, 4, 3, 1]  Output: 0  '''  class Solution(object):      def maxProfit(self, prices):          """          :type prices: List[int]          :rtype: int          """                 # Brute Force - O(n^2)      ...

Pairwise swap elements of a given linked list by changing links

Pairwise swap elements of a given linked list by changing links -  class Solution(object):          #Iterative Solution          def swapPairs(self, head):          """          :type head: ListNode          :rtype: ListNode          """          if(head is None or head.next is None):              return head                        curr = head.next          prev = head          head = curr                    while(True):              sec = curr.next              curr.next = prev              ...

Program to find Sum of Two Integers without + and -

#Sum of Two Integers Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. class Solution(object):     def getSum(self, a, b):         """         :type a: int         :type b: int         :rtype: int         """         #Works For Positive and Negative          if (a == 0): return b         if (b == 0): return a         if (a == 2147483647 and b == -2147483648): return -1         flag = False         if (a < 0 and b < 0):             a = -a             b = -b             flag = True         mask = 0xffffffff         while (b != 0):       ...

TIC TAC TOE GAME - Simulation of 2 Players

#!/usr/bin/python import random # TIC- TAC TOE GAME Simulation (2 Player , Random Positions) # X | O | X # ---------- # X | O | X # ---------- # O | X | X def fill_tic_tac(): #remove from the position list since this position is occupied #randomly select player and position mark on the matrix position = [0,1,2,3,4,5,6,7,8] box = [0]*(9) flag = True #Marking the Box for i in range(9): #Select Random Position in Matrix pos = random.choice(position) #Delete the position from original position position.remove(pos) #Select the Random player and Insert Player 1 -> 'X' ,Player 2 -> 'O' pl = random.randint(1,2) if(pl == 1): box[pos] = 'X' #Check_Winner here if(check_winner(box,'X')): flag = False print("*** Player 1 - X Is Winner *** ") break else: box[pos] = 'Y' #Check Winner Here if(check_winner(box,'Y')): flag = False print("...

Find second largest number in a list

Problem - https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list #Python Program to find Second Largest number in List with Sort #/usr/bin/python3 n = int(input()) if ( n >= 2 and n <= 10): lst = set(list(map(int,input().split()))) #Set's will avoid duplicated new_lst = list(lst) new_lst.sort() print(new_lst[-2]) #  Python Program to find Second Largest number in List Without Sort #/usr/bin/python3 n = int(input()) a = list(map(int,input().split())) f_num = a[0] s_num = 0; for i in range(1,n):  if(f_num > a[i] and a[i] > s_num) :   s_num = a[i]  if(a[i] > f_num):   s_num = f_num;   f_num = a[i] print("Second Large number is :-",s_num) Input - 5 5 2 10 1 2 Output - Second Large number is :- 5

Nested Lists in Python - List Comprehension

Problem -  https://www.hackerrank.com/challenges/nested-list  - Store stundent information using nested list and retrieve the information , use list comprehension #!/usr/bin/python3 #Read input and append the list to main records list using List Compression records = [[input(),float(input())] for i in range(int(input()))] #sort the list using list compression set will avoid duplicates mk_lst  = sorted(set(x[1] for x in records)) #loop through records and if marks matches with second highest sort and display  the names for name in sorted(x[0] for x in records if x[1] == mk_lst[1]):         print(name) Input   -  5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39 Output - Berry Harry

Python program to find Matrix Diagonal Difference

Program Statement – Matrix Diagonal Difference You are given a square matrix of size  N × N . Can you calculate the absolute difference of the sums across the main diagonal and the secondary diagonal? https://www.hackerrank.com/challenges/diagonal-difference Program – Python 3 Version mat = [] nrow = int(input()) for i in range(nrow):   mat.extend(list(map(int,input().split()))) #keep extending the array #Main Diagonal Sum indx,pd_sum = 0,0 for i in range(nrow):   pd_sum += mat[indx]   indx += nrow + 1 #Secondary Diagonal Sum indx,sd_sum = nrow-1,0 for i in range(nrow):   sd_sum += mat[indx]   indx += nrow - 1 print(abs(pd_sum – sd_sum)) Input - 3 11 2 4 4 5 6 10 8 -12 Output - 15

Python List Comprehension

Program Statement – List Comprehension in Python https://www.hackerrank.com/challenges/list-comprehensions print a list of all possible coordinates on the three dimensional grid, such that at any point the sum X i  + Y i  + Z i  is not equal to N. Solution :- Python 3 Version xlist = range(int(input()) + 1) ylist = range(int(input()) + 1) zlist = range(int(input()) + 1) n = int(input()) complst = [[x,y,z] for x in xlist for y in ylist for z in zlist if x + y + z != n] print(complst) Input - 1 1 2 Output - [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]] References -  http://www.thelearningpoint.net/computer-science/learning-python-programming-and-data-structures/learning-python-programming-and-data-structures--tutorial-15--generators-and-list-comprehensions http://www.python-course.eu/list_comprehension.php

Python program to find Symmetric Difference between Sets

Problem statement -https://www.hackerrank.com/challenges/sets Program – Python 3 if int(input()) > 0 : x = set(list(map(int,input().split()))) if int(input()) > 0: y = set(list(map(int,input().split()))) z = sorted(x.symmetric_difference(y)) for i in z: print(i) sets – s ets are un ordered  collection of items. Every element is unique (no duplicates ) !! map() -> map will perform the particular action/function on a list of values.Here it converts to int. symmetric_difference () -> is function of sets which will return the elements which are  unique  in X and Y but not in both sets . Ex – x.symmetric_difference(y)

Program to perform list operation in Python

Task You have to initialize your list L = [] and follow the N commands given in N lines. Commands will be 1 of the 8 commands as given above, other than extend, and each command will have its value separated by space. Follow this example: Sample Input 12 insert 0 5 insert 1 10 insert 0 6 print remove 6 append 9 append 1 sort print pop reverse print Sample Output [6, 5, 10] [1, 5, 9, 10] [9, 5, 1] Python Code Solution 1 - #!/usr/bin/python lst = [] n = int(raw_input()) #Loop till all the commands are read for i in range(0,n): read = raw_input() cmd = read.split() #check for the commands and perform the action if (cmd[0] == 'insert'):     lst.insert(int(cmd[1]),int(cmd[2])) #pos,elem elif(cmd[0] == 'print'):      print lst elif(cmd[0] == 'remove'):      lst.remove(int(cmd[1])) ...

Python program to print Triangle Quest

Problem Statement -  https://www.hackerrank.com/challenges/python-quest-1 Program to print below output with single for loop and no string operation. n = 5 1 22 333 4444 Code - for i in range(1,int(raw_input())):       print int(i- (10*(i/10)))*(((10**i-1))/9) or  print i*(10** (i)-1)/9 Resources - http://math.stackexchange.com/questions/1352084/expressing-the-infinite-sum-1-22-333-4444 https://en.wikipedia.org/wiki/Repdigit Note that for integers greater than 0 and less than 10. ( 10 1 /   9 )   X   1 = 1 ( 10 2 /   9 )   X   2 = 22 ( 10 3 /   9 )   X   3 = 333 ( 10 4 /   9 )   X   4 = 4444 ( 10 5 /   9 )   X   5 = 55555 ( 10 6 /   9 )   X   6 = 666666 ( 10 7 /   9 )   X   7 = 7777777 ( 10 8 /   9 )   X   8 = 88888888 ( 10 9 /   9 )   X   9 = 999999999