List Comprehension เป็นเทคนิคยอดนิยมใน Python ที่นี่เราใช้เทคนิคนี้ เราสร้างอาร์เรย์อินพุตของผู้ใช้และองค์ประกอบอาร์เรย์ควรเป็น 0 และ 1 ในลำดับแบบสุ่ม จากนั้นแยก 0 ทางด้านซ้ายและ 1 ทางด้านขวา เราสำรวจอาร์เรย์และแยกรายการที่แตกต่างกันสองรายการ รายการหนึ่งประกอบด้วย 0 และรายการอีกรายการประกอบด้วย 1 รายการ จากนั้นจึงเชื่อมรายการสองรายการเข้าด้วยกัน
ตัวอย่าง
Input:: a=[0,1,1,0,0,1] Output::[0,0,0,1,1,1]
อัลกอริทึม
seg0s1s(A) /* A is the user input Array and the element of A should be the combination of 0’s and 1’s */ Step 1: First traverse the array. Step 2: Then check every element of the Array. If the element is 0, then its position is left side and if 1 then it is on the right side of the array. Step 3: Then concatenate two list.
โค้ดตัวอย่าง
# Segregate 0's and 1's in an array list
def seg0s1s(A):
n = ([i for i in A if i==0] + [i for i in A if i==1])
print(n)
# Driver program
if __name__ == "__main__":
A=list()
n=int(input("Enter the size of the array ::"))
print("Enter the number ::")
for i in range(int(n)):
k=int(input(""))
A.append(int(k))
print("The New ArrayList ::")
seg0s1s(A)
ผลลัพธ์
Enter the size of the array ::6 Enter the number :: 1 0 0 1 1 0 The New ArrayList :: [0, 0, 0, 1, 1, 1]