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.
CodePudding user response:
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]
CodePudding user response:
You should make an empty list before the for-loop, then inside the for-loop, instead of printing each number, append it to the list. Then at the end, print the list.
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)))
output_list = []
for number in numbers:
exponentiation = power(number,increment)
output_list.append(exponentiation)
print(output_list)
CodePudding user response:
You can use single line for loops -
exponentiation = [power(number,increment) for number in numbers]
print(exponentiation)
#[1,32,243]
CodePudding user response:
you can use the pow function of the python library and append value in the list and print list instead of individual value
numbers = [1,2,3]
increment = 5
l=[]
for i in numbers:
ex=pow(i,increment )
l.append(ex)
print(l)
output
[1, 32, 243]