patternpythonMajor
Python Power function
Viewed 0 times
functionpythonpower
Problem
I'm a freshman in Python world, I used to program in C.
I wrote a function/method that returns the power of a number:
Mine is a logic question (correctly): if I set
Does
I wrote a function/method that returns the power of a number:
def pow(x, y):
powered = x
if y == 0:
return 1
while y > 1:
powered *= x
y -= 1
return poweredMine is a logic question (correctly): if I set
y = 0 then it returns \$1\$, but on the last line of the code I wrote return powered then = x.Does
return work like as break?Solution
return means "Eureka! I have found the answer! It is …." It hands that result back to the caller and stops executing any more code in this function.Unlike
x**y, your function gives incorrect results for negative or non-integer values of y. You should note that caveat in a docstring.The standard way to do counting loops in Python is to use
range() (or, in Python 2, xrange()).To reduce the complexity of your code, you should avoid unnecessary special cases.
def pow(x, y):
"""Raise x to the power y, where y must be a nonnegative integer."""
result = 1
for _ in range(y): # using _ to indicate throwaway iteration variable
result *= x
return resultThis particular looping pattern (starting with some initial value and repeatedly applying an operation to the result) could be reduced to a one-liner:
from functools import reduce # Optional in Python 2, required in Python 3
def pow(x, y):
"""Raise x to the power y, where y must be a nonnegative integer."""
return reduce(lambda result, _: result * x, range(y), 1)This solution is admittedly foreign-looking to a C programmer. The
reduce() function uses 1 as the starting value (equivalent to result = 1 in the first solution). For each _ in range(y), it does result = result * x. lambda is just a way to define a simple function on the spot.A more efficient algorithm would be repeated squaring.
Code Snippets
def pow(x, y):
"""Raise x to the power y, where y must be a nonnegative integer."""
result = 1
for _ in range(y): # using _ to indicate throwaway iteration variable
result *= x
return resultfrom functools import reduce # Optional in Python 2, required in Python 3
def pow(x, y):
"""Raise x to the power y, where y must be a nonnegative integer."""
return reduce(lambda result, _: result * x, range(y), 1)Context
StackExchange Code Review Q#120082, answer score: 25
Revisions (0)
No revisions yet.