-1

I have to do something like below. I have one instance v1 and from there on, I have to create other instances by running certain function over it in a recurring way.

v2 = vclass.makesomething(v1,a).attribute1()
v3 = vclass.makesomething(v2,a).attribute1()
v4 = vclass.makesomething(v3,a).attribute1()
.
.
.

The only thing I thought was using a change in name of variable like having v+str(i) but that is a bad way to proceed to the problem. Is there a way to create a recurring code for this?

May be I have phrased the question badly, but I did not know how should I express the problem.

second method I found to work along with what @Duck suggested,

vtemplist = [vertex1]
for i in range(number_of_instances_needed)):
    vtemplist.append(vclass.makesomething(vtemplist[-1],a).attribute1())
jkhadka
  • 2,443
  • 8
  • 34
  • 56
  • Do you know how often you'll have to do it? I would think the best way would be a `for i in range(start, stop, step)` loop, where you're assigning the attributes to an array. i'm not familiar with python though, so maybe there is some limitation i'm not aware of there. – Orion Jan 15 '16 at 15:34
  • Hey @mykepwnage I was trying to do something along the lines as you suggested and I found above technique to work :) – jkhadka Jan 15 '16 at 19:43

1 Answers1

3
def recur(v, times):
    if (times != 0):
        v = vclass.makesomething(v,a).attribute1()
        return recur(v, times-1)
    return v

Now you can call recur with the initial value of v and how many times you would like to recurse.

Edit: I was assuming you only were interested in the last instance. If not, you can use the following, which will return a list of v objects.

def recur(v, times, lst=[]):
    if (times != 0):
        v = vclass.makesomething(v,a).attribute1()
        lst.append(v)
        return recur(v, times-1, lst)
    return lst
Duck
  • 178
  • 1
  • 11
  • Hey @Duck this works. thanks for this idea. It is as simple as it can get and yet elegant :) I am not from CS background so kind of suck with idea of recursion. – jkhadka Jan 15 '16 at 16:44