Home > Enterprise >  Is there a more elegant way of finding minimum in array in this case?
Is there a more elegant way of finding minimum in array in this case?

Time:11-04

What needs to be done in this task:

Determine the amount of couples of neighbouring elements in which both of the numbers are multiple of 7 and also determine a minimal sum of the elements of such couples.

In the actual task I need to read a file, but here I put elements in the list by myself.

a = [7, 14, 2, 6, 5, 7, 7]

counter = 0
minSum = 1000000000000000000000 # This is what this question is all about
for i in range(len(a)):
    if a[i] % 7 == 0 and a[i   1] % 7 == 0:
        counter  = 1
        if (a[i]   a[i   1]) < minSum:
            minSum = a[i]   a[i   1]

print(counter, minSum)

So my question is basically this: is there a more elegant way of searching a minimal sum of elements, I mean without setting a giant number to the variable?

CodePudding user response:

Use float('inf'), which will always compare larger to any other number (except float('inf') and float('nan'), of course).

So:

minSum = float('inf')

CodePudding user response:

It is far more elegant to use the built-in function min to search for a minimum.

min_sum = min(
    x   y
    for (x, y) in zip(a, a[1:])
    if x % 7 == 0 and y % 7 == 0 
)

CodePudding user response:

Use itertools.pairwise to iterate through successive pairs of values and then find the minimum of valid candidates:

>>> import itertools
>>> min(sum(p) for p in pairwise(a) if p[0] % 7 == 0 and p[1] % 7 == 0)
14

CodePudding user response:

You could use None as a sentinel:

counter = 0
minSum = None
for i in range(len(a)-1):
    if a[i] % 7 == 0 and a[i 1] % 7 == 0:
        counter  = 1
        t = a[i]   a[i 1]
        if minSum is None or t < minSum:
            minSum = t

(By the way, range(len(a)) should be range(len(a)-1), which I've fixed here.)

  • Related