ヒント 5cmちょうどの棒を見る
左端の3cmはどちらの条件でも外れます。右端の9cmはどちらにも入ります。真ん中の2本はどうでしょう。
答えと二つの挿入位置
1本。9cmだけです。 添字を0から数えると、5を左寄せで挿入する位置は1、右寄せでは3です。要素数4から引くと、5以上は4−1で3本、5を超えるのは4−3で1本になります。
Pythonで確かめる
from bisect import bisect_left, bisect_right
def count_lengths(sorted_lengths, threshold):
"""Return counts at or above the threshold, then strictly above it."""
n = len(sorted_lengths)
return n - bisect_left(sorted_lengths, threshold), n - bisect_right(sorted_lengths, threshold)
if __name__ == "__main__":
lengths = [3, 5, 5, 9] # 昇順に並べる
at_least, above = count_lengths(lengths, 5)
print("5cm以上", at_least, "本")
print("5cmを超える", above, "本")
リストを [5, 5] にすれば結果は2本と0本、空のリストなら両方0本です。このコードは長さを昇順に渡します。
この例をPythonファイルで保存。Python 3で python3 sticks.py と実行できます。