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

ตรวจสอบว่าสตริงที่กำหนดสามารถสร้างได้จากการต่อสตริงในลิสต์ใน Python

เราบางครั้งต้องตรวจสอบว่าสตริงที่ต้องการสามารถสร้างได้จากสตริงจำนวนมากที่อยู่ในลิสต์ ลำดับของสตริงในลิสต์ที่ต้องต่อกันเพื่อให้ได้สตริงที่ต้องการก็ไม่สำคัญ

ด้วย permutations

จาก itertools เราสามารถใช้ฟังก์ชัน permutations ซึ่งจะให้การจัดเรียงที่เป็นไปได้ของสตริงในลิสต์ในลำดับต่างๆ ทันทีที่การจัดเรียงใดตรงกับสตริงที่ต้องการ เราสรุปได้ว่าสตริงสามารถสร้างได้

ตัวอย่าง

from itertools import permutations
chk_str = 'balloon'
Alist = ['fly','on', 'o', 'hot', 'ball', 'air']
def findstring(strchk, biglist):
    for i in range(2, len(biglist) + 1):
        for perm in permutations(biglist, i):
            if ''.join(perm) == strchk:
                return True
    return False
# Using the function
if findstring(chk_str, Alist):
    print("String can be formed.")
else:
    print("String can not be formed.")

Output

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ -

String can be formed.

ด้วย Regular Expressions

โมดูล re มีฟังก์ชัน compile ซึ่งจะสร้างสตริงที่เป็นไปได้โดยระบุรูปแบบ regular expression จากนั้นจะเปรียบเทียบกับสตริงที่ต้องตรวจสอบ หากผลลัพธ์ไม่ใช่ none เราสรุปได้ว่าสตริงสามารถสร้างได้

ตัวอย่าง

import re
chk_str = 'balloon'
Alist = ['fly','on', 'o', 'hot', 'ball', 'air']
def findstring(strchk, biglist):
    r = re.compile("(?: " + "|".join(biglist) + ")*$")
    if r.match(strchk) != None:
        return True
    return False
# Using the function
if findstring(chk_str, Alist):
    print("String can be formed.")
else:
    print("String can not be formed.")

Output

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ -

String can be formed.