分散システムとポエム

パーティーに行くタイミング|問題解決のPythonプログラミング 2章

書籍「問題解決のPythonプログラミング」を積んだままだったので読みながらコードを書いてみた.今回はその2章にある問題をといてみた.

(問題)有名人が参加する時間帯が事前に分かっているパーティーがある.このパーティーに1時間だけ参加するとき,最も多くの有名人がいる時間帯がいつか求める.

入力は有名人のいる時間帯をあらわすタプルで構成されている.例えば(6,8)の場合は6:00から8:00まで参加するということをあらわす.今回の場合は9:00 – 10:00が5人で最多となる.

タイムライン

簡単なコードを書いてみた.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
guest_schdules = [(6,8), (6,12), (6,7), (7,8),
(7,10), (8,9), (8,10), (9,12),
(9,10), (10,11), (10,12), (11,12)]
times = []
for schd in guest_schdules:
times.append(('start', schd[0]))
times.append(('end', schd[1]))
times_sorted = sorted(times, key=lambda x: x[1])
current_guest = 0
max_time = max_value = 0
for time in times_sorted:
if time[0] == 'start':
current_guest += 1
elif time[0] == 'end':
current_guest -= 1
if max_time < time[1]:
max_time = time[1]
max_value = current_guest
print("Answer:", "time=", max_time, "num_of_guest=", max_value)
guest_schdules = [(6,8), (6,12), (6,7), (7,8), (7,10), (8,9), (8,10), (9,12), (9,10), (10,11), (10,12), (11,12)] times = [] for schd in guest_schdules: times.append(('start', schd[0])) times.append(('end', schd[1])) times_sorted = sorted(times, key=lambda x: x[1]) current_guest = 0 max_time = max_value = 0 for time in times_sorted: if time[0] == 'start': current_guest += 1 elif time[0] == 'end': current_guest -= 1 if max_time < time[1]: max_time = time[1] max_value = current_guest print("Answer:", "time=", max_time, "num_of_guest=", max_value)
guest_schdules = [(6,8), (6,12), (6,7), (7,8),
        (7,10), (8,9), (8,10), (9,12),
        (9,10), (10,11), (10,12), (11,12)]
times = []

for schd in guest_schdules:
    times.append(('start', schd[0]))
    times.append(('end', schd[1]))

times_sorted = sorted(times, key=lambda x: x[1])

current_guest = 0
max_time = max_value = 0
for time in times_sorted:
    if time[0] == 'start':
        current_guest += 1
    elif time[0] == 'end':
        current_guest -= 1

    if max_time < time[1]:
        max_time = time[1]
        max_value = current_guest

print("Answer:", "time=", max_time, "num_of_guest=", max_value)

実行結果:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
$ python3 2-party.py
Answer: time= 9 num_of_guest= 5
$ python3 2-party.py Answer: time= 9 num_of_guest= 5
$ python3 2-party.py
Answer: time= 9 num_of_guest= 5

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です