Sort Tuple by Float Element

Tags: sort, tuple

Write a Python program to sort a tuple by its float element.

Example 1:

Input: ('34.6', '203.4', '44.2', '11.9', '12.6', '15.3') 
Output: ('11.9', '12.6', '15.3', '34.6', '44.2', '203.4')

Example 2:

Input: ('1.5', '10.7', '0.3', '5.5', '3.6', '1.9') 
Output: ('0.3', '1.5', '1.9', '3.6', '5.5', '10.7')

Use the sorted() function with a key argument that converts the elements to floats.

def sort_by_float(t):
    return tuple(sorted(t, key=float))

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!