Welcome, guest | Sign In | My Account | Store | Cart

Container can be used to contain sets of differents numbers and strings, and applying maths' operations such as intersection, union and other functions.

Python, 162 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#On the name of ALLAH and may the blessing and peace of Allah 
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 27/06/08
#Version :2.4
import operator
class Container:
    def __init__(self,switch):    #Initialize
       self.switch = switch
       self.value = [] 
       for item in switch:
           self.value.append(item)
    def append(self,node):
       return self.value.append(node)
    def __getattr__(self,name):
        if name == 'union':
           self.union = operator.or_
           return operator.attrgetter(name)
        elif name == 'intersect':
           self.intersect = operator.and_
           return operator.attrgetter(name)
        else :
             return getattr(self.value,name)
    def __getitem__(self,i):
       return self.switch[i]
    def __len__(self):            # Container length
       return len(self.switch)
    def __and__(self,other):      # Intersection 
       self.intersect = operator.and_
       res = []
       for item in self.switch:
		if item in other:
		    res.append(item)
       return Container(res)
    def __or__(self,other):       # Union
        self.union = operator.or_
	res = self.value[:]
        for item in other:
		if item not in res:
		    res.append(item)
        return Container(res)
    def insideout(self,other):     # !=Intersection != Union item only in x but not in y
        res = []
        for item in self.switch:
            if item not in other:
                res.append(item)
        return Container(res)
    def outinside(self,other):     # != Union != Intersection item in x and y but not in both
        res = []
        for item in self.switch:
            if item not in other:
                res.append(item)
        for item in other:
            if item not in self.switch:
                res.append(item)
        return Container(res)
    def __str__(self):             #Print
        return '<Container : %s \n<Length : %s' % (self.value,(len(self.switch)))

if __name__ == '__main__':
    X = Container([1,2,3,4,5,6])
    Y = Container([3,4,5,6,7,8,0])
    Z = Container([1,1,1,2,2,2,3,3,7,7,7,17])
    for i in Container(Z):
        if Z.count(i) > 1:
            Z.remove(i)
    print Z 
    print '[%s]' % min(X)    
    print '[%s]' % max(X) 
    print X.outinside(Y)
    print Y.outinside(X)
    X.union(Y)
    print X.union(X,Y)
    X.intersect(Y)
    print X.intersect(X,Y)
    print X | Y
    print X & Y 
    print X
    X.reverse(),
    print X
    print Y
    Y.reverse(),
    print Y
    Y.sort()
    print Y
    print X.insideout(Y)
    print Y.insideout(X)
    Z = Container ( [ "hello world","hello worl","hello wor","SE7EN"])
    W = Container ( [ "hello","Fouad Teniou","SE7EN","G"])
    print Z
    print W
    print Z & W
    a = Z | W
    a.reverse()
    print a
    print Z.insideout(W)
    print W.insideout(Z)
    print X & Y & W
    print X | Y | W
    G = Container('hello world')
    print G
    G & "try"
    print (G & "try")
    G | "try"
    print ( G | "try")

PS. There is no need to make Container as a subclass of list to be able to use the list commands such as reverse and sort... as it is mentioned in Python resourses, since list is a built in method and you can access it without having to use it as a super class 

-------------------------------------------------------------------
c:\hp\bin\Python>python "c:\hp\bin\Python\Scripts\Myscripts\Container2.py" 
<Container :  [1,2,3,7,17]
<Length : 5 
[1]
[6] 
<Container : [1,2,7,8,0]
<Length : 5
<Container : [7,8,0,1,2]
<Length : 5
<Container : [1,2,3,4,5,6,7,8,0]
<Length : 9
<Container : [1,2,3,4,5,6,7,8,0]
<Length : 9
<Container : [3,4,5,6]
<Length : 4
<Container : [3,4,5,6]
<Length : 4
<Container : [1,2,3,4,5,6]
<Length : 6
<Container : [6,5,4,3,2,1]
<Length : 6 
<Container : [3,4,5,6,7,8,0]
<Length : 7
<Container : [0,8,7,6,5,4,3]
<Length : 7 
<Container : [0,3,4,5,6,7,8]
<Length : 7 
<Container : [1,2]
<Length : 2 
<Container : [7,8,0]
<Length : 3 
<Container : ['hello world', 'hello word','hello wor','SE7EN']
<Length : 4 
<Container :['hello','Fouad Teniou','SE7EN','G']
<Length : 4
<Container : ['SE7EN']
<Length : 1
<Container : ['G','Fouad Teniou','hello','SE7EN','hello war','hello word','hello world']
<Length : 7
<Container : ['hello world','hello word','hello wor']
<Length : 3
<Container : ['hello','Fouad Teniou','G']
<Length : 3
<Container : []
<Length : 0
<Container : [1,2,3,4,5,6,0,7,8,'hello','Fouad Teniou','SE7EN','G']
<Length : 13
.......
..........
.........
...........

c:\hp\bin\Python>







  

