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.

for item in iterable:
  if condition == True:
    newlist.append(x)

By using list comprehension, this code can be reduced to:

newlist = [expression for item in iterable if condition == True]

A solution to this problem using list comprehension is the funtion firstUniqChar(s) shown below:

def firstUniqChar(s):
        """
        :type s: str
        :rtype: int
        """
        
        if len(s) == 0:
            return -1

        elif len(s) == 1:
            return 0

        else:
            idx = [s.index(x) for x in 'abcdefghijklmnopqrstuvwxyz' if s.count(x) == 1]
            return min(idx)

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).

firstUniqChar(s = 'aabbdc')

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.

Liam Healy

Liam Healy

Liam Healy
Experienced Quantitative Model Developer within Retail Banking and Treasury. Passionate about about modelling, programming and optimisation!

The First Order Greeks

Mathematics and Quantitative Finance Continue reading

Deriving Delta for European Options

Published on October 10, 2020

Gaussian Copula Simulation

Published on September 15, 2020