My function closest_power(base, num) failing some test cases
<pre><code>def closest_power(base, num):
    '''
    base: base of the exponential, integer &gt; 1
    num: number you want to be closest to, integer &gt; 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&lt;num:
        if base**exp &lt;= num &lt; base**(exp+1):
           result = exp

        elif num - base**exp &lt;= base**(exp+1) - num:
           result=exp+1

        exp+=1
    return result
</code></pre>

<p>In my code, when I try running <code>closest_power(4,62)</code> it returns <code>2</code> instead of <code>3</code> and, in similar test cases like <code>closest_power(4, 12)</code> returns <code>1</code> instead of <code>2</code>. (<code>closest_power(5, 22)</code> returns <code>1</code> instead of <code>2</code>) </p>

<p>For rest of the test cases it works fine for example: </p>

<pre><code>closest_power(2, 384.0) 
</code></pre>

<p>returns <code>8</code>.</p>

<p>Why am I missing out those cases?</p>

<p>I suppose <code>elif</code> is extra. If condition is satisfied, you should return the value.</p>

<pre><code>def closest_power2(base, num):
    exp=1
    while base**exp&lt;=num:
        if base**exp &lt;= num &lt;= base**(exp+1):
           num_low = base**exp
           num_high = base**(exp+1)
           return exp if num-num_low&lt;num_high-num else exp+1
        exp += 1
    return 0
</code></pre>

<p>Emm... In your case, for <code>exp=8</code>, the first <code>if</code> condition is satisfied. Then you assign <code>result=exp</code> (which is 8) and at the next iteration <code>while</code> breaks, because <code>2^9</code> is not less than <code>384</code>, so you return <code>8</code>.</p>

<p>Please notice, I've changed <code>base**exp&lt;num</code> to <code>base**exp&lt;=num</code>.</p>

python python-3.x