String diberikan, tugas kita adalah mencari tahu kata kedua yang diulang. Di sini kita Counter(iterator) untuk membuat kamus yang berisi kata sebagai kunci dan frekuensinya sebagai nilai Show
AlgoritmaStep 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. Kode contoh# 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_ KeluaranEnter the size of the List ::4 Enter the word :: aa bb aa cc Second most repeated word ::> bb Saat diperlukan untuk menemukan karakter yang paling sering muncul dalam string, kamus kosong dibuat, dan elemen dalam string diulangi. Ketika sebuah karakter ditemukan dalam kamus, itu adalah kenaikan, selain itu ditetapkan ke 1. Nilai maksimum dalam kamus ditemukan, dan ditugaskan ke variabel ContohDi bawah ini adalah demonstrasi yang sama my_string = "Python-Interpreter" print ("The string is : ") print(my_string) max_frequency = {} for i in my_string: if i in max_frequency: max_frequency[i] += 1 else: max_frequency[i] = 1 my_result = max(max_frequency, key = max_frequency.get) print ("The maximum of all characters is : ") print(my_result) KeluaranThe string is : Python-Interpreter The maximum of all characters in Python-Interpreter is : e_ Penjelasan
|