-1

Trying to make an application that would designate a family member to give a present to another one with the following restriction :

    - you can't designate your partner
    - you can't designate yourself
    - you can't designate a different generation
    - you can only recieve a gift from one person

Here is my code :

import random

adultes=['Helene', 'Malo', 'Sophie', 'Olivier', 'Francois']

couples = {'Helene':'Olivier', 'Sophie':'Malo', 'Gwendal':'Justine', 'Audren':'Vanessa', 'Lila':'Michel', 'Gauthier':'Ana'}


def gift(d):
    r=d
    for n in d:
        x=random.choice(r)
        
        while (n in couples) or ((n in couples.values()) and (x in couples)) or n==x:
            
            if n==x:
                if n==d[len(d)-1]:
                    break
                else:
                    x=random.choice(r)
            
            elif (n in couples.values()) and (x in couples):
                if couples[x]==n:
                    x=random.choice(r)
                else: break
            
            
            elif n in couples:
                if couples[n]==x:
                    x=random.choice(r)
                else: break
                   
        
        
        print n + " will make a present to " + x
        r.remove(x)
        #I encouter a wierd result so i tried to print my list.
        print d


gift(adultes)

The idea behind this code is to iterate through the list of a generation (here adultes), and for each member pick a reciever that will not be not be your partner or yourself.

Therefore in my gift function i create a reciever list r. Everytime a reciever is designated he gets removed from it.

Problem : it's my adultes list that gets shorten and i don't understand wh but it leads me to unexpected results.

Problem 2 : i'm very beginner in Python. Still i want my function to work if i make new list of generation or add couples to the existing ones.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Aod Ren
  • 681
  • 1
  • 8
  • 17
  • You should use some more brackets, otherwise the boolean equation is solved linearly, and you will not get the result you expect (according to the `if`-`else`-part later). – arc_lupus Nov 24 '15 at 10:09

1 Answers1

2

r=d just makes r point to the same list as d. It does not make a copy. If you want to modify one without changing the other, you actually do need to make a copy. One way of doing this would be to do

r = d[:]
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895