Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading