Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Mã Python in ký tự chung của hai chuỗi theo thứ tự alphabet


Cho hai chuỗi nhập từ người dùng, nhiệm vụ in tất cả ký tự chung theo thứ tự alphabet.

Ví dụ

Input: string1: python
string2: program
Output: op

Giải thích

Các chữ cái chung giữa hai chuỗi là o (1 lần), p (1 lần).

Thuật toán

Bước 1: Nhập hai chuỗi.
Bước 2: Chuyển hai chuỗi thành Counter dictionary.
Bước 3: Tìm phần tử chung bằng intersection (&).
Bước 4: Kết quả cũng là Counter dictionary với key chung và value là tần suất chung.
Bước 5: Dùng elements() của Counter để mở rộng list key theo tần suất.
Bước 6: Sắp xếp list tăng dần để in chuỗi kết quả theo alphabet.
Bước 7: Nối ký tự không space tạo chuỗi kết quả.

Ví dụ mã

from collections import Counter

def common(str1, str2):
    d1 = Counter(str1)
    d2 = Counter(str2)
    cdict = d1 & d2
    if len(cdict) == 0:
        print(-1)
        return
    cchars = list(cdict.elements())
    cchars = sorted(cchars)
    print("Common characters are ::>", ''.join(cchars))

# Driver program
if __name__ == "__main__":
    s1 = input("Enter first string")
    s2 = input("Enter second string")
    common(s1, s2)

Kết quả

Enter first string python
Enter second string program
Common characters are ::> op