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

สุ่มแทรกสมาชิกเข้าในลิสต์ K ครั้ง (Random Insertion K Times)

แนวคิด

สุ่มเลือกตำแหน่งในลิสต์ และสุ่มเลือกค่าจากลิสต์เพิ่มเติม แทรกเข้าไป ทำซ้ำ K ครั้ง ใช้ random.randint และ random.choice

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

import random

my_list = [34, 12, 21, 56, 8, 9, 0, 3, 41, 11, 90]
print("ลิสต์:", my_list)

my_list.sort()
print("หลังเรียง:", my_list)

to_add = ["Python", "Object", "oriented", "language", "cool"]
K = 3
print("K =", K)

for _ in range(K):
    idx = random.randint(0, len(my_list))  # 0 ถึง len (รวมท้าย)
    chosen = random.choice(to_add)
    my_list = my_list[:idx] + [chosen] + my_list[idx:]

print("ผลลัพธ์:", my_list)

ผลลัพธ์ตัวอย่าง (สุ่ม)

ลิสต์: [34, 12, 21, 56, 8, 9, 0, 3, 41, 11, 90]
หลังเรียง: [0, 3, 8, 9, 11, 12, 21, 34, 41, 56, 90]
K = 3
ผลลัพธ์: [0, 3, 8, 9, 11, 12, 'Python', 21, 34, 41, 56, 90, 'Object', 'oriented']

คำอธิบาย

  • random.randint(0, len(my_list)) สุ่ม index 0 ถึง n (นำเข้าได้ที่ท้าย)
  • random.choice(to_add) สุ่มค่าจากลิสต์เพิ่ม
  • list[:idx] + [val] + list[idx:] แทรกค่า (สร้างลิสต์ใหม่)

หมายเหตุ

  • ลิสต์เดิมจะเปลี่ยนขนาด ทุกครั้งที่แทรก
  • index สุ่มใหม่ทุกครั้งอิงจากลิสต์ปัจจุบัน
  • ผลลัพธ์จะสุ่มต่างกันทุกครั้งรัน