
\documentclass{article}

\setlength{\oddsidemargin}{-0.5in}
\setlength{\evensidemargin}{-0.5in}
\setlength{\topmargin}{0.0in}
\setlength{\headheight}{0in}
\setlength{\headsep}{0in}
\setlength{\textwidth}{7.0in}
\setlength{\textheight}{9.5in}
\setlength{\parindent}{0in}
\setlength{\parskip}{0.05in}
\setlength{\columnseprule}{0.3pt}
\usepackage{fancyvrb}
\usepackage{relsize}
\usepackage{hyperref}

\usepackage{listings}

\begin{document}

Name: \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_

Directions: {\bf Work only on this sheet} (on both sides, if needed); do
not turn in any supplementary sheets of paper. There is actually plenty
of room for your answers, as long as you organize yourself BEFORE
starting writing.

{\bf 1.} () The function {\bf findfile()} searches for a file (which
could be a directory) in the specified directory tree, returning the
full path name of the first instance of the file found with the
specified name, or returning None if not found.

For instance, suppose we have the directory tree {\bf /a} shown on
pp.51-52, except that {\bf /b} contains a file {\bf z}.  Then the code

\begin{lstlisting}
print findfile('/a','y')
print findfile('/a','b')
print findfile('/a','u')
print findfile('/a','z')
print findfile('/a/b','z')
\end{lstlisting}

produces the output

\begin{lstlisting}
/a/y
/a/b
None
/a/b/z
/a/b/z
\end{lstlisting}

Fill in the blanks:

\begin{lstlisting}
import            # blank

def findfile(treeroot,flname):
   os.chdir(treeroot)
   currfls = os.listdir('.')
   for fl in currfls:
      if fl == flname:   # blank
   for fl in currfls:
       # blank; insert <= 5 lines of code,
       # possibly including with lesser indentation
\end{lstlisting}

{\bf Solutions:} 

{\bf 1.}

\begin{lstlisting}
import os

# returns full path name of flname in the tree rooted at treeroot;
# returns None if not found; directories do count as finding the file
def findfile(treeroot,flname):
   os.chdir(treeroot)
   currfls = os.listdir('.')
   for fl in currfls:
      if fl == flname:
         return os.path.abspath(fl)
   for fl in currfls:
      if os.path.isdir(fl):
         tmp = findfile(fl,flname)
         if not tmp == None: return tmp
   return None

def main():
   print findfile('/a','y')
   print findfile('/a','u')
   print findfile('/a','z')
   print findfile('/a/b','z')

if __name__ == '__main__': main()
\end{lstlisting}

\end{document}

