[hackerrank][python] Organizing Containers of Balls
Feb 24, 2021
連結: https://www.hackerrank.com/challenges/organizing-containers-of-balls/problem
遇到這種題目落落長的,打比賽真的氣死
其實條件就是球數不能大於籃子的容量,所以只要把球數跟籃數算出來就好。
以下是我一開始沒寫好的解法(多統計了球的種類,但沒必要):
def organizingContainers(container):
t = {}
c = [] for l in container:
tmp = 0
for i in range(len(l)):
if i not in t:
t[i] = 0
t[i] += l[i]
tmp += l[i]
c.append(tmp) while len(t):
cur_max = 0
for k, v in t.items():
if v > cur_max:
cur_max = v
cur_key = k if cur_max > max(c):
return 'Impossible' del t[cur_key]
c.remove(max(c)) return 'Possible'
然後又去看了神解:
def organizingContainers(container):
r = sorted([sum(x) for x in container])
c = sorted([sum(x) for x in zip(*container)])
return "Possible" if r == c else "Impossible"
sorted([sum(x) for x in container]) : 統計 & 排序籃子的空間大小
sorted([sum(x) for x in zip(*container)]) :
- *container 會先將原本的 list 展開
- zip() 會一起 iterate 展開的 list
- sum() 統計每次 iter,也就是每種球的數量
- 最後比較是否球數跟籃空間不一致
用 Python 生成式去解題真的是另一個世界,目前解題還是都用最基本的寫法把問題做拆解,看來從C寫上來的,真的差好多阿