Search code examples
pythonfor-loopif-statementincrementexponentiation

python, exponentiaiton with 'def' and 'for-loop'


input:

numbers = [1,2,3]
increment = 5

Expected output:

[1, 32, 243]

Result with my code:

1
32
243

Code:

def power(x, y):

    if (y == 0): return 1
    elif (int(y % 2) == 0):
        return (power(x, int(y / 2)) *
            power(x, int(y / 2)))
    else:
        return (x * power(x, int(y / 2)) *
                power(x, int(y / 2)))

for number in numbers:
    exponentiation = power(number,increment)
    print(exponentiation)

I'm trying to find the square root of the numbers in a list without pow() and '**' functions. I've found the square root of each number, but I'm wondering how to put them in a list.


Solution

  • You are printing the exponentiations, but instead you want to output the list. This is what you want to do:

    # your function code above
    
    answer = []
    for number in numbers:
        exponentiation = power(number,increment)
        answer.append(exponentiation)
    
    print(answer)
    

    This will give:

    [1, 32, 243]