""" Authors: Peter Mawhorter Consulted: Date: 2022-5-1 Purpose: Looping recursion lab practice solutions. """ import os FAMILY = [ "Louise", ["Richard", ["Sarah"], ["Peter", ["Aaron"]], ["John"], ["Ross"]], ["Steven", ["Chris"], ["Michael", ["Mac"], ["Claire"], ["Frances"]]], ["Jeannie", ["Anna"], ["Claire"]], ] def countDescendants(familyTree): """ Returns the total number of people listed in the given tree of descendants. Each entry in the tree is a list where the first element is a string naming the person. The remaining elements are sub-trees for each of that person's children. If someone has no descendants, then their list will just have their name. """ count = 1 for subTree in familyTree[1:]: count += countDescendants(subTree) return count print("Should be 2:") print(countDescendants(FAMILY[1][2])) print("Should be 6:") print(countDescendants(FAMILY[1])) print("Should be 16:") print(countDescendants(FAMILY)) def revealHiddenFiles(directory): """ Recursively traverses the directories under the given one, printing out each hidden file it finds. Hidden files are just files (not directories) whose name starts with '.'. Directories and files are inspected in alphabetical order. """ for fileOrDir in sorted(os.listdir(directory)): fullPath = os.path.join(directory, fileOrDir) if os.path.isfile(fullPath): if fileOrDir.startswith('.'): print(fullPath) # else do nothing else: # assume it's a directory and recurse revealHiddenFiles(fullPath) # implicit base case: there are no directories inside this one print() print("Should have one .DS_Store in each directory, plus .numbers:") revealHiddenFiles('testdir') print("\nCorrect result:") print("""\ testdir/.DS_Store testdir/.hidden/.DS_Store testdir/.numbers testdir/pset/.DS_Store testdir/pset/scene/.DS_Store testdir/pset/shrub/.DS_Store testdir/pset/shrub/images/.DS_Store testdir/remember/.DS_Store""") def listHiddenFiles(directory): """ Works like revealHiddenFiles except returns a list of file paths, rather than printing them. """ result = [] for fileOrDir in sorted(os.listdir(directory)): fullPath = os.path.join(directory, fileOrDir) if os.path.isfile(fullPath): if fileOrDir.startswith('.'): result.append(fullPath) # else do nothing else: # assume it's a directory and recurse result += listHiddenFiles(fullPath) # implicit base case: there are no directories inside this one return result print() print("Should have one .DS_Store in each directory, plus .numbers:") print(listHiddenFiles('testdir')) print("\nCorrect result:") print( "['testdir/.DS_Store', 'testdir/.hidden/.DS_Store', 'testdir/.numbers'," + " 'testdir/pset/.DS_Store', 'testdir/pset/scene/.DS_Store'," + " 'testdir/pset/shrub/.DS_Store', 'testdir/pset/shrub/images/.DS_Store'," + " 'testdir/remember/.DS_Store']" )