import itertools from itertools import permutations import copy guyprefers = { 'm1': ['w2','w1','w3'], 'm2': ['w3','w2','w1'], 'm3': ['w3','w1','w2'], } galprefers = { 'w1': ['m2','m3','m1'], 'w2': ['m3','m1','m2'], 'w3': ['m1','m2','m3'], } uncertainty ={ 'm1': [[{'pref':['w3','w2','w1'], 'prob': 1/2}], [{'pref':['w2','w1','w3'], 'prob': 1/2}], [{'pref':['w1','w3','w2'], 'prob': 1/2}]], 'm2': [[{'pref':['w3','w2','w1'], 'prob': 1/2}], [{'pref':['w2','w1','w3'], 'prob': 1/2}], [{'pref':['w1','w3','w2'], 'prob': 1/2}]], 'm3': [[{'pref':['w3','w2','w1'], 'prob': 1/2}], [{'pref':['w2','w1','w3'], 'prob': 1/2}], [{'pref':['w1','w3','w2'], 'prob': 1/2}]], 'w1': [[{'pref':['m1','m2','m3'], 'prob': 1}]], 'w2': [[{'pref':['m1','m2','m3'], 'prob': 1}]], 'w3': [[{'pref':['m1','m2','m3'], 'prob': 1}]], } guys = sorted(guyprefers.keys()) gals = sorted(galprefers.keys()) listuncertain = list(uncertainty) prevGuyPrefers = {} prevGalPrefers = {} prevStable = {} db_engaged = [] def check(engaged): #thanks to rosettacode inversengaged = dict((v,k) for k,v in engaged.items()) # print("====================CHECKING===============================") # print("-- %s" % engaged) # print("guypref- %s" % guyprefers) # print("galpref- %s" % galprefers) # print("===================================================") for she, he in engaged.items(): shelikes = galprefers[she] shelikesbetter = shelikes[:shelikes.index(he)] helikes = guyprefers[he] helikesbetter = helikes[:helikes.index(she)] for guy in shelikesbetter: guysgirl = inversengaged[guy] guylikes = guyprefers[guy] if guylikes.index(guysgirl) > guylikes.index(she): return False for gal in helikesbetter: girlsguy = engaged[gal] gallikes = galprefers[gal] if gallikes.index(girlsguy) > gallikes.index(he): return False return True def initialMatching(newGuyPrefers, newGalPrefers, verbose=False): freeAgents = [] engaged = {} freeAgents = guys[:] newGuyPrefers2 = copy.deepcopy(newGuyPrefers) newGalPrefers2 = copy.deepcopy(newGalPrefers) # keep perform matching while there are still the free agents while len(freeAgents) > 0: guy = freeAgents.pop(0) if verbose: print("Processing %s" % guy) guylists = newGuyPrefers2[guy] gal = guylists.pop(0) gallists = newGalPrefers2[gal] fiance = engaged.get(gal) if fiance: if verbose: print("%s is engaged with %s" % (gal, guy)) # try to break, check preference rank if gallists.index(guy) < gallists.index(engaged[gal]): if verbose: print("ada kesempatan nih") engaged[gal] = guy if verbose: print("%s putus dengan %s, lebih milih %s" % (gal, fiance, guy)) if newGuyPrefers2[fiance]: freeAgents.append(fiance) else: if verbose: print("uda ga ada kesempatan brooo...") if guylists: freeAgents.append(guy) else: engaged[gal] = guy if verbose: print("%s now engaged with %s" %(gal, guy)) # print("Engaged: %s " % engaged) return engaged def initialWomanMatching(newGuyPrefers, newGalPrefers, verbose=False): freeAgents = [] engaged = {} freeAgents = gals[:] newGuyPrefers2 = copy.deepcopy(newGalPrefers) newGalPrefers2 = copy.deepcopy(newGuyPrefers) # keep perform matching while there are still the free agents while len(freeAgents) > 0: guy = freeAgents.pop(0) if verbose: print("Processing %s" % guy) guylists = newGuyPrefers2[guy] gal = guylists.pop(0) gallists = newGalPrefers2[gal] fiance = engaged.get(gal) if fiance: if verbose: print("%s is engaged with %s" % (gal, guy)) # try to break, check preference rank if gallists.index(guy) < gallists.index(engaged[gal]): if verbose: print("ada kesempatan nih") engaged[gal] = guy if verbose: print("%s putus dengan %s, lebih milih %s" % (gal, fiance, guy)) if newGuyPrefers2[fiance]: freeAgents.append(fiance) else: if verbose: print("uda ga ada kesempatan brooo...") if guylists: freeAgents.append(guy) else: engaged[gal] = guy if verbose: print("%s now engaged with %s" %(gal, guy)) # print("Engaged: %s " % engaged) engaged2= {y:x for x,y in engaged.items()} return engaged2 def unique(list1): # initialize a null list unique_list = [] # traverse for all elements for x in list1: # check if exists in unique_list or not if x not in unique_list: unique_list.append(x) # print list for x in unique_list: print(x) def matriks(guypref, galpref, guy, fiance): # print("Find matrix of agent %s" % agent) return matriks_value def dobelprobabilisticSMP(newGuyPrefers, newGalPrefers, instance, verbose=False): # decide the driver = man-optimal | woman-optimal if not prevGuyPrefers and not prevGalPrefers: if verbose: print("Preparing for initial matching...") # preparing for man optimal # set all men as free if orient == "man": global_engaged = initialMatching(newGuyPrefers, newGalPrefers, False) else: global_engaged = initialWomanMatching(newGuyPrefers, newGalPrefers, False) else: previous_sm = db_engaged[instance-2] engaged = previous_sm['stable'] #comparing preferences #compare guys preferences # elif prevGuyPrefers != newGuyPrefers and orient == "man": print("============ MAN OPTIMAL but man in probability ============") newGuyPrefers2 = copy.deepcopy(newGuyPrefers) newGalPrefers2 = copy.deepcopy(newGalPrefers) if orient == "man": print("all gal preferences are totally same with previous") print("Previous Engagement: %s" % engaged) # freeAgents = guys[:] freeAgents = [] for pair in engaged: if newGuyPrefers2[engaged[pair]].index(pair) > 0: print("%s is NOT %s's first option, remove for engagement" % (pair, engaged[pair])) print("--Append %s as free agents" % engaged[pair]) freeAgents.append(engaged[pair]) engaged[pair] = "" else: print("**********************%s is %s's first option, postpone removing********************************"% (pair, engaged[pair])) newMatriks = matriks(newGuyPrefers, newGalPrefers, engaged[pair], pair) if newMatriks == len(guys)*len(guys): print("- %s AND %s IS UNBREAKABLE" % (pair, engaged[pair])) print(" - Removing %s from all men preference" % (pair)) #remove maksimum agent from free agents # freeAgents.remove(engaged[pair]) for manPref in newGuyPrefers2: # print("Since %s and %s are maximum, remove %s from %s preference" % (engaged[pair], pair, pair, manPref)) newGuyPrefers2[manPref].remove(pair) while len(freeAgents) > 0: guy = freeAgents.pop(0) guyslist = newGuyPrefers2[guy] print("Processing %s..." % guy) #check guy previous partner key_list = list(engaged.keys()) val_list = list(engaged.values()) try: position = val_list.index(guy) fiance = key_list[position] print("Am I needed?????") print("%s previous partner: %s" % (guy, fiance)) print("%s rank in %s is %s" % (fiance, guy, newGuyPrefers[guy].index(fiance))) print("BEFORE engaged: %s" % engaged) newMatriks = matriks(newGuyPrefers, newGalPrefers, guy, fiance) oldMatriks = matriks(prevGuyPrefers, prevGalPrefers, guy, fiance) print("newMatriks: %s" % newMatriks) print("oldMatriks: %s" % oldMatriks) if newMatriks == (len(guys)*len(guys)): print("Maximum....") continue if prevGalPrefers == newGalPrefers and (newMatriks <= oldMatriks): #cek gal = guyslist.pop(0) print("Checking %s X %s.........." % (guy, gal)) propFiance = engaged.get(gal) if not propFiance: print("-%s engaged with %s" % (gal, guy)) engaged[gal] = guy else: print("-%s currently with %s" % (gal, propFiance)) if guy == propFiance: continue galslist = newGalPrefers2[gal] if galslist.index(propFiance) > galslist.index(guy) or (gal == fiance): try: key_list = list(engaged.keys()) val_list = list(engaged.values()) position = val_list.index(guy) engaged[key_list[position]] = propFiance print("--%s engaged with %s, set %s and %s as single" % (gal, guy, propFiance, key_list[position])) if propFiance not in freeAgents: freeAgents.append(propFiance) except: pass engaged[gal] = guy else: print("-%s stay with her fiance" % gal) if newGuyPrefers[guy].index(gal) > 0: print("--NOT FIRST OPTION") newGuyPrefers2[propFiance].insert(0,gal) freeAgents.append(guy) else: print("Continus.......") continue except: print("PASSSSSSSSSSSSSSSSSSSSSSSS") gal = guyslist.pop(0) print("Exception Checking %s X %s.........." % (guy, gal)) propFiance = engaged.get(gal) if not propFiance: print("-%s engaged with %s" % (gal, guy)) engaged[gal] = guy else: galslist = newGalPrefers2[gal] print("-%s currently with %s" % (gal, propFiance)) if galslist.index(propFiance) > galslist.index(guy): print("--%s now engaged with %s" % (gal, guy)) engaged[gal] = guy if propFiance not in freeAgents: freeAgents.append(propFiance) else: print("--%s stay with her fiance" % gal) freeAgents.append(guy) global_engaged = engaged # assign the preference as old preference prevGuyPrefers = newGuyPrefers prevGalPrefers = newGalPrefers prevStable = global_engaged return global_engaged args = [] for x in uncertainty: args.append(uncertainty[x]) c = 1 new_engaged = [] for combination in itertools.product(*args): print("#>>>>>>>>>>>>>>>>>>>>>>>>> INSTANCE %s <<<<<<<<<<<<<<<<<<<<<<<<<<" % c) n = 0 prob = 1 global_engaged = {} for x in combination: # print("[%s] : %s" % (listuncertain[n], x)) if listuncertain[n][0] == 'm': guyprefers[listuncertain[n]] = x[0]['pref'] prob = prob * x[0]['prob'] # print(x[0]['prob']) elif listuncertain[n][0] == 'w': galprefers[listuncertain[n]] = x[0]['pref'] prob = prob * x[0]['prob'] # print(x[0]['prob']) n = n + 1 print("#==========================") print("guyprefers= %s" % guyprefers) print("galprefers= %s" % galprefers) # print("PROB = %s " % prob) print("#==========================") guyprefers2 = copy.deepcopy(guyprefers) galprefers2 = copy.deepcopy(galprefers) checkGuyPrefers = copy.deepcopy(guyprefers2) checkGalPrefers = copy.deepcopy(galprefers2) ########## processing driver ############ # print("Begin: %s " % (time.ctime())) dobelprobabilisticSMP(guyprefers2, galprefers2, c, False) detail_db_engaged = {} detail_db_engaged['instance_number'] = c detail_db_engaged['guypref'] = guyprefers2 detail_db_engaged['galpref'] = galprefers2 detail_db_engaged['stable'] = global_engaged db_engaged.append(detail_db_engaged) print("RESULT : %s" % global_engaged) if check(global_engaged): print("CHECKING STABILITY: PASSED") else: print("CHECKING STABILITY: FAILED") break new_engaged.append(global_engaged.copy()) print("NEW_ENGAGED ada %s: %s" % (len(new_engaged),new_engaged)) unique(new_engaged) # print(db_engaged) # print("End: %s " % (time.ctime())) c = c + 1
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |