Tuesday, June 9, 2020

How to sort a list based on element's position

Let's say there is a list of numbers

data = [9,10,15,51,68,85,19]

Sort the list based on the number in the units place. So, here sort the data based on the second digit and output should be

[10, 51, 15, 85, 68, 9, 19]

Remember single digits has 0 prepended internally. We can do it with a single line using lambda and built in sort function of list

sorted(data, key=lambda x: x%10)

This works well for numerics. What if the list has a combination of strings and numerics or strings? In this case we want to convert everything into a string and sort based on the index of string required. In this example as we are looking at second digit/ letter, index will be 1 (remember indexes start with 0)

sorted(data, key=lambda x: str(x)[1] if len(str(x))>1 else str(x)[0])


Find pair of numbers that will generate target value

Let's say there is a list of values and you are given a target value. How will you find all the pair of numbers when added up will give the target value?

Example:

data = [1,5,11,2,10,9,3,2,10]
target = 12

In this example (1,11), (2,10), (9,3) and (2,10) again will produce the target of 12. However, we don't want to have the sequence of numbers repeating. How can we do that?

There are several ways to do it. However, the clean and easy way to do this is, removing duplicates from the list. How?

data = list(set(data))

We are converting list to set and back to list. This is going to remove duplicate values. Now to get the pairs, we can use list comprehension and produce list of tuples

[(val, target-val) for cnt,val in enumerate(data) if target-val in data[cnt+1:]]