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

โปรแกรมจัดเรียงไพ่เพื่อเปิดเผยในลำดับเพิ่มขึ้นใน Python

การ์ดจะถูกเปิดเผยโดย: 1) นำไพ่บนสุดออก 2) ไพ่ถัดไปย้ายไปด้านหลัง ทำซ้ำจนหมด จัดเรียงไพ่ให้เปิดเผยได้ตามลำดับ 1,2,3...

ตัวอย่าง: [1,2,3,4,5,6,7,8] → [1,5,2,7,3,6,4,8]

อัลกอริธึมจำลองด้วย Queue

  • เรียงไพ่จากน้อยไปมาก
  • สร้าง index queue: 0,1,2... แล้วจำลองกระบวนการ: pop ซ้าย → เก็บใน order, pop ซ้าย → push ขวา
  • วางไพ่ที่เรียงแล้วตามลำดับ index ใน order

การนำไปใช้

from collections import deque

class Solution:
    def solve(self, cards):
        cards.sort()
        idx = list(range(len(cards)))
        order = []
        q = deque(idx)
        while q:
            order.append(q.popleft())
            if q:
                q.append(q.popleft())
        ans = [0] * len(cards)
        for i, card in zip(order, cards):
            ans[i] = card
        return ans

ob = Solution()
print(ob.solve([1,2,3,4,5,6,7,8]))  # [1, 5, 2, 7, 3, 6, 4, 8]