What's wrong in this code? please help


#1



def dig_pow(n, p):
    sum = 0
    num = str(n)
    for i in range(len(num)):
        sum = sum + int(num[i])** (p+i)
        return sum
    if sum % int(num) == 0:
        return sum/int(num)
    else:
        return -1


#2

i ran your code:

def dig_pow(n, p):
    sum = 0
    num = str(n)
    for i in range(len(num)):
        sum = sum + int(num[i])** (p+i)
        return sum
    if sum % int(num) == 0:
        return sum/int(num)
    else:
        return -1

print dig_pow(5,4)

and 625 seems correct, can you tell me what kind of problem you are experiencing?


#3

I am unable to pass the sample case. which is dig_pow(89,1)


#4

hm... makes sense, here:

for i in range(len(num)):
        sum = sum + int(num[i])** (p+i)
        return sum

a function ends the moment a return keyword is reached.

So, if a return keyword is reached in a loop, the function still needs to end, so the loop will break

so you want to place return outside/after the loop so the whole loop can run


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.