How to Calculate Powers of 2 in Python

The challenge

Complete the function that takes a non-negative integer `n` as input, and returns a list of all the powers of 2 with the exponent ranging from 0 to `n` (inclusive).

Examples

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```n = 0  ==> [1]        # [2^0]
n = 1  ==> [1, 2]     # [2^0, 2^1]
n = 2  ==> [1, 2, 4]  # [2^0, 2^1, 2^2]```Code language: Python (python)```

The solution in Python code

Option 1:

``````def powers_of_two(n):
out = []
for i in range(n+1):
out.append(2**i)
return out
```Code language: Python (python)```

Option 2:

``````def powers_of_two(n):
return [2**i for i in range(n+1)]
```Code language: Python (python)```

Option 3:

``````def powers_of_two(n):
return [1<<x for x in range(n + 1)]
```Code language: Python (python)```

Test cases to validate our solution

``````import test
from solution import powers_of_two

@test.describe("Fixed Tests")
def fixed_tests():
@test.it('Basic Test Cases')
def basic_test_cases():
test.assert_equals(powers_of_two(0), [1])
test.assert_equals(powers_of_two(1), [1, 2])
test.assert_equals(powers_of_two(4), [1, 2, 4, 8, 16])
```Code language: Python (python)```
Tags:
Subscribe
Notify of