Search code examples
pythonalgorithmrecursion

recursion inside for loop with no change or arguments


I have this simple piece of code which is just a template and doesn't work, but should be the basis of what I want to achieve:

def to_s(x):
    return str(x * 2)

def f(x):
    print(x + "_string")
    x_set = [2,3,4,5]
    for i in x_set:
        var = to_s(x)
        f(var)
f(str(1))

I am stuck at the logic of recursion here, specifically how to determine the base case.

I want to implement it using recursion so that I can have the following output:

"1_string"
"4_string"
"6_string"
"8_string"
"10_string"
  1. The output can have any order, and

  2. I need only one print statement.

The problem is with the iteration from the start of the for loop within nested recursive calls. We could have an expanded version like what I did:

def to_s(x):
    return str(x * 2)

x_set = [2,3,4,5]
def f(x, n):
    if n < 0:
        return 0
    if n == len(x_set):
        print(x + "_string")
    var = to_s(x_set[n-1])
    f(var, n-1)
    if n < len(x_set):
        print(x + "_string")
        
f(str(1), len(x_set))

But that's not what I am interested in, is there a simpler way to do it without adding the addtional n parameter and getting the x_set out?

Update

I have a more complicated computation going on, I just replaced it by print(x + "_string") for simplicity, so the reason for recusion is that I don't want to duplicate code and recursion looks perfect to me in my situation.


Solution

  • To satisfy both of your requirements:

    The output can have any order, and I need only one print statement.

    plus retain your helper function but keep it simple, I'd do something like:

    def two_s(x):
        return str(x * 2)
    
    def f(x, first=True):
        if x:
            print(("1" if first else two_s(x.pop())) + "_string")
    
            f(x, False)
    
    x_set = [2, 3, 4, 5]
    
    f(x_set)