ในบทช่วยสอนนี้ เราจะเรียนรู้วิธีค้นหาค่าที่ซ้ำกันทั้งหมดในสตริง เราสามารถทำได้หลายวิธีใน Python มาสำรวจกันทีละคน
จุดมุ่งหมายของโปรแกรมที่เราจะเขียนคือการค้นหาอักขระที่ซ้ำกันในสตริง ตัวอย่างเช่น เรามีสตริง tutorialspoint โปรแกรมจะให้เรา t o i เป็นเอาต์พุต พูดง่ายๆ ก็คือ เราต้องหาอักขระที่มีจำนวนมากกว่าหนึ่งในสตริง มาดูกันค่ะ
โปรแกรมขูด
การเขียนโปรแกรมโดยไม่ต้องใช้โมดูลใดๆ เราสามารถใช้วิธีต่างๆ ของ Python เพื่อให้บรรลุเป้าหมาย ขั้นแรก เราจะหาอักขระที่ซ้ำกันของสตริงโดยใช้วิธีการนับ มาดูขั้นตอนกันก่อนครับ
- เริ่มต้นสตริง
- เริ่มต้นรายการว่าง
- วนรอบสตริง
- ตรวจสอบว่าความถี่ของถ่านมีค่ามากกว่าหนึ่งหรือไม่โดยใช้วิธีการนับ
If greater than one check whether it's present in the list or not. If not present append to the list
- พิมพ์ตัวอักษร
ตัวอย่าง
## initializing string string = "tutorialspoint" ## initializing a list to append all the duplicate characters duplicates = [] for char in string: ## checking whether the character have a duplicate or not ## str.count(char) returns the frequency of a char in the str if string.count(char) > 1: ## appending to the list if it's already not present if char not in duplicates: duplicates.append(char) print(*duplicates)
หากคุณเรียกใช้โปรแกรมข้างต้น คุณจะได้ผลลัพธ์ดังต่อไปนี้
ผลลัพธ์
t o i
ตอนนี้เราจะพบอักขระที่ซ้ำกันของสตริงโดยไม่มีวิธีการใดๆ เราจะใช้โครงสร้างข้อมูลพจนานุกรมเพื่อให้ได้ผลลัพธ์ที่ต้องการ มาดูขั้นตอนกันก่อนครับ
- เริ่มต้นสตริง
- เริ่มต้นพจนานุกรมเปล่า
- วนรอบสตริง
- ตรวจสอบว่ามีอักขระอยู่ในพจนานุกรมหรือไม่
- เริ่มต้นการนับถ่านถึง 1
Increase the count
ตัวอย่าง
## initializing string
string = "tutorialspoint"
## initializing a dictionary
duplicates = {}
for char in string:
## checking whether the char is already present in dictionary or not
if char in duplicates:
## increasing count if present
duplicates[char] += 1
else:
## initializing count to 1 if not present
duplicates[char] = 1
for key, value in duplicates.items():
if value > 1:
print(key, end = " ")
print() หากคุณเรียกใช้โปรแกรมข้างต้น
ผลลัพธ์
t o i