Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình lọc thư quan trọng từ các hộp thư trong Python


Cho danh sách hộp thư, mỗi hộp chứa danh sách chuỗi: "J" (rác), "P" (cá nhân), "W" (công việc). Duyệt theo vòng tròn (round robin) từ hộp đầu tiên, bỏ qua "J", gộp thành một danh sách.

Ví dụ, mailboxes = [["W","P"],["J","P","J"],["W"]], đầu ra ["W","W","P","P"].

Các bước giải quyết:

  • n_mailboxes := số hộp thư.
  • result := danh sách rỗng.
  • counts := danh sách kích thước n_mailboxes khởi tạo 0.
  • more := True.
  • Trong khi more:
    • more = False.
    • Duyệt i từ 0 đến n_mailboxes-1:
      • index = counts[i], mailbox = mailboxes[i].
      • Nếu index < len(mailbox):
        • more = True.
        • counts[i] += 1.
        • mail = mailbox[index].
        • Nếu mail != "J", thêm vào result.
  • Trả về result.

Ví dụ minh họa

class Solution:
    def solve(self, mailboxes):
        n_mailboxes = len(mailboxes)
        result = []
        counts = [0] * n_mailboxes
        more = True
        while more:
            more = False
            for i in range(n_mailboxes):
                index, mailbox = counts[i], mailboxes[i]
                if index < len(mailbox):
                    more = True
                    counts[i] += 1
                    mail = mailbox[index]
                    if mail != "J":
                        result.append(mail)
        return result

ob = Solution()
mailboxes = [["W", "P"], ["J", "P", "J"], ["W"]]
print(ob.solve(mailboxes))

Đầu vào

[["W", "P"], ["J", "P", "J"], ["W"]]

Đầu ra

['W', 'W', 'P', 'P']