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

หาตัวอักษรซ้ำในสตริงด้วย Python Collections.Counter


หาตัวอักษรที่เกิดขึ้นมากกว่า 1 ครั้งในสตริงโดยใช้ collections.Counter

ตัวอย่าง

Input: "Hello World. Let's learn Python"
Output: e:3, l:4, o:3, space:4, r:2, t:2, n:2

อัลกอริทึม

  1. สร้าง Counter จากสตริง (key=char, value=count)
  2. วนลูป key ทุกตัว ถ้า value > 1 พิมพ์

โค้ดตัวอย่าง

from collections import Counter

def calc_char_freq(string):
    freq_count = Counter(string)
    for key in freq_count:
        if freq_count[key] > 1:
            print(f"({key}, {freq_count[key]})")

myStr = "Hello World. Let's learn Python"
calc_char_freq(myStr)

ผลลัพธ์

(e, 3)
(l, 4)
(o, 3)
( , 4)
(r, 2)
(t, 2)
(n, 2)