Skip to content
pramode edited this page Jul 26, 2011 · 6 revisions

Exercises

  1. Write a Python program which will accept the name of a directory from the command line and recursively print the contents of the directory. (DO NOT run external Linux commands from Python - solve this completely in Python. Use the functions os.listdir, os.path.exists, os.path.isfile. Be careful about handling "." and ".." which are two special entries in a directory - "." is another name for the current directory and ".." is another name for the parent directory)

  2. Modify the above program so that it will print names of only those files whose size is greater than 1000 bytes (hint: use os.stat)

  3. Write a program which will discover files whose contents are exactly the same ("duplicate files"). Your program accepts a directory name as command line parameter and checks files in that directory only.

Hint: Read about "MD5 hashes" on the net. There is a python library called "hashlib" which can be used to compute md5/sha hashes. You can MD5-hash the contents of a file and use a Python dictionary to solve this problem easily.

  1. Using a "class", create a simple "Stack" data structure in Python. It should work like this:

           a = Stack()  # create a stack object
           a.push(10)   # push 10
           a.push(20)   # push 20
           i = a.pop()  # "i" should be 20
           i = a.pop()  # "i" should be 10
           k = a.is_empty()  # "k" is True because stack is empty
           i = a.pop()  # An exception, "IndexError", because stack is now empty
    
  2. Extend the stack with an additional operation called "minimum" which will return the minimum element stored in the stack. The "minimum" operation should be implemented in O(1) time (that is, constant time. Note that this is the key requirement of the new design. Finding the minimum should be an operation which takes the same amount of time irrespective of the number of elements in the stack. Sorting, scanning through a list using builtin functions (or your own code) etc are things which are NOT O(1) - so they are not allowed).

          a = Stack()
          a.push(10)
          a.minimum() # returns 10; which is the minimum so far. This operation runs 
                      # in constant time and DOES NOT modify the stack in any way.
          a.push(20)
          a.minimum()  # returns 10
          a.push(9)       
          a.minimum()  # returns 9
          a.pop()
          a.minimum()  # returns 10
          a.pop()
          a.minimum()  # returns 10
    
Clone this wiki locally