A FoxPro to Python Quickie

[Today in the #ThatConference #ThatTrivia Slack board, there was this math question:

“Identify a multi-digit number such that when each digit is raised to the power of itself, and the result of each of those is added together you get the original number.”

eg: 274 = (2 ^ 2) + (7 ^ 7) + (4 ^ 4)

We were given the hint that it’s 4 digits, which was helpful. I quickly wrote this FoxPro script to figure it out for me:

FOR i = 1000 TO 9999
str = STR(i,4)
a = VAL(SUBSTR(str,1,1))
b = VAL(SUBSTR(str,2,1))
c = VAL(SUBSTR(str,3,1))
d = VAL(SUBSTR(str,4,1))
IF (a^a + b^b + c^c +d^d) = i
? i

But then I thought, in honor of Terry Jones’ death (RIP, ya git) I should really figure out how to do this in Python if I’m ever really going to learn. I’ve run through a few online tutorials, but I still had to google how to do for loops, how to convert integers into strings and then parse that string, how exponentiation worked, even how if statements work. Finally got it to this:

for number in range(1000,9999):
    xstr =  [int(x) for x in str(number)]
    tsum =  xstr[0]**xstr[0] + xstr[1]**xstr[1] + xstr[2]**xstr[2] +xstr[3]**xstr[3]
    if tsum == number:

The exercise felt good, like when you’re studying piano and just do simple études to strengthen the muscle memory. I’m not sure anyone’s interested but I’m sharing just in case. Coding is a muscle.






Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.