-
Notifications
You must be signed in to change notification settings - Fork 0
Random Pick With Weight #158
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tom4649
wants to merge
2
commits into
main
Choose a base branch
from
528.Random-Pick-with-Weight
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| # 528. Random Pick with Weight | ||
|
|
||
| ## step1 | ||
| 9mぐらいでまず naive を書く。計算量 O(N)。 | ||
|
|
||
| bisectを使って高速化。計算量 O(log N) | ||
|
|
||
| ## step2 | ||
| いい加減な名前で書いてしまったので改善 | ||
|
|
||
| 乱数の書き方を調べる: | ||
|
|
||
| - random.randint: uniformと同じ書き方で書ける。もともと整数なのでこちらの方が良さそう | ||
| - random.choices: `return random.choices(list(range(len(self.prefix_sums))), cum_weights=self.prefix_sums)[0]` | ||
| - 内部で二分探索が走っている | ||
| - https://github.com/python/cpython/blob/219768ff531fc0686de623139562ee9f9537df98/Lib/random.py#L460 | ||
| - np.random.choice: O(N)だがバッチジョブだと高速化 | ||
|
|
||
| --- | ||
|
|
||
| Alias method | ||
|
|
||
| https://leetcode.com/problems/random-pick-with-weight/solutions/671439/python-smart-o1-solution-with-detailed-e-r0gx/?envType=problem-list-v2&envId=7p55wqm | ||
|
|
||
| https://en.wikipedia.org/wiki/Alias_method | ||
|
|
||
| O(N)の前計算を行なっておくことでO(1)で生成できる | ||
|
|
||
| 乱数を考えると非効率な状況もある(e.g. p= 1/2, 1) | ||
|
|
||
| ## step3 | ||
| 詰まった点: | ||
| - scaled_weights で n 倍するのを忘れる | ||
| - 最後の while 処理を忘れる |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| import random | ||
| import itertools | ||
| import bisect | ||
|
|
||
| class Solution: | ||
|
|
||
| def __init__(self, w: list[int]): | ||
| self.cumsum = list(itertools.accumulate(w)) | ||
|
|
||
|
|
||
| def pickIndex(self) -> int: | ||
| sampled = random.uniform(0, self.cumsum[-1]) | ||
| return bisect.bisect_left(self.cumsum, sampled) | ||
|
|
||
|
|
||
|
|
||
| # Your Solution object will be instantiated and called as such: | ||
| # obj = Solution(w) | ||
| # param_1 = obj.pickIndex() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import random | ||
| import itertools | ||
|
|
||
| class Solution: | ||
|
|
||
| def __init__(self, w: list[int]): | ||
| self.cumsum = list(itertools.accumulate(w)) | ||
|
|
||
|
|
||
| def pickIndex(self) -> int: | ||
| sampled = random.uniform(0, self.cumsum[-1]) | ||
| for i in range(len(self.cumsum)): | ||
| if sampled <= self.cumsum[i]: | ||
| return i | ||
|
|
||
|
|
||
|
|
||
| # Your Solution object will be instantiated and called as such: | ||
| # obj = Solution(w) | ||
| # param_1 = obj.pickIndex() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import random | ||
|
|
||
| class Solution: | ||
|
|
||
| def __init__(self, weights: list[int]): | ||
| n = len(weights) | ||
| total = sum(weights) | ||
| scaled_prob = [w * n / total for w in weights] | ||
|
|
||
| self.prob = [0.0] * n | ||
| self.alias = [0] * n | ||
| self.n = n | ||
|
|
||
| small, large = [], [] | ||
| for i, p in enumerate(scaled_prob): | ||
| if p < 1.0: | ||
| small.append(i) | ||
| else: | ||
| large.append(i) | ||
|
|
||
| while small and large: | ||
| s = small.pop() | ||
| l = large.pop() | ||
| self.prob[s] = scaled_prob[s] | ||
| self.alias[s] = l | ||
| scaled_prob[l] -= 1.0 - scaled_prob[s] | ||
| if scaled_prob[l] < 1.0: | ||
| small.append(l) | ||
| else: | ||
| large.append(l) | ||
|
|
||
| while large: | ||
| self.prob[large.pop()] = 1.0 | ||
| while small: | ||
| self.prob[small.pop()] = 1.0 | ||
|
|
||
| def pickIndex(self) -> int: | ||
| i = random.randint(0, self.n - 1) | ||
| return i if random.random() < self.prob[i] else self.alias[i] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| import random | ||
| import itertools | ||
| import bisect | ||
|
|
||
| class Solution: | ||
|
|
||
| def __init__(self, weights: list[int]): | ||
| self.prefix_sums = list(itertools.accumulate(weights)) | ||
|
|
||
| def pickIndex(self) -> int: | ||
| target_weight = random.randint(0, self.prefix_sums[-1]) | ||
| return bisect.bisect_left(self.prefix_sums, target_weight) | ||
|
|
||
|
|
||
| # Your Solution object will be instantiated and called as such: | ||
| # obj = Solution(w) | ||
| # param_1 = obj.pickIndex() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import random | ||
|
|
||
| class Solution: | ||
|
|
||
| def __init__(self, weights: list[int]): | ||
| self.n = len(weights) | ||
| total = sum(weights) | ||
| scaled_weights = [w / total * self.n for w in weights] | ||
|
|
||
| self.prob = [0.0] * self.n | ||
| self.alias = [0] * self.n | ||
|
|
||
| small = [] | ||
| large = [] | ||
| for i, p in enumerate(scaled_weights): | ||
| if p < 1.0: | ||
| small.append(i) | ||
| else: | ||
| large.append(i) | ||
|
|
||
| while small and large: | ||
| i_small = small.pop() | ||
| i_large =large.pop() | ||
| self.alias[i_small] = i_large | ||
| self.prob[i_small] = scaled_weights[i_small] | ||
| scaled_weights[i_large] -= 1.0 - scaled_weights[i_small] | ||
| if scaled_weights[i_large] < 1.0: | ||
| small.append(i_large) | ||
| else: | ||
| large.append(i_large) | ||
|
|
||
| while large: | ||
| i = large.pop() | ||
| self.prob[i] = 1.0 | ||
| while small: | ||
| i = small.pop() | ||
| self.prob[i] = 1.0 | ||
|
|
||
|
|
||
| def pickIndex(self) -> int: | ||
| i = random.randint(0, self.n - 1) | ||
| return i if random.random() < self.prob[i] else self.alias[i] |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
cumsum は numpy の関数名だと思うのですが、ソフトウェアエンジニアの常識に含まれているかどうか微妙に感じます。 cumulative_sum とフルスペルで書いたほうが無難だと思います。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
そうですね、numpy に影響されたと思います。変数名は基本省略しないで書くことを意識します。
(step2 では prefix_sums としました)