Python random.choice() Examples

The following are 30 code examples for showing how to use random.choice(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module random , or try the search function .

Example 1
Project: indras_net   Author: gcallah   File: menger_model.py    License: GNU General Public License v3.0 6 votes vote down vote up
def add_prod_goods(self):
        """
        Add who produces which good, and
        make them a vendor of that good in the market.
        """
        my_good = None
        for agent in self.agents:
            for good in self.market.goods_iter():
                if not self.market.has_vendor(good):
                    my_good = good
                    break

            if my_good is None:
                my_good = random.choice(list(self.market.goods_iter()))

            agent.prod_good = my_good
            self.market.add_vendor(my_good, agent)

        print("Market = " + str(self.market)) 
Example 2
Project: indras_net   Author: gcallah   File: el_farol.py    License: GNU General Public License v3.0 6 votes vote down vote up
def discourage(unwanted):
    """
    Discourages extra drinkers from going to the bar by decreasing motivation.
    Chooses drinkers randomly from the drinkers that went to the bar.
    """
    discouraged = 0
    drinkers = get_group(DRINKERS)
    while unwanted:
        if DEBUG:
            user_tell("The members are: " + drinkers.members)
        rand_name = random.choice(list(drinkers.members))
        rand_agent = drinkers[rand_name]

        if DEBUG:
            user_tell("drinker ", rand_agent, " = "
                      + repr(drinkers[rand_agent]))

        rand_agent[MOTIV] = max(rand_agent[MOTIV] - DISC_AMT,
                                MIN_MOTIV)
        discouraged += 1
        unwanted -= 1
    return discouraged 
Example 3
Project: indras_net   Author: gcallah   File: trade_utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_rand_good(goods_dict, nonzero=False):
    """
    What should this do with empty dict?
    """
    # print("Calling get_rand_good()")
    if goods_dict is None or not len(goods_dict):
        return None
    else:
        if nonzero and is_depleted(goods_dict):
            # we can't allocate what we don't have!
            print("Goods are depleted!")
            return None

        goods_list = list(goods_dict.keys())
        good = random.choice(goods_list)
        if nonzero:
            # pick again if the goods is endowed (amt is 0)
            # if we get big goods dicts, this could be slow:
            while goods_dict[good][AMT_AVAIL] == 0:
                good = random.choice(goods_list)
        return good 
Example 4
Project: simulated-annealing-tsp   Author: chncyhn   File: anneal.py    License: MIT License 6 votes vote down vote up
def initial_solution(self):
        """
        Greedy algorithm to get an initial solution (closest-neighbour).
        """
        cur_node = random.choice(self.nodes)  # start from a random node
        solution = [cur_node]

        free_nodes = set(self.nodes)
        free_nodes.remove(cur_node)
        while free_nodes:
            next_node = min(free_nodes, key=lambda x: self.dist(cur_node, x))  # nearest neighbour
            free_nodes.remove(next_node)
            solution.append(next_node)
            cur_node = next_node

        cur_fit = self.fitness(solution)
        if cur_fit < self.best_fitness:  # If best found so far, update best fitness
            self.best_fitness = cur_fit
            self.best_solution = solution
        self.fitness_list.append(cur_fit)
        return solution, cur_fit 
Example 5
Project: mutatest   Author: EvanKepner   File: run.py    License: MIT License 6 votes vote down vote up
def colorize_output(output: str, color: str) -> str:
    """Color output for the terminal display as either red or green.

    Args:
        output: string to colorize
        color: choice of terminal color, "red" vs. "green"

    Returns:
        colorized string, or original string for bad color choice.
    """
    colors = {
        "red": f"\033[91m{output}\033[0m",  # Red text
        "green": f"\033[92m{output}\033[0m",  # Green text
        "yellow": f"\033[93m{output}\033[0m",  # Yellow text
        "blue": f"\033[94m{output}\033[0m",  # Blue text
    }

    return colors.get(color, output) 
Example 6
Project: hydrus   Author: HTTP-APIs   File: test_app.py    License: MIT License 6 votes vote down vote up
def gen_dummy_object(class_title, doc):
    """Create a dummy object based on the definitions in the API Doc.
    :param class_title: Title of the class whose object is being created.
    :param doc: ApiDoc.
    :return: A dummy object of class `class_title`.
    """
    object_ = {
        "@type": class_title
    }
    for class_path in doc.parsed_classes:
        if class_title == doc.parsed_classes[class_path]["class"].title:
            for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or prop.write is False:
                    continue
                if "vocab:" in prop.prop:
                    prop_class = prop.prop.replace("vocab:", "")
                    object_[prop.title] = gen_dummy_object(prop_class, doc)
                else:
                    object_[prop.title] = ''.join(random.choice(
                        string.ascii_uppercase + string.digits) for _ in range(6))
            return object_ 
Example 7
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def gen_dummy_object(class_title, doc):
    """Create a dummy object based on the definitions in the API Doc.
    :param class_title: Title of the class whose object is being created.
    :param doc: ApiDoc.
    :return: A dummy object of class `class_title`.
    """
    object_ = {
        "@type": class_title
    }
    for class_path in doc.parsed_classes:
        if class_title == doc.parsed_classes[class_path]["class"].title:
            for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or prop.write is False:
                    continue
                if "vocab:" in prop.prop:
                    prop_class = prop.prop.replace("vocab:", "")
                    object_[prop.title] = gen_dummy_object(prop_class, doc)
                else:
                    object_[prop.title] = ''.join(random.choice(
                        string.ascii_uppercase + string.digits) for _ in range(6))
            return object_ 
Example 8
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def setUpClass(self):
        """Database setup before the CRUD tests."""
        print("Creating a temporary datatbsse...")
        engine = create_engine('sqlite:///:memory:')
        Base.metadata.create_all(engine)
        session = scoped_session(sessionmaker(bind=engine))
        self.API_NAME = "demoapi"
        self.HYDRUS_SERVER_URL = "http://hydrus.com/"
        self.session = session

        self.doc = doc_maker.create_doc(
            doc, self.HYDRUS_SERVER_URL, self.API_NAME)

        test_classes = doc_parse.get_classes(self.doc.generate())

        # Getting list of classes from APIDoc
        self.doc_collection_classes = [
            self.doc.collections[i]["collection"].class_.title for i in self.doc.collections]
        print(self.doc_collection_classes)
        print(random.choice(self.doc_collection_classes))
        test_properties = doc_parse.get_all_properties(test_classes)
        doc_parse.insert_classes(test_classes, self.session)
        doc_parse.insert_properties(test_properties, self.session)
        print("Classes and properties added successfully.")
        print("Setup done, running tests...") 
Example 9
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_delete(self):
        """Test CRUD delete."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        delete_response = crud.delete(
            id_=id_, type_=object_["@type"], session=self.session)
        assert isinstance(insert_response, str)
        response_code = None
        try:
            get_response = crud.get(
                id_=id_,
                type_=object_["@type"],
                session=self.session,
                api_name="api")
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code 
Example 10
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_delete_type(self):
        """Test CRUD delete when wrong/undefined class is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        assert isinstance(insert_response, str)
        assert insert_response == id_
        response_code = None
        try:
            delete_response = crud.delete(
                id_=id_, type_="otherClass", session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 400 == response_code 
Example 11
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_delete_id(self):
        """Test CRUD delete when wrong/undefined ID is given."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        insert_response = crud.insert(
            object_=object_, id_=id_, session=self.session)
        response_code = None
        try:
            delete_response = crud.delete(
                id_=999, type_=object_["@type"], session=self.session)
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code
        assert isinstance(insert_response, str)
        assert insert_response == id_ 
Example 12
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 6 votes vote down vote up
def test_delete_ids(self):
        objects = list()
        ids = "{},{}".format(str(uuid.uuid4()), str(uuid.uuid4()))
        for index in range(len(ids.split(','))):
            object = gen_dummy_object(random.choice(
                self.doc_collection_classes), self.doc)
            objects.append(object)
        insert_response = crud.insert_multiple(objects_=objects,
                                               session=self.session, id_=ids)
        delete_response = crud.delete_multiple(
            id_=ids, type_=objects[0]["@type"], session=self.session)

        response_code = None
        id_list = ids.split(',')
        try:
            for index in range(len(id_list)):
                get_response = crud.get(
                    id_=id_list[index],
                    type_=objects[index]["@type"],
                    session=self.session,
                    api_name="api")
        except Exception as e:
            error = e.get_HTTP()
            response_code = error.code
        assert 404 == response_code 
Example 13
Project: hydrus   Author: HTTP-APIs   File: test_cli.py    License: MIT License 6 votes vote down vote up
def gen_dummy_object(class_title, doc):
    """Create a dummy object based on the definitions in the API Doc.
    :param class_title: Title of the class whose object is being created.
    :param doc: ApiDoc.
    :return: A dummy object of class `class_title`.
    """
    object_ = {
        "@type": class_title
    }
    for class_path in doc.parsed_classes:
        if class_title == doc.parsed_classes[class_path]["class"].title:
            for prop in doc.parsed_classes[class_path]["class"].supportedProperty:
                if isinstance(prop.prop, HydraLink) or prop.write is False:
                    continue
                if "vocab:" in prop.prop:
                    prop_class = prop.prop.replace("vocab:", "")
                    object_[prop.title] = gen_dummy_object(prop_class, doc)
                else:
                    object_[prop.title] = ''.join(random.choice(
                        string.ascii_uppercase + string.digits) for _ in range(6))
            return object_ 
Example 14
Project: ALF   Author: blackberry   File: grammr2.py    License: Apache License 2.0 6 votes vote down vote up
def generate(self, gstate):
        if gstate.instances[self.ref]:
            gstate.output.append(random.choice(gstate.instances[self.ref]))
        else:
            pass # TODO, no instances yet, what now? generate one?
            # dharma generates content first, then reference definitions after (which must be created before the content)
            # this makes the testcases much cleaner ...  but how to work with the cracker?
            # IDEA:
            # we know which variables are tracked .. (ie references are possible, added to Grammar.tracked)
            # so whenever a tracked variable could occur, don't generate it, but keep track of where it could be
            # - if it's in a choice, set the weight to 0
            # - if it's somewhere else ?? error?
            # if a reference to the tracked variable is used, go back and generate the tracked variable in one of the preceding places
            # it could have occurred.
            #
            # simpler:
            # don't mess with the weights, but do keep track of the first place one could have occurred but didn't
            # if a reference is needed before one is actually generated, go back and generate it where it could have occurred.
            # - might be complicated (might violate repeat conditions, might need a reference before we find a place to generate the declaration)
            #
            # alternate: go dharma style and don't allow reference variables to be declared except when called for, then defined in a specific place
            # - how does this work with parsing? 
Example 15
Project: DDPAE-video-prediction   Author: jthsieh   File: moving_mnist.py    License: MIT License 6 votes vote down vote up
def __getitem__(self, idx):
    length = self.n_frames_input + self.n_frames_output
    if self.is_train or self.num_objects[0] != 2:
      # Sample number of objects
      num_digits = random.choice(self.num_objects)
      # Generate data on the fly
      images = self.generate_moving_mnist(num_digits)
    else:
      images = self.dataset[:, idx, ...]

    if self.transform is not None:
      images = self.transform(images)
    input = images[:self.n_frames_input]
    if self.n_frames_output > 0:
      output = images[self.n_frames_input:length]
    else:
      output = []

    return input, output 
Example 16
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: FireFlies.py    License: MIT License 6 votes vote down vote up
def step(self, amt=1):
        amt = 1  # anything other than 1 would be just plain silly
        if self._step > self.layout.numLEDs:
            self._step = 0

        self.layout.all_off()

        for i in range(self._count):
            pixel = random.randint(0, self.layout.numLEDs - 1)
            color = random.choice(self.palette)

            for i in range(self._width):
                if pixel + i < self.layout.numLEDs:
                    self.layout.set(pixel + i, color)

        self._step += amt 
Example 17
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: hyperspace.py    License: MIT License 6 votes vote down vote up
def step(self, amt=1):
        self.layout.all_off()

        for i in range(self._growthRate):
            newTail = random.randrange(0, 360, self._angleDiff)
            color = random.choice(self.palette)
            self._tails[newTail].append((0, color))

        for a in range(360):
            angle = self._tails[a]
            if len(angle) > 0:
                removals = []
                for r in range(len(angle)):
                    tail = angle[r]
                    if tail[0] <= self.lastRing:
                        self._drawTail(a, tail[0], tail[1])
                    if tail[0] - (self._tail - 1) <= self.lastRing:
                        tail = (tail[0] + amt, tail[1])
                        self._tails[a][r] = tail
                    else:
                        removals.append(tail)
                for r in removals:
                    self._tails[a].remove(r)

        self._step = 0 
Example 18
Project: gated-graph-transformer-network   Author: hexahedria   File: turing.py    License: MIT License 6 votes vote down vote up
def encode_turing_machine_rules(rules, starting_state=None, story=None):
    if story is None:
        story = graph_tools.Story()
    graph = story.graph
    if starting_state is None:
        starting_state = random.choice(len(rules))
    the_edges = [(cstate, read, write, nstate, direc)
                    for (cstate, stuff) in enumerate(rules)
                    for (read, (write, nstate, direc)) in enumerate(stuff)]
    random.shuffle(the_edges)
    for cstate, read, write, nstate, direc in the_edges:
        source = graph.make_unique('state_{}'.format(cstate))
        dest = graph.make_unique('state_{}'.format(nstate))
        edge_type = "rule_{}_{}_{}".format(read,write,direc)
        source[edge_type] = dest
        story.add_line("rule {} {} {} {} {}".format(source.type, read, write, dest.type, direc))
    head = graph.make_unique('head')

    head.state = graph.make_unique('state_{}'.format(starting_state))
    story.add_line("start {}".format(head.state.type))
    return story 
Example 19
Project: gated-graph-transformer-network   Author: hexahedria   File: ggtnn_train.py    License: MIT License 6 votes vote down vote up
def visualize(m, story_buckets, wordlist, answerlist, output_format, outputdir, batch_size=1, seq_len=5, debugmode=False, snap=False):
    cur_bucket = random.choice(story_buckets)
    sampled_batch = sample_batch(cur_bucket, batch_size, len(answerlist), output_format)
    part_sampled_batch = sampled_batch[:3]
    with open(os.path.join(outputdir,'stories.txt'),'w') as f:
        ggtnn_graph_parse.print_batch(part_sampled_batch, wordlist, answerlist, file=f)
    with open(os.path.join(outputdir,'answer_list.txt'),'w') as f:
        f.write('\n'.join(answerlist) + '\n')
    if debugmode:
        args = sampled_batch
        fn = m.debug_test_fn
    else:
        args = part_sampled_batch[:2] + ((seq_len,) if output_format == model.ModelOutputFormat.sequence else ())
        fn = m.snap_test_fn if snap else m.fuzzy_test_fn
    results = fn(*args)
    for i,result in enumerate(results):
        np.save(os.path.join(outputdir,'result_{}.npy'.format(i)), result) 
Example 20
Project: comport   Author: codeforamerica   File: JSON_test_client.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_disposition(self):
        return random.choice(
            ["Inactivated",
             "Informational Purpose On",
             "No Violation",
             "Not Sustained",
             "Not within Policy",
             "Partially Sustained",
             "Sustained",
             "Unfounded/Exonerated",
             "Unfounded/False",
             "Unfounded/Not Involved",
             "Unfounded/Unwarranted",
             "Withdrawn",
             "Within policy",
             None
             ]) 
Example 21
Project: indras_net   Author: gcallah   File: composite.py    License: GNU General Public License v3.0 5 votes vote down vote up
def rand_member(self):
        if len(self) > 0:
            # this is expensive: maybe we can speed it up
            # by not going to list somehow
            key = choice(list(self.members.keys()))
            return self[key]
        else:
            return None 
Example 22
Project: indras_net   Author: gcallah   File: agent_pop.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_randagent_of_var(self, var):
        return random.choice(self.vars[var]["agents"]) 
Example 23
Project: indras_net   Author: gcallah   File: grid_env.py    License: GNU General Public License v3.0 5 votes vote down vote up
def find_empty(self, grid_view=None):
        """
        Return a random, empty cell.
        """
        if self.exists_empty_cells():
            if grid_view is None:
                return random.choice(self.empties)
            else:
                view_empties = grid_view.get_empties()
                if view_empties:
                    return random.choice(view_empties)
        return None 
Example 24
Project: indras_net   Author: gcallah   File: obst.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_rand_direction():
    return random.choice(DIRECTIONS) 
Example 25
Project: jumpserver-python-sdk   Author: jumpserver   File: models.py    License: GNU General Public License v2.0 5 votes vote down vote up
def random_ssh_gateway(self):
        return random.choice([g for g in self.gateways if g.protocol == 'ssh']) 
Example 26
Project: vergeml   Author: mme   File: random_robot.py    License: MIT License 5 votes vote down vote up
def random_robot_name(moment_of_birth, dest=None):
    """Construct a random robot name.
    """
    random.seed(moment_of_birth)
    adj = random.choice(_ADJ)
    noun = random.choice(_NOUN)
    name = "{}-{}".format(adj, noun).lower()

    if dest and os.path.exists(os.path.join(dest, name)):
        return random_robot_name(datetime.now(), dest)

    return name 
Example 27
Project: vergeml   Author: mme   File: random_robot.py    License: MIT License 5 votes vote down vote up
def ascii_robot(moment_of_birth, name, include_phrase=True):
    """Generate random robot ascii art.
    """
    random.seed(moment_of_birth)

    def paste(cur, *lines):

        cur = list(cur)
        for line in lines:
            if len(line) > len(cur):
                cur += [' '] * (len(line) - len(cur))

            for i, char in enumerate(line):
                if char != " ":
                    cur[i] = char
        return "".join(cur)

    if random.choice([2, 3]) == 2:
        top = random.choice(ANTENNA)
        head = paste(random.choice(EYES), random.choice(EARS))
        body = paste("", random.choice(ARMS), random.choice(SIDES), random.choice(CENTER))
        bottom = random.choice(FEET)
    else:
        top = random.choice(ANTENNA_3)
        head = paste(random.choice(EYES_3), random.choice(EARS_3))
        if random.choice(["thin", "thick"]) == "thick":
            body = paste("", random.choice(ARMS_3_THICK),
                         random.choice(SIDES_3_THICK), random.choice(CENTER_3_THICK))
        else:
            body = paste("", random.choice(ARMS_3_THIN), random.choice(SIDES_3_THIN),
                         random.choice(CENTER_3_THIN))

        bottom = random.choice(FEET3)

    if include_phrase:
        phrase = random_phrase(name)
        bottom = paste(bottom, '            - {}'.format(phrase))

    return "\n".join(map(lambda part: "  " + part, [top, head, body, bottom])) 
Example 28
Project: vergeml   Author: mme   File: random_robot.py    License: MIT License 5 votes vote down vote up
def random_phrase(robot_name):
    """Construct a random phrase about robot_name.
    """
    phrase = random.choice(_PHRASES)
    parts = [random.choice(part) if isinstance(part, tuple) else part for part in phrase]
    res = " ".join(map(lambda x: x.strip(), parts))
    for char in (":", ".", "!", "?"):
        res = res.replace(" " + char, char)
    for char in ("'", '"'):
        res = res.replace(char + " ", char)

    res = res.replace("$name", "@" + robot_name)
    if res[-1] not in (".", "!", "?"):
        res += "."
    return res 
Example 29
Project: mlbv   Author: kmac   File: mlbsession.py    License: GNU General Public License v3.0 5 votes vote down vote up
def gen_random_string(n):
    return ''.join(
        random.choice(
            string.ascii_uppercase + string.digits
        ) for _ in range(n)
    ) 
Example 30
Project: hydrus   Author: HTTP-APIs   File: test_crud.py    License: MIT License 5 votes vote down vote up
def test_insert(self):
        """Test CRUD insert."""
        object_ = gen_dummy_object(random.choice(
            self.doc_collection_classes), self.doc)
        id_ = str(uuid.uuid4())
        response = crud.insert(object_=object_, id_=id_, session=self.session)

        assert isinstance(response, str)