You can use the list or other built in object functions ( reverse, sort , count , etc...) without having to make Container as a subclass of list as it is described in Python resources. However, insideout function could also be used for some mathematics and scientific studies.

7 comments

Daniel Lepage 15 years, 10 months ago  # | flag

Redundancy. The functionality you're trying to create already exists in the builtin type set:

x = set([1,2,3,4])
y = set([3,4,5,6])
print x # prints 'set([1, 2, 3, 4])'
print y # prints 'set([3, 4, 5, 6])'
print x The functionality you're trying to create already exists in the builtin type set:
<pre>
x = set([1,2,3,4])
y = set([3,4,5,6])
print x # prints 'set([1, 2, 3, 4])'
print y # prints 'set([3, 4, 5, 6])'
print x

</pre>

Fouad Teniou (author) 15 years, 10 months ago  # | flag

Fouad Teniou. Thank you for your comment, Please check the new update on 28/06/08, I am sure it will be something interesting and different for you.

Gary Eakins 15 years, 10 months ago  # | flag

many coding errors. The return statements in the __getattr__ method are incorrectly indented. if __main__... should be 'if __name__...' and should end with ':'. 'Print' should be 'print'.

Gary Eakins 15 years, 10 months ago  # | flag

A Terser Version.

class Container:
    def __init__(self,switch=[]):  #Initialize
       self.union = self.__or__ # alias
       self.intersect = self.__and__ # alias
       self.value = list(switch)
    def __getattr__(self, name):
       """Applies an unknown attribute to list object."""
       return getattr(self.value, name)
    def __getitem__(self,i):
       """Return the ith item in the value."""
       return self.value[i]
    def __and__(self,other):      # Intersection
       res = [item for item in self.value if item in other]
       return Container(res)
    def __or__(self,other):       # Union
        res = self.value[:]
        for item in other:
            if item not in res:
                res.append(item)
        return Container(res)
    def insideout(self,other):     # !=Intersection != Union
        res = []
        for item in self.value:
            if item not in other:
                res.append(item)
        return Container(res)
    def __str__(self):             #Print
        return '&lt;Container : %s Length : %s&gt;' % (self.value,(len(self.value)))

import sys
def exec_(text):
    exec text in sys.modules['__main__'].__dict__
    print ' ', text, '---&gt;', '%s is' % (text[0]), repr(eval(text[0]))

def eval_(text):
    print '  ', text, '---&gt;', eval(text)

if __name__ == '__main__':
    exec_('X = Container([1,2,3,4,5,6])')
    exec_('Y = Container([3,4,5,6,7,8,0])')
    eval_('X.union(Y)')
    eval_('X.intersect(Y)')
    exec_("X = Container(['thud'])")
    exec_("Y = Container(['foo'])")
    eval_('X.union(Y)')
    eval_('X.intersect(Y)')
    eval_('X | Y')
    eval_('X &amp; Y ')
    exec_('X.append("python")')
    exec_('X.reverse()')
    exec_('Y.extend(["mary", "had"])')
    exec_('Y.reverse()')
    exec_('Y.sort()')
    eval_('X.insideout(Y)')
    eval_('Y.insideout(X)')
    exec_('Z = Container ( [ "hello world","hello worl","hello wor","SE7EN"])')
    exec_('W = Container ( [ "hello","Fouad Teniou","SE7EN","G"])')
    eval_('Z &amp; W')
    exec_('a = Z | W')
    exec_('a.reverse()')
    eval_('Z.insideout(W)')
    eval_(' W.insideout(Z)')
    eval_('X &amp; Y &amp; W')
    eval_('X | Y | W')
    exec_("G = Container('hello world')")
    eval_('G &amp; "try"')
    eval_('G | "try"')
Fouad Teniou (author) 15 years, 10 months ago  # | flag

Fouad Teniou. Thank you for your comment, and I realised the indented faults at home yesterday and applied changes today before I read your comment. However, you should know that I wrote the program at the Central Library and I do not have a direct access to python software to check for errors, but my version is working properly now and it is different, because I do not need to call the built in list object in my coding or use the __repr__ definition, yet without defining the intersection or union, I still call their attributes just by using an if statment on the __getattr__ definition and the operator attrgetter(name). I noticed your version and I appreciate your effort, yet my version could be used efficiently and effectively better, by accessing the list built in object without having to writing it in the program or defining the union or intersection to use their attribute names as I read in Python various resources. you should know that the volume of data, and the time it take for the program to execute is very important.

Jack Trainor 15 years, 10 months ago  # | flag

Why do you keep revising this? Are you improving it? Do you find this code useful for your work?

Fouad Teniou (author) 15 years, 9 months ago  # | flag

Fouad Teniou. Yes I did improve it and added a new function (outinside),

which, will be extremely useful for all types of users.

Created by Fouad Teniou on Fri, 27 Jun 2008 (PSF)
Python recipes (4591)
Fouad Teniou's recipes (37)

Required Modules

  • (none specified)

Other Information and Tasks