2
\$\begingroup\$

Attempting to see whether using 196 as a respectively in my program will have a result or not, I made a simple function to test it. Now the 196-Algorithm requires this:

  • Take any positive integer with at least two digits, a

  • Take a and reverse it (for example 23 becomes 32)

  • Now add the new number to a

  • Repeat the process until the a is a palindrome (when reversed, a palindrome's value should still be the same)

This is my function:

def one_nine_six_algorithm(a):
    b = a
    if a > 9:
        while str(b)[::-1] != str(b):
            c = str(b)[::-1]
            b += int(c)
        return b

In this program, I literally did how do the algorithm. The integer, a, is taken in and checked that it is a positive, two-digit number. Then, the algorithm is run in the while loop, where b is the new/current value of a and c is basically b reversed but as a string in able to use [::-1]. Then c as an integer (int(c)) is added to b and is continued until b is a palindrome (checked in the while line). Then it returns b, which is used for whatever reason I need it for.

Now for complicated integers, this might go through a lot of loops and take a lot of time to finish. Is there a more efficient way to improve my program in terms of speed and readability?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ For what it's worth, this question/algorithm (and the oddity of 196 when reversed and added this way) has been around a long time. Just for example, it was in the inaugaral issue of one of the first magazines for small computers: Creative Computing \$\endgroup\$ Commented Mar 8, 2016 at 1:23
  • \$\begingroup\$ a > 9 does not test for a two-digit number, it tests that the number has more than one digit. Is that a flaw in your description of the algorithm? \$\endgroup\$
    – jscs
    Commented Mar 8, 2016 at 2:56

1 Answer 1

3
\$\begingroup\$

Why bother renaming a to b?

This function would be more useful as a generator, because you will be interested in finding the next number in the sequence. That is, you should yield rather than return the result.

You wrote str(b) three times. Once would be better, but that would still be once too many, if you care about performance. Keep in mind that stringifying a number involves allocating an object, some buffer space, some arithmetic, and translation to ASCII behind the scenes. A function to compute the reversed integer yourself, even if it involves writing more code, should be faster.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.