3 of 3 added 238 characters in body

Python 2.7 - 447B (filesize)

This is my first try at Codegolf, I hope it satisfies. I needed 2h. (But I'm still a beginner at Python)

Edit: Thanks to "Kevin Lau - not Kenny" for pointing out these:

  • pythons self argument in a class can be replaced by anything
  • indentation only has to be a single space
  • the builtin sorted - funktion (I knew I had seen it, but I thought it to be a method in lists)
  • __ radd __ is not needed (I only support adding B-objects(Bag-type) anyways)

Edit: Additionally I saved space by replacing functions with lambdas and new lines and indentations with more semicolons.

Code:

class B:
 def __init__(S,L=[]):S.L=sorted(list(L));S.p=lambda:[[i]*S.L.count(i)for k,i in enumerate(S.L)if i!=S.L[k-1]];S.__eq__=lambda o:S.L==o.L;S.__rmul__=S.__mul__=lambda o:B(S.L*o);S.__add__=lambda o:B(S.L+o.L);S.__sub__=lambda o:B([i for k in S.p()for i in k[:max(0,S.L.count(k[0])-o.L.count(k[0]))]]);S.__div__=lambda o:B([i for k in S.p()for i in k[::o][:[-1,None][len(k)%o==0]]]);S.c=lambda o:min([S.L.count(i)//o.L.count(i)for i in o.L])

checks:

print B([1,2,2,3]) + B([1,2,4]) == B([1,1,2,2,2,3,4]) # Add

print B([1,2,2,4]) - B([1,2]) == B([2,4]) #Substract
print B([1,2,3])   - B([2,4]) == B([1,3]) #Substract

print B([1,2,3,3,4]) * 3 == B([1,1,1,2,2,2,3,3,3,3,3,3,4,4,4])#Multiply
print 2 * B([1,3]) == B([1,1,3,3])                            #

print B([1,1,2,2,2])   /2 == B([1,2]) #Divide
print B([1,2,2,3,3,3]) /3 == B([3])   #

print B([1,1,2,2,2,2,3,3,3]).c(B([1,2,3]))==2 #Contained n times

print B([3,2,1,2]) == B([1,2,2,3]) # Equal
print B([1,2,3])   == B([1,2,2,3]) # Unequal

Output:

True
True
True
True
True
True
True
True
True
False

I might try it an other time with set as basis some time. Edit: Maybe I'll even try with functions only.