So I have a list and I would like to "assign" the values to a different random value.
For eg.
list = ["dog", "cat", "rat", "bird", "monkey"]
I would like an output like
{"dog": "bird", "cat": "monkey", "rat": "dog", "bird": "rat", "monkey": "cat"}
What I would like is:
- A value can't be assigned to itself e.g not {"cat": "cat"}
- A value can only be assigned once e.g not {"cat": "dog", "rat": "dog"}
- Values can't be assigned to each other e.g not {"cat": "dog", "dog", "cat"}
I tried this code:
def shuffle_recur(_list):
final = {}
not_done = copy.deepcopy(_list)
for value in _list:
without_list = not_done.copy()
if value in without_list :
without_list.remove(value)
if value in final.values():
for final_key, final_value in final.items():
if final_value == value:
print(final_value, ' ', final_key)
if final_key in without_list :
without_list.remove(final_key)
if len(without_list) < 1:
print('less')
return shuffle_recur(_list)
target = random.choice(without_list)
not_done.remove(target)
final[value] = target
print('{} >> {}'.format(value, target))
return final
But it is very messy and I don't think it the the best way. What would be a better way to do this?