Home > Back-end >  Add a for loop if X = 1
Add a for loop if X = 1

Time:12-28

I'm trying to create a function to translate words to numbers, one of the parameters is "depth" if depth is 1, then the function will know "Ok, I'm translating a word", if depth is 2 the function will know "Now I'm translating a list of words"... etc

The question:

There's a form to add "for" loops if X == Y? This is the current form of the function:
def translate(input_: Union[str, list], depth: int = 3):
    
    if depth == 1: # Just one word
        sum: int = 0
        for char in input_:
            sum  = 17 * ord(char)
        
        return sum

    if depth == 2: # list of words
        buffer: list = []
        
        for word in input_: # for each word in list
            sum: int = 0
            for char in word: # the same as depth == 1
                sum  = 17 * ord(char)

            buffer.append(sum)

    if depth == 3: # list of lists of words
        buffer: list = []

        for lst in input_:
            for word in lst: # the same as depth == 2
                sum: int = 0
                for char in word:
                    sum  = 17 * ord(char)

A pseudocode solution

In Python exist a form to do this?:

If depth > 2:
    
    MAIN.ADDFORLOOP(for LIST in INPUT) <- We added the for loop if there's more than one list to translate

if depth > 1:
    
    MAIN.ADDFORLOOP(for WORD in LIST) <- We added a for loop if there's more than one word


Here, if depth is 3 all for loops will be created, if depth is two, just two for loops will be created, etc

MAIN.LOADALLTHEFORLOOPS()

for char in word:
    # The function goes here

CodePudding user response:

You don't even need depth to resolve your problem. You can check if your object is list or not and use recursion like this:

def translate(input_: Union[str, list]):
    sum = 0
    for i in input_:
        if isinstance(i, list):
            sum  = translate(i)
        else:
            sum  = 17 * ord(i)
    return sum
  • Related