0

I am trying to write a class that initialises certain parameters that are to be use over again in different methods. However when I write a simple recursive algorithm based on initialised values I always get an error message and I really don't know how to solve it myself.

Here is what the algorithm should look like:

def normal_recursion(poly):

    if len(poly) == 1:
        return poly[0]

    else:
        return poly[0] + normal_recursion(poly[1:])

>>> print(normal_recursion([1,2,3]))
>>> 6

which is exactly what should come out.

Now my class looks like:

class Ps2(object):

    def __init__(self, poly):
        self.poly = poly


    def testFunction(self):

        '''Computes the sum of the elements of an indexable object.'''

        if len(self.poly) == 1:
            return self.poly[0]

        else:
            return self.poly[0] + self.testFunction(self.poly[1:])

if:

test = Ps2([1,2,3])

and:

test.testFunction()

then:

TypeError: testFunction() takes 1 positional argument but 2 were given

I have tried all kinds of variations of 'def testFunction(self):' like 'def testFunction(self, self.poly)' but non of them were successful.

However, there is a related question here on Stackoverflow: Python Recursion within Class and I should mention that this algorithm works.

The difference to my problem is that I want to used the values from def init(): as the input for my method.

Anyway, your help is really being appreciated.

0

1 Answer 1

2
def testFunction(self,poly = None):

    '''Computes the sum of the elements of an indexable object.'''
    poly = self.poly if poly is None else poly
    if len(poly) == 1:
        return poly[0]

    else:
        return poly[0] + self.testFunction(poly[1:]) #since you send it an argument here you must have a argument in the function declaration
Sign up to request clarification or add additional context in comments.

1 Comment

Just changed the comment. Great help really. I could not have come up with that approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.