Course Content
Python Functions Tutorial
Python Functions Tutorial
Challenge: Recursive File Search
Swipe to start coding
Imagine needing to check whether a specific file exists within a nested dictionary structure representing a file system. Implement a function file_exists
that recursively navigates through folders (dictionary objects) and searches for a file (represented by the string "file"
). Return True
if the file is found; otherwise, return False
.
- Use a
for
loop to iterate through all elements of thefile_system
dictionary using theitems()
method. This retrieves the key (name
) and the value (content
). - Check if
content
is a file (i.e., the string"file"
) and ifname
matchestarget
(the name of the file being searched for). - If both conditions are met, return
True
, indicating that the file has been found. - If content is not a file, check whether it is a folder.
Use the
isinstance()
function, passingcontent
as the first argument anddict
as the second (which checks if the element is a dictionary). - If
content
is a folder, callfile_exists
recursively with the necessary parameters to continue searching inside it. - If the recursive call returns
True
, the file has been found, so returnTrue
. - If no matches are found after checking all folders and files, return
False
.
Solution
Thanks for your feedback!
Challenge: Recursive File Search
Swipe to start coding
Imagine needing to check whether a specific file exists within a nested dictionary structure representing a file system. Implement a function file_exists
that recursively navigates through folders (dictionary objects) and searches for a file (represented by the string "file"
). Return True
if the file is found; otherwise, return False
.
- Use a
for
loop to iterate through all elements of thefile_system
dictionary using theitems()
method. This retrieves the key (name
) and the value (content
). - Check if
content
is a file (i.e., the string"file"
) and ifname
matchestarget
(the name of the file being searched for). - If both conditions are met, return
True
, indicating that the file has been found. - If content is not a file, check whether it is a folder.
Use the
isinstance()
function, passingcontent
as the first argument anddict
as the second (which checks if the element is a dictionary). - If
content
is a folder, callfile_exists
recursively with the necessary parameters to continue searching inside it. - If the recursive call returns
True
, the file has been found, so returnTrue
. - If no matches are found after checking all folders and files, return
False
.
Solution
Thanks for your feedback!