Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมจัดเรียงวลีตามความถี่ที่ปรากฏในประโยคใน Python

ได้รับลิสต์ phrases และ sentences ต้องนับความถี่ที่แต่ละวลีใน phrases ปรากฏใน sentences แล้วจัดเรียง phrases จากมากไปน้อย

ตัวอย่าง: phrases=['strong','durable','efficient'], sentences=[...] ผลลัพธ์ ['efficient','durable','strong']

วิธีแก้ปัญหา

  1. cnt := dict เริ่มต้นทุกค่าเป็น 0
  2. วน response ใน sentences:
    • s := set(response.split())
    • วน i ใน s: ถ้า i in cnt ให้ cnt[i] += 1
  3. สร้างลิสต์ res = [[k, cnt[k]] for k in cnt]
  4. เรียง res ตาม -x[1] แล้ว phrases.index(x[0])
  5. คืน [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']