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>Your first condition is always true until while condition violated. For example if <code>exp=1</code> => <code>4**1 &lt;= 64 &lt; 4**(1+1)</code> yields to true. If <code>exp=2</code> => <code>4**2 &lt;= 64 &lt; 4**(2+1)</code> also yields to true.</p>

<p>And when condition violated result is always equals to smaller exponent (result=exp). So calling <code>closest_power(4,62)</code> is same as calling <code>closest_power(4,18)</code> and returns <code>2</code>. </p>

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

<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.

    '''
    exp=1
    while base ** exp &lt; num:
        exp+=1
    return exp if base ** exp - num &lt; num - base ** (exp - 1) else exp - 1 
</code></pre>

python python-3.x