Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a function to a recursive function

Hey guys I don’t know if I can ask this but I’m working on the original files in google collab and I wrote a function that sums all the sizes of the file

import os
def recls_rtsize(argpath):
  sumsize = 0
  for entry in os.scandir(argpath):
    path= argpath+'/'+entry.name
    size= os.path.getsize(path)
    sumsize+=size
  return sumsize
print("total:",recls_rtsize('/var/log'))

But I need a way to make this function a recursive function or if there is some kind of formula or idea to convert no-recursive into recursive

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For example, you could write helper function to process it recursively, although I don’t understand the purpose:

import os


def recls_rtsize(argpath):
    def helper(dirs):
        if not dirs:
            return 0
        path = argpath + '/' + dirs[0].name
        size = os.path.getsize(path)
        return size + helper(dirs[1:])

    return helper(list(os.scandir(argpath)))


print("total:", recls_rtsize('testing_package'))

Explanation:

Let’s say argpath contains several files:

argpath = [file1, file2, file2]

Then the function calls would be:

size(file1) + recls_rtsize([file2, file2]) we pass everything after the first element

size(file1) + size(file2) + recls_rtsize([file3])

size(file1) + size(file2) + size(file3) + recls_rtsize([])
There are no elements left, and we return 0 and start backtracking

size(file1) + size(file2) + size(file3) + 0

size(file1) + size(file2) + (size(file3) + 0)

size(file1) + (size(file2) + (size(file3) + 0))

(size(file1) + (size(file2) + (size(file3) + 0))) # our result

I hope it make sense

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading