Skip to content

Commit fe151db

Browse files
authored
Update sort-integers-by-the-power-value.py
1 parent 63cdece commit fe151db

File tree

1 file changed

+16
-26
lines changed

1 file changed

+16
-26
lines changed

Python/sort-integers-by-the-power-value.py

+16-26
Original file line numberDiff line numberDiff line change
@@ -38,19 +38,14 @@ def partition_around_pivot(left, right, pivot_idx, nums, compare):
3838
left = new_pivot_idx + 1
3939

4040
def power_value(x):
41-
y = x
42-
if x not in Solution.dp:
43-
result = 0
44-
while x > 1:
45-
result += 1
46-
if x%2:
47-
x = 3*x + 1
48-
else:
49-
x //= 2
50-
if x in Solution.dp:
51-
result += Solution.dp[x]
52-
break
53-
Solution.dp[y] = result
41+
y, result = x, 0
42+
while x > 1 and x not in Solution.dp:
43+
result += 1
44+
if x%2:
45+
x = 3*x + 1
46+
else:
47+
x //= 2
48+
Solution.dp[y] = result + (Solution.dp[x] if x > 1 else 0)
5449
return Solution.dp[y], y
5550

5651
arr = map(power_value, range(lo, hi+1))
@@ -71,19 +66,14 @@ def getKth(self, lo, hi, k):
7166
:rtype: int
7267
"""
7368
def power_value(x):
74-
y = x
75-
if x not in Solution2.dp:
76-
result = 0
77-
while x > 1:
78-
result += 1
79-
if x%2:
80-
x = 3*x + 1
81-
else:
82-
x //= 2
83-
if x in Solution2.dp:
84-
result += Solution2.dp[x]
85-
break
86-
Solution2.dp[y] = result
69+
y, result = x, 0
70+
while x > 1 and x not in Solution2.dp:
71+
result += 1
72+
if x%2:
73+
x = 3*x + 1
74+
else:
75+
x //= 2
76+
Solution2.dp[y] = result + (Solution2.dp[x] if x > 1 else 0)
8777
return Solution2.dp[y], y
8878

8979
return sorted(range(lo, hi+1), key=power_value)[k-1]

0 commit comments

Comments
 (0)