I have written a Python function to solve the Dig Pow
problem, where the goal is to find a number k such that the sum of each digit of n raised to a specific and increasing power equals n * k.
Here is my current code:
def dig_pow(n, p):
if n != int(n):
return -1
stockn = n
tab = []
while n > 0:
newn = n % 10
tab.append(newn)
n //= 10
tab = tab[::-1]
tabRes = []
for i in range(len(tab)):
tabRes.append(pow(tab[i], i + p))
sum_pow = sum(tabRes)
k = sum_pow // stockn
if sum_pow % stockn == 0:
return k
else:
return -1
I would like to get some suggestions on how to improve code readability, and efficiency. Any other recommendations to optimize the code and make it run faster would also be appreciated.