Skip to content

Conversation

@Satorien
Copy link
Owner

index = binary_search_from_left(nums, target, key=score_num)
if nums[index] == target:
return index
return -1
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

面白い書き方だと思いました。
num > nums[-1]num >= nums[0]としても動きますかね?
個人的にはscore_numは次のように書いてしまえば初見でもわかりやすくなるかもしれないと思いました。(今の書き方もエレガントで面白いですが)

if target > nums[-1]:
    if num >= target or num <= nums[-1]:
        return 1
if target <= nums[-1]:
    if num >= target and num <= nums[-1]:
        return 1
return 0

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

もしこうするならscore_numはis_past_targetみたいな名前のbooleanを返す関数にしてしまって、
if key(nums[middle]) < key(target)みたいなところはif not is_past_target(num)みたいな形にしてもいいかもしれません。

class Solution:
def search(self, nums: List[int], target: int) -> int:
def score_num(num: int) -> int:
return -(num > nums[-1]) + (num >= target)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ブール値を足すことに私は抵抗があります

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ドキュメントにも書かれてました。初めて知りました。
https://docs.python.org/3/library/stdtypes.html#typebool

In many numeric contexts, False and True behave like the integers 0 and 1, respectively. However, relying on this is discouraged; explicitly convert using int() instead.

left = middle
continue
return -1
return left

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

私の理解不足かもしれませんが、left = 0, middle = 0 となった時に is_between の right-1 は -1 になり、結果的に正しく動いているように見えて不思議に思いました。

class Solution:
def search(self, nums: List[int], target: int) -> int:
def score_position(num: int) -> int:
return (num <= nums[-1]) + (num >= target)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(num <= nums[-1], num) で本当はいいみたいですね。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants