Exercises - list and set

Let us go through some exercises related to list and set.

Get second largest integer

Develop a code snippet using list and set manipulation functions to get second largest element from the list.

  • List: [1, 5, 2, 1, 7, 5, 7, 3]

  • Answer: 5

# Your code should go here

Create a list for integers

Develop a function which take a list as argument and return a new list with only integers. You can develop this using loops.

  • The list might contain data with different data types.

  • The new list with only integers should be sorted in descending order.

  • The new list should only contain unique values

# You should add the logic here
def extract_integers(l):
    l_ints = []
    return l_ints
extract_integers([1, 'Hello', None, 5, 0.15, 1, 5]) # Answer: [5, 1]

Get top n salaries

Develop a function which take a list of salaries and give us top n salaries. Solve the problem with out using loops.

  • The function should take 2 arguments - list of salaries and the top n.

  • Based up on the value passed as part of second argument, you should get those many top salaries.

  • We should get only unique top n salaries

# You should add the logic here
def top_n_salaries(salaries, top_n):
    salaries_top_n = []
    return salaries_top_n
salaries = [
    18732.8, 12842.28, 13391.69, 14061.23,
    25509.77, 13636.95, 11841.63, 11519.12,
    16719.45, 25066.37, 12842.28, 25066.37
]
top_n_salaries(salaries, 3)
# Output: [25509.77, 25066.37, 18732.8]
top_n_salaries(salaries, 5)
[25509.77, 25066.37, 18732.8, 16719.45, 14061.23]