Homicidal
Homicidal

Reputation: 41

Finding minimal value with condition python

a = []
for i in range(3):
    a.append(input())
j = 0
for i in a:
   if i % 10 != 7:
       j = min(a)
print j

I need an algorithm which finds the smallest positive number in list, which decimal representation does not end with the number 7. It is guaranteed that the list has at least one positive element, which decimal representation does not end with the number 7. I tried this, but condition doesn't work. For example: it says that 7 is smallest in [9,8,7].

Upvotes: 4

Views: 11499

Answers (2)

Adrián Pérez
Adrián Pérez

Reputation: 2216

EDIT: Ok I misreaded your code, you were using remainder which i think is better. Although it could work using just plain divisions like this.

if ((i / 10) - int(i / 10)) * 10 != 7:

And also, if you aren't using Python 3, you might need to use this for the above to work:

from __future__ import division

Or casting to floats with float(), but that makes it too messy.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1125258

You are always testing for the minimum number in a, albeit as many times as there are unfiltered numbers in a. Don't add numbers that end in 7 to a in the first place; you probably want to filter on positive numbers too:

a = []
for i in range(3):
    value = input()
    if i % 10 != 7 and i >= 0:
        a.append(value)

print min(a)

Alternatively, filter out values in a generator expression:

a = []
for i in range(3):
    a.append(input())

print min(i for i in a if i % 10 != 7 and i >= 0)

Upvotes: 5

Related Questions