0

I am trying to write a recursive function which takes an integer as its parameter and returns the number of pairs of numbers within the integer that sum to 10. For example, findPairs(28164730) would return 3 because 2+8=10, 6+4=10, and 7+3=10.
This is what my code looks like now:

def find(x):
    x = str(x)
    count = 0
    if str((10 - int(x[0]))) in x:
        count = count + 1
        x = x[1:]
        find(x)
    elif len(x) > 1:
        x = x[1:]
        find(x)
    return count

The problem I am having is that the function will always return that the count is 1 because I am calling it again for recursion and it is setting the count back to 0 instead of just adding 1 to the count every time a pair is found. Does anyone know how I can fix this?

3 Answers3

1

One possible solution would be to simplify by e.g. not using recursion at all. See e.g. the following attempt:

def find(x):
    x = str(x)
    count = 0
    for i in range(len(x)-1):

        if str((10-int(x[i]))) in x[i+1:]:
            count += 1

    return count
coffeinjunky
  • 11,254
  • 39
  • 57
  • Perhaps `ctr = {int(d): c for d, c in Counter(x).items()}` and `return sum(ctr[i] * ctr.get(k-i,0) for i in ctr) // 2` for `O(N)`? – hilberts_drinking_problem Aug 10 '19 at 21:50
  • Thanks for that but I am trying to practice recursion by going through some of these practice problems, appreciate the help tho! –  Aug 10 '19 at 22:04
1

Right now, your code isn't using the returned value of the recursive find call; it's just calling find(x). This will fix your problem:

def find(x):
    x = str(x)
    count = 0
    if str((10 - int(x[0]))) in x:
        # count = count + 1
        x = x[1:]
        count = 1 + find(x)
    elif len(x) > 1:
        x = x[1:]
        count = find(x)
    return count
thisisbenmanley
  • 386
  • 2
  • 9
Samha'
  • 369
  • 2
  • 7
-1

Either have a separate function that declares count then calls find(), or set count as a global variable. I think the first method is preferable.

def get_count(x):
  count = 0
  find(str(x))
  return count

Or something like that. Also if you use that method, make sure to remove the count = 0 from the original find function

Amin
  • 908
  • 1
  • 11
  • 23