Computer >> Máy Tính >  >> Lập trình >> Python

Từ được lặp lại nhiều thứ hai trong một chuỗi bằng Python?

Chuỗi đã cho, nhiệm vụ của chúng ta là tìm ra từ lặp lại thứ hai. Ở đây, chúng tôi Bộ đếm (trình lặp) để tạo từ điển chứa từ làm khóa và tần suất của nó dưới dạng giá trị.

Thuật toán

Step 1: Create user define list.
Step 2: Then convert list into a dictionary.
Step 2: Next get the values and sort them in descending order.
Step 3: Then the second element is the second largest value.
Step 4: Next again traverse whole dictionary and display key whose value is equal to second largest element.

Mã mẫu

# To print Second most repeated word in a sequence in Python from collections 
import Counter
defsecondrepeatation(A):
# Convert list into dictionary
con = Counter(A)
res = sorted(con.values(), reverse=True)
maxi = res[1]
for (key, val) in con.items():
   if val == maxi:
       print("Second most repeated word ::>",key)
       return
# Driver program
if __name__ == "__main__":
   A=list()			#create user defined list
n=int(input("Enter the size of the List ::"))
print("Enter the word ::")
for i in range(int(n)):
   k=input("")
   A.append(k)
secondrepeatation(A)		# call function

Đầu ra

Enter the size of the List ::4
Enter the word ::
aa
bb
aa
cc
Second most repeated word ::> bb