List Comprehension
List comprehension is a neat was to constuct a list in python within one line of code. The code below shows the general syntax for appending items using a loop.
By using list comprehension, this code can be reduced to:
A solution to this problem using list comprehension is the funtion firstUniqChar(s)
shown below:
The funtion firstUniqChar(s)
takes a string s
as the input. If the length of the string is 0 or 1 then the solution is trivial. In the case when there are multiple letters in the string, we use list comprehension to loop through each letter of the alphabet x in 'abcdefghijklmnopqrstuvwxyz'
and keep the indices s.index(x)
where the letter only occurs once s.count(x) == 1
. However, since we are traversing the letters in alphabetical order, we need to take the minimum index as the solution return min(idx)
.
In this example, the indices which are unique are returned as follows idx = [5,4]
. By taking the minimum of this list we gauruntee to return the first unique letter d
, even though its not the first unique intex returned.