ภาพรวม
โจทย์สร้าง acronym (ตัวย่อ) จากประโยค โดยเอาตัวอักษรแรกของแต่ละคำ (ยกเว้นคำ "and") และแปลงเป็นตัวใหญ่ทั้งหมด
ตัวอย่าง
อินพุต: "Indian Space Research Organisation"
คำ: Indian, Space, Research, Organisation
ตัวอักษรแรก: I, S, R, O → ISRO
โค้ด Python
class Solution:
def solve(self, s):
tokens = s.split()
string = ""
for word in tokens:
if word != "and":
string += str(word[0])
return string.upper()
ob = Solution()
print(ob.solve("Indian Space Research Organisation"))
วิธี Pythonic
def acronym(s):
return "".join(w[0] for w in s.split() if w.lower() != "and").upper()
ขยาย: รองรับหลายคำยกเว้น
def acronym_ex(s, exclude={"and", "or", "the", "of", "in"}):
return "".join(w[0] for w in s.split() if w.lower() not in exclude).upper()
ผลลัพธ์
ISRO