简体   繁体   中英

Finding the next biggest integer in two arrays

I have two arrays, arr_x and arr_y . These arrays contain integers 1 to 20, no duplicates and not all integers from 1 to 20 are in these arrays. For example:

arr_x = [4,5,6,7]
arr_y = [16,15,14,13]

I'm counting up from 1 and lets say I get to 7, I want to find the next biggest integer that is in either of these arrays, and then perform an action if it is in arr_y , and do nothing if it is in arr_x .

Referencing the example it would find, the next biggest integer in either of these arrays is 13, and its in arr_y , so it would perform the action.

I've been stuck on this without nesting all these if's and for loops and it gets really sloppy, any ideas?

Simplest answer I can think of: Filter out all values lower or equal to 7, then pick the lowest remaining value.

try:
    # Replace 7 with increasing variable if run in loop.
    if min(filter(lambda n: n > 7, arr_x + arr_y)) in arr_y:
        perform_some_action()
except IndexError:
    print('There is no next biggest integer.')

I expanded on @Banana answer to include which list the value comes from so it should be simple to check if it comes from arr_y using...

if findNextLargest(arr_x,arr_y)[1] #to check if it is arr_y


def findNextLargest(arr_x,arr_y):
    res = False
    for i,each in enumerate([arr_x,arr_y]):
    #enumerate will mark which list it comes from
    #order is important so you can overwrite answer if found in X and Y, Answer Priority is given to Y

        filtered = filter(lambda n: n > 7,each) #filters using @Banana logic
        if filtered:res=  (min(filtered),i)     #grabs next largest using @Banana logic
return res #returns a tuple where first value is the next largest value and second is the list it comes from where 1 is y and 0 is x

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