Bruffff
Bruffff

Reputation: 53

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

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?

Upvotes: 0

Views: 58

Answers (1)

not_speshal
not_speshal

Reputation: 23146

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)

Upvotes: 2

Related Questions