asfasf6525 - 1 year ago 146

Python Question

`def closest_power(base, num):`

'''

base: base of the exponential, integer > 1

num: number you want to be closest to, integer > 0

Find the integer exponent such that base**exponent is closest to num.

Note that the base**exponent may be either greater or smaller than num.

In case of a tie, return the smaller value.

Returns the exponent.

'''

result=0

exp=1

while base**exp<num:

if base**exp <= num < base**(exp+1):

result = exp

elif num - base**exp <= base**(exp+1) - num:

result=exp+1

exp+=1

return result

In my code, when I try running

`closest_power(4,62)`

`2`

`3`

`closest_power(4, 12)`

`1`

`2`

`closest_power(5, 22)`

`1`

`2`

For rest of the test cases it works fine for example:

`closest_power(2, 384.0)`

returns

`8`

Why am I missing out those cases?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Your first condition is always true until while condition violated. For example if `exp=1`

=> `4**1 <= 64 < 4**(1+1)`

yields to true. If `exp=2`

=> `4**2 <= 64 < 4**(2+1)`

also yields to true.

And when condition violated result is always equals to smaller exponent (result=exp). So calling `closest_power(4,62)`

is same as calling `closest_power(4,18)`

and returns `2`

.

As @wim said your method is too complicated. Something like below would be more clear:

```
def closest_power(base, num):
'''
base: base of the exponential, integer > 1
num: number you want to be closest to, integer > 0
Find the integer exponent such that base**exponent is closest to num.
Note that the base**exponent may be either greater or smaller than num.
In case of a tie, return the smaller value.
Returns the exponent.
'''
exp=1
while base ** exp < num:
exp+=1
return exp if base ** exp - num < num - base ** (exp - 1) else exp - 1
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**