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

Chuyển đổi POS sang SOP trong Python

Bài viết trình bày giải pháp chuyển dạng POS (Product of Sums) sang dạng SOP (Sum of Products) tương đương.

Chuyển đổi thực hiện bằng: đếm số biến số trong POS, tính các maxterm và minterm.

Ví dụ

# Python code to convert standard POS form to standard SOP form

# Đếm số biến
def count_no_alphabets(POS):
    i = 0
    no_var = 0
    while (POS[i] != '.'):
        if (POS[i].isalpha()):
            no_var += 1
        i += 1
    return no_var

# Tính maxterm
def Cal_Max_terms(Max_terms, POS):
    a = ""
    i = 0
    while (i < len(POS)):
        if (POS[i] == '.'):
            b = int(a, 2)
            Max_terms.append(b)
            a = ""
            i += 1
        elif (POS[i].isalpha()):
            if (i + 1 != len(POS) and POS[i + 1] == "'"):
                a += '1'
                i += 2
            else:
                a += '0'
                i += 1
        else:
            i += 1
    Max_terms.append(int(a, 2))

# Chuyển minterm sang nhị phân và tạo SOP
def Cal_Min_terms(Max_terms, no_var, start_alphabet):
    Min_terms = []
    max_val = 2 ** no_var
    for i in range(0, max_val):
        if (Max_terms.count(i) == 0):
            b = bin(i)[2:]
            while (len(b) != no_var):
                b = '0' + b
            Min_terms.append(b)
    SOP = ""
    for i in Min_terms:
        value = start_alphabet
        for j in i:
            if (j == '0'):
                SOP = SOP + value + "'"
            else:
                SOP = SOP + value
            value = chr(ord(value) + 1)
        SOP = SOP + "+"
    SOP = SOP[:-1]
    return SOP

# Main
def main():
    POS_expr = "(A'+B'+C).(A+B+C').(A+B'+C).(A'+B+C)"
    Max_terms = []
    no_var = count_no_alphabets(POS_expr)
    Cal_Max_terms(Max_terms, POS_expr)
    SOP_expr = Cal_Min_terms(Max_terms, no_var, POS_expr[1])
    print("Standard SOP form of " + POS_expr + " ==> " + SOP_expr)

if __name__ == "__main__":
    main()

Kết quả

Standard SOP form of (A'+B'+C).(A+B+C').(A+B'+C).(A'+B+C) ==> A'B'C'+A'BC+AB'C+ABC

Chuyển đổi POS sang SOP trong Python

Các biến khai báo trong phạm vi cục bộ, tham chiếu như hình trên.

Kết luận

Đã học cách chuyển POS sang SOP.