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

โปรแกรมหมุนสตริงขนาด n ไปซ้าย n ครั้งใน Python

การหมุนสตริงซ้าย n ครั้ง (n = ความยาวสตริง)

สร้างรายการของสตริงที่หมุนซ้าย 1, 2, ..., n ตำแหน่ง

อัลกอริทึม

  1. res = [], n = len(s)
  2. วน i = 0 ถึง n-1:
    • s = s[1:] + s[0] (หมุนซ้าย 1 ตำแหน่ง)
    • เพิ่ม s ลง res
  3. คืนค่า res

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

def solve(s):
    res = []
    n = len(s)
    for i in range(0, n):
        s = s[1:n] + s[0]
        res.append(s)
    return res

s = "hello"
print(solve(s))

ผลลัพธ์

['elloh', 'llohe', 'lohel', 'ohell', 'hello']

คำอธิบาย

"hello" → "elloh" → "llohe" → "lohel" → "ohell" → "hello" (กลับมาที่เดิมหลังหมุน 5 ครั้ง)