Skip to main content

Posts

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("...