Home > Blockchain >  Display n-digit number with same sums on even,uneven indexes. Python
Display n-digit number with same sums on even,uneven indexes. Python

Time:11-03

I need to implement recursive version of the function mentioned in the tittle. My problem is that I don't know how to implemnt it as recursion. I've only done it with loops.

def n_sums(n:int):
    for i in range(10**(n-1),10**n):
        i=str(i)
        sum1=0
        sum2=0
        for j in range(len(i)):
            if j%2==0:
                sum1 =int(i[j])
            else:
                sum2 =int(i[j])

        if sum1==sum2:
            print(i)

CodePudding user response:

Could you do something like this?

def n_sums_recursive(n: int, i: int = 0, sum1: int = 0, sum2: int = 0):
    if i == 0:
        i = 10**(n-1)
    if i < 10**n:
        i = str(i)
        for j in range(len(i)):
            if j % 2 == 0:
                sum1  = int(i[j])
            else:
                sum2  = int(i[j])

        if sum1 == sum2:
            print(i)

        n_sums_recursive(n, int(i) 1, 0, 0)
  • Related