0

I'm trying to become comfortable with python. I've been trying some simple activities that I've given in my beginning c++ classes when I was teaching. I did one involving functions and writing a file which worked flawlessly. I thought this one would be easier. It acts like it is in a silent endless loop, but it won't even let me trace it. Can someone see where I am going awry?

# Find Adam Numbers

def isAdamNumber(candidate):
    isAdam = False
    rev = reverse(candidate)
    square = candidate * candidate
    revsq = rev*rev
    if revsq == reverse(square):
        isAdam = True
    return isAdam
    
def reverse(num):
    rev=0
    while num > 0:
        rev = rev * 10 + num%10
        num/=10
    return rev
for x in range (11,25):
    if isAdamNumber(x):
        print(x, " is an adam number\n")
RonD
  • 9
  • 1
  • I think your problem is in the `reverse` function. It returns `inf` for any positive value passed. – Codeman Nov 15 '21 at 03:21
  • Can you share you expected output as well as some comments in the code? I can't seem to understand what you're trying to do. – 3kstc Nov 15 '21 at 03:21
  • @3kstc I think he's trying to find if a given number `x` is an adam number (square of num and square of reverse of num are reverses of each other). – Codeman Nov 15 '21 at 03:23

4 Answers4

2

The quick fix is to change /= with the integer division version, //=

AJ Biffl
  • 493
  • 3
  • 10
1

Inside the reverse function, you are going into an infinite loop. num value always will be greater than 0, therefore the while loop will continuously run. In python, you can get the reverse of the function without much effort. Convert the integer to string and reverse the string and now change the string back to integer.

def reverse(num):
    num_str = str(num)[::-1]
    return int(num_str)

I think this function definition can solve your problem. To visualize the python to learn and teach, use this link

0

num > 0 is never False. Dividing a positive number by 10 repeatedly makes it smaller, but it never becomes zero, so the while loop keeps repeating.

Use //= instead. It rounds to the nearest integer, so it will reach 0.

This also wouldn't reverse numbers (unless I'm missing something). Alternatively, you can use

int(str(num)[::-1])

which converts the number to a string, reverses it using slicing, and turns it back into an integer.

0

The problem has already been addressed by the other answers, so here's the expanded and simplified version of the slicing that's going on [this doesn't actually use slicing]:

def reverse(num):
    rev = ''
    num = str(num)
    for i in range(len(num) - 1, -1, -1):
        rev += num[i]
    return int(rev)

This counts backward from the last element in the string version of num, and adds all the elements of num (in reverse order) to rev.

Codeman
  • 477
  • 3
  • 13