Home > database >  How can I let my code return the numbers that result in the biggest difference?
How can I let my code return the numbers that result in the biggest difference?

Time:11-09

I wrote this code:

def partition(lst: list):
    f = []
    for i in range(len(lst)):
        if i < len(lst)-1:
            diff = lst[i 1] - lst[i]
            f.append(diff)
        else:
            return f

def grouping(lst: list):
    for i in range(len(lst)):
        if lst[i 1] - lst[i] == 

print(grouping([1,3,5,7,12,14,15]))

I want grouping(lst) to return the two numbers that result in the biggest difference. How can I do that?

So if we use print(partition([1,3,5,7,12,14,15])), the output would be 5. I want grouping to return the numbers, whose difference is the max, or in this case, 5.

According to the input of print(partition([1,3,5,7,12,14,15])) the output groupingshould be [7,12] since they are the ones that has a difference of 5.

How can I do that?

CodePudding user response:

Use zip:

def partition(lst: list):
    return max(j-i for i,j in zip(lst[:-1], lst[1:]))

def grouping(lst: list):
    differences = [j-i for i,j in zip(lst[:-1], lst[1:])]
    return [(i, j) for i, j in zip(lst[:-1],lst[1:]) if j-i == max(differences)][0]

>>> partition([1,3,5,7,12,14,15])
5

>>> grouping(lst)
(7, 12)

If you want to use a dictionary, the following structure might be best:

dct = {(i, j): j-i for i, j in zip(lst[:-1], lst[1:])}

>>> max(dct.values())
5

>>> max(dct, key=dct.get)
(7, 12)

CodePudding user response:

You can use zip and dict and get what you want:

lst = [1,3,5,7,12,14,15]

res = {}
for a,b in zip(lst,lst[1:]):
    res.setdefault((b-a), []).append((a,b))

Output:

>>> res
{2: [(1, 3), (3, 5), (5, 7), (12, 14)], 5: [(7, 12)], 1: [(14, 15)]}

>>> max(res)
5

>>> res[max(res)]
[(7, 12)]
  • Related