Skip to content

【Arai60】58問目 31. Next Permutation#58

Merged
shining-ai merged 2 commits intomainfrom
review58
Jun 29, 2024
Merged

【Arai60】58問目 31. Next Permutation#58
shining-ai merged 2 commits intomainfrom
review58

Conversation

@shining-ai
Copy link
Copy Markdown
Owner

if nums[target_index] < nums[i] < min_num:
min_num = nums[i]
index = i
return index
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

forループ内のif文に入らない場合、何が返りますか?読んでいて不安になりました。やっぱりfor文の中でしか定義していない変数をfor文の外で使うのは気になります。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

left = find_index_not_asc_from_end(nums)

の処理をすれば、find_index_next_largerがif文に入らないケースはなくなるので、雑に書いてしまいました。
関数単体で見ても問題がないようにすることが望ましいのですね。
今回の場合は、indexの初期値を作っておいて例外の処理を書くのかなと思いました。

def find_index_next_larger(nums, target_index):
            min_num = math.inf
            index = -1
            for i in range(target_index + 1, len(nums)):
                if nums[target_index] < nums[i] < min_num:
                    min_num = nums[i]
                    index = i
            return index

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

まあコメントがあるだけでも良いかもです。それだけでforの中のif文がちゃんと呼ばれるよね、と確認する手間が減ります。

return
right = find_index_next_larger(nums, left)
nums[left], nums[right] = nums[right], nums[left]
nums[left + 1 :] = sorted(nums[left + 1 :])
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

L17のmin_numとの比較を<=に変えてあげれば、leftの右側は降順になるので単純にreverseするだけでよくなります。

今回は値が同じ場合を考慮してあげる必要があるのが少し違いますが、前回のコメントと同様ですね。
#50 (comment)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

reverseでやりたいけど同値でできないと思っていたのですが、ありがとうございます。

right = i
nums[left], nums[right] = nums[right], nums[left]
nums[left + 1 :] = sorted(nums[left + 1 :])
break
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

これ return ではなく break にした事情あります?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

breakにした特別な意図はないです。
値を返す問題ではなかったので、ここでreturnしようという発想がありませんでした。

@shining-ai shining-ai merged commit 7e8b5df into main Jun 29, 2024
@shining-ai shining-ai deleted the review58 branch June 29, 2024 14:06
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.

3 participants