The contains method

This is the place for queries that don't fit in any of the other categories.

The contains method

Postby Cereal » Fri May 09, 2014 9:41 am

I am working with classes and has this class:

Code: Select all
class Interval(object):
    def __init__(self, min, max=None): #task 6
        if max is None:
            max = min
        self.min = min
        self.max = max
    def __repr__(self):
        return '[{}, {}]'.format(self.min, self.max)

So the class is about intervals.

(And I will change some names later, since I named them min and max, which actually are things in Python)

I want to use a contains- method.

So if this is the Interval with the name K:
[1, 10]

I want to write
Code: Select all
print 2 in K

and get "true"
Code: Select all
print 12 in K

and get "false".

I have used other methods for add, sub, etc. and did similarly since I wasn't sure exactly what to put in the method.

I have written this:
Code: Select all
    def __contains__(self,other):
        f1,s1 = self.min, self.max
        p = other
        if f1<=p:
            if p<=s1:
                return Interval (0,0)
            return Interval(1,2)

So I have told Python to return Interval(0,0) if it is true. I don't want that. I tried to write return print "true" instead of return Interval(0,0), but I got this error message:
Code: Select all
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\", line 523, in runfile
    execfile(filename, namespace)
  File "C:\Users\mat11CJo\Downloads\Homework 2 Task 1, 2, 3, 4, 5, 6, 7, 8 N", line 95
    return print "true"
SyntaxError: invalid syntax

where line 95 is

Code: Select all
return print "true"

When I print return Interval(0,0) I don't get any errors and if I print this:
Code: Select all
B = Interval(1,7)
print 2 in B
print 8 in B

I get
True and False like I want to.

But I want to write something more correct in my method __contains__.
Any suggestion on what I could write instead?

Thank you,
Posts: 15
Joined: Tue Apr 15, 2014 7:42 am

Re: The contains method

Postby stranac » Fri May 09, 2014 9:46 am

You don't do "return print value", just "return value".
So it's not "return print 'true'", but "return True".

Also, your method can be super simple:
Code: Select all
def __contains__(self, value):
    return self.min <= value <= self.max

A quick test run:
Code: Select all
>>> K = Interval(1, 10)
>>> 2 in K
>>> 12 in K

P.S. That filename is ridiculous...
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
Posts: 1790
Joined: Thu Feb 07, 2013 3:42 pm

Re: The contains method

Postby Cereal » Fri May 09, 2014 9:58 am


I will work on the names :)
Posts: 15
Joined: Tue Apr 15, 2014 7:42 am

Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot] and 7 guests