1

members I am facing problem to do the following in Python. I have input as follows

Input {(1, 2): [(2,), (1,)], (1, 3): [(3,), (1,)], (2, 3): [(2,), (3,)], 
(1,): [1], (2,): [2], (3,): [3], (1, 2, 3): [(1, 2), (3,)]}  

Now the output should be

(1,2,3=(2),(1),(3). 

It needs to check the Input key (1,2,3) and its corresponding value is [(1,2),(3)] again it looks for (1,2) in input array and it finds value corresponding to (1,2) is (2) and (1). Any idea how to do it.My code is not working perfectly.

I need your help regarding this.

def OptimalPartition(L=[],tempdict=dict()):
global ret
L=tuple(L)
chk0=tempdict.get(L[0])
chk1=tempdict.get(L[1])
if len(tuple([chk0]))==1:
   print(L[0])
   ret.append(chk0)
else:
   OptimalPartition(list(L[0]),tempdict)
if len(tuple([chk1]))==1:
   print(L[1])
   ret.append(chk1)
else:
   OptimalPartition(list(L[1]),tempdict)
0

1 Answer 1

1

You basically just want to unpack each key-value entry indefinitely within the same dictionary.

This small snippet will let you do that, the formatting is up to you to get right.

d = {(1, 2): [(2,), (1,)], (1, 3): [(3,), (1,)], (2, 3): [(2,), (3,)], 
     (1,): [1], (2,): [2], (3,): [3], (1, 2, 3): [(1, 2), (3,)]}  


def unpack(d,key):
    if len(d[key]) == 1:
        return tuple(d[key])
    ret = tuple()
    for k in d[key]:
        if k in d:
            ret += unpack(d,k)
        else:
            # This happens if the value for the key has
            # one value, in that case we simply add that 
            # to the returning tuple
            ret += (k,)
    return ret


for key in d:
    ret = unpack(d,key)
    print('  key, ret: ',key,', ',ret)
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you @zeroth . You made my life easier.
@NARAYANCHANGDER Please follow the form of stackexchange, tick the answer button if it resolved your question, and tick up any questions/answer you may find interesting or excellently posed.
I will try this method.Ok i will follow this rule @zeroth
Here problem is when the key and value is same. In that case the program runs continuously till maximum recursion depth reached. For example d:{(1,2):[(1,2)],(1,2,3):[(1,2),(3)]} and output should be (1,2,3)=(1,2)(3)
@NARAYANCHANGDER see now, it should do as you suspected.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.