Home > Back-end >  A better solution to solve sorting numbers with functions?
A better solution to solve sorting numbers with functions?

Time:12-15

Im new to python and trying to learn the use of function. I have some numbers i want to sort into low and high's. And want to sort them by calling functions. How would you do it? Code below :)

rsi_list = ([14, 88, 56, 74, 25, 22, 41, 55, 31, 98, 44, 56, 24, 43, 87, 15, 91, 71, 14, 16, 33, 38, 4, 6, 3, 78])


def sort_rsi_low(x):
    low_rsi = []
    for n in rsi_list:
         if n < 50:
            low_rsi.append(n)
    return low_rsi


print(sort_rsi_low(rsi_list))


def sort_rsi_high(x):
    high_rsi = []
    for n in rsi_list:
        if n > 50:
            high_rsi.append(n)
    return high_rsi


print(sort_rsi_high(rsi_list))

CodePudding user response:

I don't quite understand the use case for this but I think this can be solved using a single function:

def sort_low_high(x):
    low_rsi, high_rsi = [], []
    for n in x:
         if n < 50:
            low_rsi.append(n)
         else:
            high_rsi.append(n)

    return low_rsi, high_rsi

Then, call function and expand the return values into lower and higher` variables

rsi_list = [
    14, 88, 56, 74, 25, 22, 41, 55, 31, 98, 44, 56, 24,
    43, 87, 15, 91, 71, 14, 16, 33, 38, 4, 6, 3, 78
]

lower, higher = sort_low_high(rsi_list)
print('< 50:', lower)
print('> 50:', higher)

# Output
# < 50: [14, 25, 22, 41, 31, 44, 24, 43, 15, 14, 16, 33, 38, 4, 6, 3]
# > 50: [88, 56, 74, 55, 98, 56, 87, 91, 71, 78]

CodePudding user response:

You can use "List Comprehension" in Python which offers a shorter syntax when you want to create a new list based on the values of an existing list. Source: https://www.w3schools.com/python/python_lists_comprehension.asp

def sort_rsi_low(x):
    return [a for a in x if a < 50]
print(sort_rsi_low(rsi_list))
def sort_rsi_high(x):
    return [a for a in x if a > 50]
print(sort_rsi_high(rsi_list))

And you can make it shorter by using Lambda which is a small anonymous function. Source: https://www.w3schools.com/python/python_lambda.asp

sort_rsi_low = lambda x: [a for a in x if a < 50]
print(sort_rsi_low(rsi_list))
sort_rsi_high = lambda x: [a for a in x if a > 50]
print(sort_rsi_high(rsi_list))
  • Related