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

โปรแกรม Python ตรวจสอบว่าสองลิสต์เป็น circularly identical หรือไม่


ตรวจสอบว่าลิสต์สองตัวมีลำดับเดียวกันเมื่อมองแบบวนลูป (circular) โดยคูณลิสต์แรกเป็น 2 เท่าแล้วเช็ค substring

ตัวอย่าง

A = [100,100,10,10,100]
B = [100,100,100,10,10]
Output: True

อัลกอริทึม

  1. สร้างลิสต์ A, B
  2. แปลงเป็นสตริงด้วย ' '.join(map(str, list))
  3. เช็คว่า B อยู่ใน A*2 หรือไม่

โค้ดตัวอย่าง

A = []; B = []; C = []
# ... input code omitted for brevity ...
print("Compare A and B:", ' '.join(map(str, B)) in ' '.join(map(str, A*2)))
print("Compare A and C:", ' '.join(map(str, C)) in ' '.join(map(str, A*2)))

ผลลัพธ์

Compare First List and Second List: True
Compare Second List and Third List: False