เมื่อต้องการตรวจสอบว่าสตริงหนึ่งสามารถสร้างจากตัวอักษรของอีกสตริงหนึ่งได้หรือไม่ ใช้ Counter นับตัวอักษร แล้วใช้ตัวดำเนินการ & (intersection)
ตัวอย่างโค้ด
from collections import Counter
def can_form(str1, str2):
c1 = Counter(str1)
c2 = Counter(str2)
intersection = c1 & c2
return intersection == c1
s1 = 'Hi Mark'
s2 = 'how are yoU'
print("First string:", s1)
print("Second string:", s2)
if can_form(s1, s2):
print("It is possible")
else:
print("It is not possible")ผลลัพธ์
First string: Hi Mark Second string: how are yoU It is not possible
คำอธิบาย
Counterสร้างดิกชันนารีนับจำนวนตัวอักษรแต่ละตัวc1 & c2คืนค่า intersection (ค่าต่ำสุดของแต่ละคีย์ที่มีในทั้งสอง)ถ้า
intersection == c1หมายถึงทุกตัวอักษรใน str1 มีใน str2 พอๆ กันหรือมากกว่าตัวอย่าง: 'Hi Mark' ต้องการ H,i,M,a,r,k แต่ 'how are yoU' ไม่มี M,k → False