Home > other >  How to convert a function to a recursive function
How to convert a function to a recursive function

Time:11-01

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

CodePudding user response:

Recursive function is the function which calls itself. For example if You are trying to calculate the sum of all files inside some directory You can just loop through files of that directory and summarize the sizes of the files. If directory You are checking for has subdirectories, then you can just put a condition, if directory has subdirs, if it is, then you can call function itself for that subdirectory.

In your case:

import os

def recls_rtsize(argpath):
  sumsize = 0
  for entry in os.scandir(argpath):
    # is directory is some function that checks if this path is a directory
    if entry.id_directory():
      # then call your function for this directory
      size = recls_stsize(entry)
    else:
      path = argpath '/' entry.name
      size = os.path.getsize(path)
    sumsize  = size
  
  return sumsize

print("total:",recls_rtsize('/var/log'))

CodePudding user response:

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

CodePudding user response:

To iterate over files in sub-folders (I assume that this is your goal here) you can use os.walk().

example

  • Related