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

Python - สร้างสตริงขนาด N ที่มี Substring ขนาด K มีตัวอักษรที่ต่างกัน K ตัว

สร้างสตริงความยาว N โดยที่ทุก Substring ความยาว K จะมีตัวอักษรที่ต่างกัน (Distinct) อยู่ K ตัว

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

def generate_my_string(string_size, substring_size, distinct_chars):
    my_string = ""
    count_1 = 0
    count_2 = 0
    for i in range(string_size):
        count_1 += 1
        count_2 += 1
        if count_1 <= substring_size:
            if count_2 <= distinct_chars:
                my_string = my_string + chr(96 + count_1)
            else:
                my_string = my_string + 'a'
        else:
            count_1 = 1
            count_2 = 1
            my_string = my_string + 'a'
    return my_string

my_string_size = 8
my_substring_size = 6
K_distinct_chars = 4

print("The string size is :")
print(my_string_size)
print("The substring size is :")
print(my_substring_size)
print("The distinct characters count is :")
print(K_distinct_chars)
print("The resultant string is :")
print(generate_my_string(my_string_size, my_substring_size, K_distinct_chars))

ผลลัพธ์

The string size is : 8
The substring size is : 6
The distinct characters count is : 4
The resultant string is : abcdaaab

คำอธิบาย

  • count_1: นับตำแหน่งใน Substring ปัจจุบัน (1 ถึง K)
  • count_2: นับตัวอักษรที่ต่างกันที่ใช้ไป
  • ใน Substring แรก: ใช้ a,b,c,d (4 ตัว) แล้วเติม 'a' ซ้ำ
  • เริ่ม Substring ใหม่: รีเซ็ต Count, ใส่ 'a'
  • Logic เฉพาะเจาะจงสำหรับการสร้างสตริงทดสอบ