0

I found a thread on this but am not having any luck getting it working.

min = 9
max = 10
a = ['8','9','10','11']

for x in a:
    if max >= x > min:
        print 'one'
    else:
        d = (max >= x > min)
        print d, x
    if (x > min >= max):
   #if (min < x >= max):
        print x
    else:
        print x, ' is equal to or greater than', max 

Outputs:

False 8
8  is equal to or greater than 10
False 9
9  is equal to or greater than 10
False 10
10  is equal to or greater than 10
False 11
11  is equal to or greater than 10

this thread working code? indicates syntax needs to be:

if 10000 <= number <= 30000:
pass

I've tried every combination of signs I can think of, and the returns are always True or False for all, which is wrong.

I've also tried this (much longer) code:

min = 9
max = 10
a = ['8','9','10','11']

for x in a:
    print 'X is:', x
    if int(x) == max:
        print 'max found:', x
    elif int(x) < max:
        if int(x) > min:
            print 'min:', x
    elif int(x) < min:
        print 'under range', x
    else:
        print 'out of range', x

with output also unexpected, since I expect to catch all cases:

X is: 8
X is: 9
X is: 10
max found: 10
X is: 11
out of range 11

Ugh! How can I check all items 'properly' and return under, at, over my min, max?

Community
  • 1
  • 1
shawn
  • 549
  • 1
  • 5
  • 11

1 Answers1

0

You need to compare int, int or str, str. Past that I would recommend bisect which gives you insertion points.

For example:

import bisect

minint, maxint = 9, 10
a = ['8','9','10','11']

b = [int(x) for x in a]

minidx = bisect.bisect_left(b, minint)
maxidx = bisect.bisect_left(b, maxint)

print('below:', a[0:minidx])
print('between:', a[minidx:maxidx])
print('above:', a[maxidx:])

which outputs:

below: ['8']
between: ['9']
above: ['10', '11']

Depending on how you define the comparison <= or < at each of the ends you need to apply either bisect_left or bisect_right

If we change the first bisect to right:

import bisect

minint, maxint = 9, 10
a = ['8','9','10','11']

b = [int(x) for x in a]

minidx = bisect.bisect_right(b, minint)
maxidx = bisect.bisect_left(b, maxint)

print('below:', a[0:minidx])
print('between:', a[minidx:maxidx])
print('above:', a[maxidx:])

The output changes and shows that nothing is in between 9 and 10

below: ['8', '9']
between: []
above: ['10', '11']

The docs (for 2.7): https://docs.python.org/2/library/bisect.html

mementum
  • 3,153
  • 13
  • 20
  • Nice! I've no experience with bisect. Thanks for posting! – shawn Jan 20 '16 at 17:28
  • Apart from the type error in my first code chunk - it turns out I don't actually need to check within, only case A or B. This code does what it's supposed to do: if len(rec) == max_rec_len: authored.append(rec) elif len(rec) == min_rec_len: records.append(rec) – shawn Jan 20 '16 at 17:28