lundi 26 septembre 2016

Python: random choice executing all function calls listed

I'm stuck on a probably simple issue: when using choice with functions, it seems like all of them gets executed while only one should. Example:

from ordereddict import OrderedDict
from random import choice

def PrintStrings():
    Text = choice(["Gutentag!", "Ni hao!", "Hola!"])
    print "Chosen Text is:", Text
    return Text

class Greeting():
    fields = OrderedDict([
         ("Morning",     "Hi"),
         ("Afternoon",   "Good Afternoon!"),
         ("Evening",     "Good Evening!"),
    ])

    def change(self):
        self.fields["Morning"] = "Good morning!"

    def changerandom(self, n = 1): 
        function=[
                    {self.fields["Morning"]: PrintStrings()},
                    {self.fields["Afternoon"]: PrintStrings()},
                    {self.fields["Evening"]: PrintStrings()},
                 ]
        result = {}
        for i in range(n):
            result.update(choice(function))
            print "Updated string:",result
            return result

text = Greeting()
text.change()
text.changerandom()

When running this script, I get all 3

                    {self.fields["Morning"]: PrintStrings()},
                    {self.fields["Afternoon"]: PrintStrings()},
                    {self.fields["Evening"]: PrintStrings()},

executed, while it shouldn't. This script returns:

Chosen Text is: Ni hao!
Chosen Text is: Gutentag!
Chosen Text is: Hola!
Updated string: {'Good morning!': 'Hola!'}

Expected result is:

Chosen Text is: Hola!
Updated string: {'Good morning!': 'Hola!'}




Aucun commentaire:

Enregistrer un commentaire