1

I wrote a simple code for a simple task, but I keep getting error message

RecursionError: maximum recursion depth exceeded in comparison

I have already spent a lot of time looking into it, but can't seem to figure it out.

def printMultiTable(high):
    i = 1
    while i <= high:
        printMultiTable(i)
        i +=1
printMultiTable(7)

The result I am expecting.

enter image description here

James Z
  • 12,209
  • 10
  • 24
  • 44
Vondoe79
  • 313
  • 4
  • 22

2 Answers2

1

Your function will call itself forever because you are always setting i back to one.

Something like this will not run infinitely:

def printMultiTable(i, high):
    while i <= high:
        i +=1
        printMultiTable(i, high)


printMultiTable(1, 7)

However, I'm not sure if this function has the exact behavior that you want, because you are not clear about what behavior you want. This function will add one to i each time, calling itself until i <= high is false. Hopefully that's what you want. If not, let me know.

edit: Now I see what your desired output is. This should do nicely:

def printMultiTable(low, high): 
    for i in range(low, high + 1):
        for j in range(low, high):
            print i*j, "\t",
        print ""         


printMultiTable(1,7) 
setholopolus
  • 253
  • 3
  • 17
1

If you want to solve this via recursion , then you have to understand some rules of recursion:

Rule no #1:

You must always have some base cases, which can be solved without recursion.

Rule no #2:

For cases that are to be solved recursively, the recursive call must always be a case that makes progress toward a base case.

Here is your solution for recursive approach:

def printMultiTable(high,low,track):
multitable=[]

if track==0:
    return 0
else:
    while high > low:
        multitable.append(high*track)



        high -= 1
    print("multitable of {}".format(track))
    print('--------------------------')


    print(multitable[::-1])
    print('--------------------------')

    high=7

    printMultiTable(high,low,track-1)

print(printMultiTable(7,0,6))

output:

multitable of 6
--------------------------
[6, 12, 18, 24, 30, 36, 42]
--------------------------
multitable of 5
--------------------------
[5, 10, 15, 20, 25, 30, 35]
--------------------------
multitable of 4
--------------------------
[4, 8, 12, 16, 20, 24, 28]
--------------------------
multitable of 3
--------------------------
[3, 6, 9, 12, 15, 18, 21]
--------------------------
multitable of 2
--------------------------
[2, 4, 6, 8, 10, 12, 14]
--------------------------
multitable of 1
--------------------------
[1, 2, 3, 4, 5, 6, 7]
--------------------------
None
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88