Python program to print the string with minimum number of unique characters
In this Python tutorial post, we are going to learn how to write a Python code to print the string with the minimum number of unique characters. Take for example, we have a list with five different strings each of varying length with each string consisting of all unique characters. In the output, the string with minimum unique characters will be displayed as shown below.
OUTPUT:
Original List is: [‘abc’, ‘qr’, ‘with’, ‘boywp’, ‘cabled’]
The string with minimum unique characters is:qr
Print only the string with minimum number of unique characters in Python
The entire Python code to perform the said task is as shown below:
list = ['abc', 'qr', 'with', 'boywp', 'cabled'] print("Original List is:" + str(list)) dict = {i: len(set(i)) for i in list} pranjal = min(dict, key=dict.get) print("The string with minimum unique characters is:" + str(pranjal))
- As can be seen in the above code, at first we have defined a list with five different strings each of varying length and each string containing all unique characters and we have printed the original list with the print statement.
str()
is a built in function in python that returns a string representation of whatever value we have passed. - Then we have used dictionary comprehension concept of python to point out the string with minimum unique characters. ‘dict’ is a dictionary and comprehension part is written inside the parentheses with a for loop. The for loop will check for variable ‘i’ in the list.
- After that we have used the
min()
inbuilt function of python to access the ‘dict’ variable and to find the string with minimum number of unique characters and store it in ‘pranjal’ variable. - Lastly, we will print the string with minimum unique characters by accessing the ‘pranjal’ variable.
Output:
Original List is:['abc', 'qr', 'with', 'boywp', 'cabled'] The string with minimum unique characters is:qr
Congrats! It’s done.
Leave a Reply