当前位置: 首页>>代码示例>>Python>>正文


Python random.choice方法代码示例

本文整理汇总了Python中random.choice方法的典型用法代码示例。如果您正苦于以下问题:Python random.choice方法的具体用法?Python random.choice怎么用?Python random.choice使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在random的用法示例。


在下文中一共展示了random.choice方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_prod_goods

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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)) 
开发者ID:gcallah,项目名称:indras_net,代码行数:21,代码来源:menger_model.py

示例2: discourage

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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 
开发者ID:gcallah,项目名称:indras_net,代码行数:24,代码来源:el_farol.py

示例3: get_rand_good

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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 
开发者ID:gcallah,项目名称:indras_net,代码行数:23,代码来源:trade_utils.py

示例4: initial_solution

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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 
开发者ID:chncyhn,项目名称:simulated-annealing-tsp,代码行数:23,代码来源:anneal.py

示例5: colorize_output

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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) 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:20,代码来源:run.py

示例6: gen_dummy_object

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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_ 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:23,代码来源:test_app.py

示例7: setUpClass

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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...") 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:27,代码来源:test_crud.py

示例8: test_delete

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:23,代码来源:test_crud.py

示例9: test_delete_type

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:19,代码来源:test_crud.py

示例10: test_delete_id

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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_ 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:19,代码来源:test_crud.py

示例11: test_delete_ids

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:27,代码来源:test_crud.py

示例12: generate

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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? 
开发者ID:blackberry,项目名称:ALF,代码行数:24,代码来源:grammr2.py

示例13: __getitem__

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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 
开发者ID:jthsieh,项目名称:DDPAE-video-prediction,代码行数:21,代码来源:moving_mnist.py

示例14: step

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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 
开发者ID:ManiacalLabs,项目名称:BiblioPixelAnimations,代码行数:18,代码来源:FireFlies.py

示例15: step

# 需要导入模块: import random [as 别名]
# 或者: from random import choice [as 别名]
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 
开发者ID:ManiacalLabs,项目名称:BiblioPixelAnimations,代码行数:27,代码来源:hyperspace.py


注:本文中的random.choice方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。