- 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"

and

- 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)

else:

Interval(1,2)

else:

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\sitecustomize.py", line 523, in runfile

execfile(filename, namespace)

File "C:\Users\mat11CJo\Downloads\Homework 2 Task 1, 2, 3, 4, 5, 6, 7, 8 N le.py", 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,

L.