ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่นับและพิมพ์คำที่มีความถี่ของตัวอักษรมากกว่าโปรแกรมที่สอง
ใช้สตริงและตัวอักษรสองตัว คำนำหน้าที่มีความถี่สูงกว่าของตัวอักษรตัวแรกจะถูกพิมพ์ออกมา และแสดงการนับที่ส่วนท้ายของเอาต์พุต
มาดูตัวอย่างกัน
อินพุต
string:- apple alphabets:- p, e
ผลลัพธ์
ap app appl apple 4
อินพุต
string:- apple alphabets:- e, p
ผลลัพธ์
0
มาดูขั้นตอนในการเขียนโค้ดกันครับ
-
กำหนดฟังก์ชันและเขียนโค้ดลงไป
-
เริ่มต้นนับถึง 0 และสตริงว่าง
-
วนซ้ำบนสตริง
-
รับคำนำหน้าโดยใช้การแบ่งสตริงและดัชนี และเก็บไว้ในสตริงว่าง
-
เปรียบเทียบความถี่ตัวอักษรในคำนำหน้า
-
พิมพ์และเพิ่มจำนวนหากพอใจ
-
พิมพ์การนับในตอนท้าย
ตัวอย่าง
# defining a function for multiple calles
def prefixes(string, _1, _2):
# count count = 0
# empty string for comparison
prefix = ""
# iterating over the string
for i in range(len(string)):
# getting the prefix from the string
prefix = string[:i + 1]
# comparing the count of alphabets in the prefix
if prefix.count(_1) > prefix.count(_2):
# printing the prefix if success
print(prefix)
# incrementing the count by 1
count += 1
# printing the count
print(f"Total prefixes matched: {count}")
if __name__ == '__main__':
# invokging the function
print(f"----------------apple p e---------------------")
prefixes('apple', 'p', 'e')
print()
print(f"----------------apple e p---------------------")
prefixes('apple', 'e', 'p') ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
----------------apple p e--------------------- ap app appl apple Total prefixes matched: 4 ----------------apple e p--------------------- Total prefixes matched: 0
บทสรุป
หากคุณกำลังประสบปัญหาใดๆ ในการทำความเข้าใจโค้ด ให้พูดถึงในส่วนความคิดเห็น