Skip to content

Commit 6a896a7

Browse files
committed
EPI: power_x_y (CPP/Py)
1 parent 001f01c commit 6a896a7

File tree

3 files changed

+47
-8
lines changed

3 files changed

+47
-8
lines changed

elements-of-programming-interviews/cpp/power_x_y.cc

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,21 @@
11
#include "test_framework/generic_test.h"
2+
double _helper(double x, int y, std::map<int, double>& dp) {
3+
if (dp.find(y) != dp.end()) {
4+
return dp[y];
5+
}
6+
double val = _helper(x, y / 2, dp);
7+
val *= val;
8+
if (y % 2) {
9+
val = (y < 0) ? val / x : val * x;
10+
}
11+
dp[y] = val;
12+
return dp[y];
13+
}
14+
215
double Power(double x, int y) {
3-
// TODO - you fill in here.
4-
return 0.0;
16+
std::map<int, double> dp{{0, 1}, {1, x}, {-1, (1.0 / x)}};
17+
_helper(x, y, dp);
18+
return dp[y];
519
}
620

721
int main(int argc, char* argv[]) {

elements-of-programming-interviews/problem_mapping.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,15 +100,15 @@ problem_mapping = {
100100
},
101101
"4.07 Compute pow(x,y)": {
102102
"C++: power_x_y.cc": {
103-
"passed": 0,
103+
"passed": 10002,
104104
"total": 10002
105105
},
106106
"Java: PowerXY.java": {
107107
"passed": 0,
108108
"total": 10002
109109
},
110110
"Python: power_x_y.py": {
111-
"passed": 0,
111+
"passed": 10002,
112112
"total": 10002
113113
}
114114
},
Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,36 @@
11
from test_framework import generic_test
22

33

4+
def brute_force_power(x: float, y: int) -> float:
5+
total = 1.0
6+
if y >= 0:
7+
for i in range(1, y+1):
8+
total *= x
9+
else:
10+
for i in range(1, (-y)+1):
11+
total /= x
12+
return total
13+
14+
15+
def _helper(x: float, y: int, dp: dict) -> float:
16+
if y in dp:
17+
return dp[y]
18+
val = _helper(x, y//2, dp) * _helper(x, y//2, dp)
19+
if y % 2: # odd
20+
val = (val * x)
21+
dp[y] = val
22+
return dp[y]
23+
24+
425
def power(x: float, y: int) -> float:
5-
# TODO - you fill in here.
6-
return 0.0
26+
dp = {
27+
0: 1.0,
28+
1: x,
29+
-1: (1/x)
30+
}
31+
_helper(x, y, dp)
32+
return dp[y]
733

834

935
if __name__ == '__main__':
10-
exit(generic_test.generic_test_main('power_x_y.py', 'power_x_y.tsv',
11-
power))
36+
exit(generic_test.generic_test_main('power_x_y.py', 'power_x_y.tsv', power))

0 commit comments

Comments
 (0)