简体   繁体   中英

How to print a range based on two lists, from the user input entered?

So basically, I want to write a python program where based on two lists, such as this:

minsalary = [22000,41000,10000,51500,13000]

maxsalary = [35000,95000,34000,65000,31000] 

The user enters an input and based on the input, the program prints out the range based on input AND position. Each index corresponds to a job and range. So index(position) 0 in minsalary and index 0 in maxsalary both are a range that corresponds to job 0. So from 22000 to 35000 at index 0 is a job in itself.

It is based on maximum salary, each range corresponds to an index(or job position)
So if user enters 30000, program would print the best range would be 22000 to 35000 based on position 0 (index).

Using built-in min with key :

minsalary = [22000,41000,10000,51500,13000]

maxsalary = [35000,95000,34000,65000,31000] 

def ranger(user_input):
    lower = min(minsalary, key = lambda x: abs(x-user_input))
    upper = min(maxsalary, key = lambda x: abs(x-user_input))
    print('Best range is %s to %s, use position %s' % (lower, upper, maxsalary.index(upper)))

Output:

ranger(13000)
# Best range is 13000 to 31000, use position 4

This will work without mixing up min/max values of different indexes (eg 33000):

minsalary = [22000,41000,10000,51500,13000]
maxsalary = [35000,95000,34000,65000,31000]
salary    = 14000
index     = min((b-a,i) for i,(a,b) in enumerate(zip(minsalary,maxsalary)) if salary in range(a,b+1))[1]
print(f'Best range is {minsalary[index]} to {maxsalary[index]}, use position {index}')

Here is a broken down version to better isolate each step:

ranges          = zip(minsalary,maxsalary)  # [ (min,max), (min,max), ... ]
indexedRanges   = enumerate(ranges)         # [ (0,(min,max)), (1,(min,max)) ... ]
eligibleIndexes = [ (b-a,i) for i,(a,b) in indexedRanges if salary>=a and salary <= b ] # [ (size,2), (size,4) ]
smallest        = min(eligibleIndexes) # (size,4)
index           = smallest[1]
print(f'Best range is {minsalary[index]} to {maxsalary[index]}, use position {index}')
  • The ranges variable converts the two arrays into an array of tuples with (minimum,maximu) salaries in the ranges.
  • The indexedRanges variable adds the index (position) to the ranges tuples
  • The eligibleIndexes filters indexedRanges to only keep the items where the salary is inside the range and returns the range size and the corresponding index
  • The smallest variable receives the minimum entry of eligibleIndexes which is the one with the smallest range size. The result is a tuple with the size and index.
  • The index of the best eligible range is the second part of the smallest tuple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM