ได้รับลิสต์ phrases และ sentences ต้องนับความถี่ที่แต่ละวลีใน phrases ปรากฏใน sentences แล้วจัดเรียง phrases จากมากไปน้อย
ตัวอย่าง: phrases=['strong','durable','efficient'], sentences=[...] ผลลัพธ์ ['efficient','durable','strong']
วิธีแก้ปัญหา
cnt := dictเริ่มต้นทุกค่าเป็น 0- วน
responseในsentences:s := set(response.split())- วน
iในs: ถ้าi in cntให้cnt[i] += 1
- สร้างลิสต์
res = [[k, cnt[k]] for k in cnt] - เรียง
resตาม-x[1]แล้วphrases.index(x[0]) - คืน
[i[0] for i in res]
ตัวอย่างโค้ด
def solve(phrases, sentences):
cnt = {}
for feature in phrases:
cnt[feature] = 0
for response in sentences:
p = response.split()
s = set(p)
for i in s:
if i in cnt:
cnt[i] += 1
res = [[k, cnt[k]] for k in cnt]
res.sort(key=lambda x: (-x[1], phrases.index(x[0])))
return [i[0] for i in res]
print(solve(['strong','durable','efficient'],
['the product is durable and efficient',
'strong and durable',
'it is efficient',
'like it because it is efficient']))
อินพุต
['strong','durable','efficient'], ['the product is durable and efficient', 'strong and durable', 'it is efficient', 'like it because it is efficient']
เอาต์พุต
['efficient', 'durable', 'strong']