• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python random.rand_choice函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: __init__

    def __init__(self, position_x, position_y, data_set = {}, 
                previous_nodes = []):
        """ The initializator of CartesianNode representation,
        position_x and position_y must be specified, data_set and previous_nodes
        depends on type of the node """
        self.data = None
        self.inputs = []
        self.params = {}
        self.x = position_x
        self.y = position_y

        try:
            self.data = rand_choice(data_set.keys())
        except IndexError:
            self.data = ""

        try:
            inputs_count = data_set[self.data]-1
        except KeyError:
            inputs_count = 1

        if (len(previous_nodes) == 0 and inputs_count > 0):
            raise ValueError("Bad data set and previous nodes values " 
                            "combination. If specified data set with input args"
                            " then previous nodes can not be empty!")
            
        for i in range(0, inputs_count):
            self.inputs.append(rand_choice(previous_nodes))            
            
        for param in CartesianNode.paramMapping.keys():
            self.params[param] = eval(CartesianNode.paramMapping[param])
开发者ID:ImpactHorizon,项目名称:Pyevolve,代码行数:31,代码来源:G2DCartesian.py


示例2: choose_attack

 def choose_attack(self):
     rand_row = rand_choice(row_range)
     rand_col = rand_choice(col_range)
     if self.enemy_board.cell_empty(rand_row, rand_col):
         return (rand_row, rand_col)
     else:
         return self.choose_attack()
开发者ID:rmotr-group-assignments,项目名称:pyp-c2-a1-b4-g3-t1,代码行数:7,代码来源:player.py


示例3: G1DListCrossoverEdge

def G1DListCrossoverEdge(genome, **args):
   """ THe Edge Recombination crossover for G1DList (widely used for TSP problem)

   See more information in the `Edge Recombination Operator <http://en.wikipedia.org/wiki/Edge_recombination_operator>`_
   Wikipedia entry.
   """
   gMom, sisterl  = args["mom"], []
   gDad, brotherl = args["dad"], []

   mom_edges, dad_edges, merge_edges = Util.G1DListGetEdgesComposite(gMom, gDad)

   for c, u in (sisterl, set(gMom)), (brotherl, set(gDad)):
      curr = None
      for i in xrange(len(gMom)):
         curr = rand_choice(tuple(u)) if not curr else curr         
         c.append(curr)
         u.remove(curr)
         d = [v for v in merge_edges.get(curr, []) if v in u]
         if d: curr = rand_choice(d)
         else:
            s  = [v for v in mom_edges.get(curr, []) if v in u]
            s += [v for v in dad_edges.get(curr, []) if v in u]
            curr = rand_choice(s) if s else None

   sister = gMom.clone()
   brother = gDad.clone()
   sister.resetStats()
   brother.resetStats()

   sister.genomeList  = sisterl
   brother.genomeList = brotherl

   return (sister, brother)
开发者ID:DamionKing,项目名称:Pyevolve,代码行数:33,代码来源:Crossovers.py


示例4: GTreeGPMutatorOperation

def GTreeGPMutatorOperation(genome, **args):
   """ The mutator of GTreeGP, Operation Mutator

   .. versionadded:: 0.6
      The *GTreeGPMutatorOperation* function
   """

   if args["pmut"] <= 0.0:
      return 0
   elements = len(genome)
   mutations = args["pmut"] * elements
   ga_engine = args["ga_engine"]

   gp_terminals = ga_engine.getParam("gp_terminals")
   assert gp_terminals is not None

   gp_function_set = ga_engine.getParam("gp_function_set")
   assert gp_function_set is not None

   if mutations < 1.0:
      mutations = 0
      for i in xrange(len(genome)):
         if Util.randomFlipCoin(args["pmut"]):
            mutations += 1
            rand_node = genome.getRandomNode()
            assert rand_node is not None
            if rand_node.getType() == Consts.nodeType["TERMINAL"]:
               term_operator = rand_choice(gp_terminals)
            else:
               op_len = gp_function_set[rand_node.getData()]
               fun_candidates = []
               for o, l in gp_function_set.items():
                  if l == op_len:
                     fun_candidates.append(o)

               if len(fun_candidates) <= 0:
                  continue

               term_operator = rand_choice(fun_candidates)
            rand_node.setData(term_operator)
   else:
      for it in xrange(int(round(mutations))):
         rand_node = genome.getRandomNode()
         assert rand_node is not None
         if rand_node.getType() == Consts.nodeType["TERMINAL"]:
            term_operator = rand_choice(gp_terminals)
         else:
            op_len = gp_function_set[rand_node.getData()]
            fun_candidates = []
            for o, l in gp_function_set.items():
               if l == op_len:
                  fun_candidates.append(o)

            if len(fun_candidates) <= 0:
               continue

            term_operator = rand_choice(fun_candidates)
         rand_node.setData(term_operator)

   return int(mutations)
开发者ID:MaximilianoRios,项目名称:Pyevolve,代码行数:60,代码来源:Mutators.py


示例5: GTreeCrossoverSinglePoint

def GTreeCrossoverSinglePoint(genome, **args):
   """ The crossover for GTree, Single Point """
   sister = None
   brother = None
   gMom = args["mom"].clone()
   gDad = args["dad"].clone()

   gMom.resetStats()
   gDad.resetStats()

   node_mom_stack = []
   all_mom_nodes  = []
   node_mom_tmp   = None

   node_dad_stack = []
   all_dad_nodes  = []
   node_dad_tmp   = None

   node_mom_stack.append(gMom.getRoot())
   node_dad_stack.append(gDad.getRoot())

   while (len(node_mom_stack) > 0) and  (len(node_dad_stack) > 0):
      node_mom_tmp = node_mom_stack.pop()
      node_dad_tmp = node_dad_stack.pop()

      if node_mom_tmp != gMom.getRoot():
         all_mom_nodes.append(node_mom_tmp)
         all_dad_nodes.append(node_dad_tmp)

      node_mom_stack.extend(node_mom_tmp.getChilds())
      node_dad_stack.extend(node_dad_tmp.getChilds())

   if len(all_mom_nodes)==0 or len(all_dad_nodes)==0:
      return (gMom, gDad)

   if len(all_dad_nodes) == 1: nodeDad = all_dad_nodes[0]
   else: nodeDad = rand_choice(all_dad_nodes)

   if len(all_mom_nodes) == 1: nodeMom = all_mom_nodes[0]
   else: nodeMom = rand_choice(all_mom_nodes)

   nodeMom_parent = nodeMom.getParent()
   nodeDad_parent = nodeDad.getParent()

   # Sister
   if args["count"] >= 1:
      sister = gMom
      nodeDad.setParent(nodeMom_parent)
      nodeMom_parent.replaceChild(nodeMom, nodeDad)
      sister.processNodes()

   # Brother
   if args["count"] == 2:
      brother = gDad
      nodeMom.setParent(nodeDad_parent)
      nodeDad_parent.replaceChild(nodeDad, nodeMom)
      brother.processNodes()

   return (sister, brother)
开发者ID:DamionKing,项目名称:Pyevolve,代码行数:59,代码来源:Crossovers.py


示例6: build_board

 def build_board(self):
     boat_list = [Submarine, Aircraft, PatrolBoat, PatrolBoat]
     while len(boat_list) != 0:
         rand_pos = (rand_choice(row_range), rand_choice(col_range))
         horizontal = randint(0, 1) == 0
         ship = boat_list[-1](rand_pos, horizontal)
         if ship.can_place(self.my_board):
             ship.place(self.my_board)
             boat_list.pop()
开发者ID:rmotr-group-assignments,项目名称:pyp-c2-a1-b4-g3-t1,代码行数:9,代码来源:player.py


示例7: mutate_code

def mutate_code(code):
    v = randint(0, 2 if len(code) > 0 else 0)
    pos = randint(0, len(code))
    if v == 0:
        # insert symbol
        return code[:pos] + rand_choice(COMMANDS) + code[pos:]
    elif v == 1:
        # replace symbol
        return code[:pos] + rand_choice(COMMANDS) + code[pos + 1 :]
    else:
        # remove symbol
        return code[:pos] + code[pos + 1 :]
开发者ID:neumond,项目名称:natural-selection,代码行数:12,代码来源:world.py


示例8: init_func

def init_func(genome, **args):
   the_set = []
   set_size = randrange(1,MAX_SET_SIZE+1)
   for i in xrange(set_size):
      rule = [rand_choice(('0','1')) for j in xrange(RULE_SIZE)]
      the_set = the_set + rule
   genome.genomeList = the_set
开发者ID:LuisMiranda132,项目名称:FightSimulator,代码行数:7,代码来源:gabil.py


示例9: exchange

    def exchange(self):
        """ This is the main method, is where the individuals
        are exchanged """

        if not self.isReady():
            return

        pool_to_send = self.selectPool(self.getNumIndividuals())
        pool_received  = self.comm.sendrecv(sendobj=pool_to_send,
                                            dest=self.dest,
                                            sendtag=0,
                                            recvobj=None,
                                            source=self.source,
                                            recvtag=0)

        population = self.GAEngine.getPopulation()

        pool = pool_received
        for i in xrange(self.getNumReplacement()):
            if len(pool) <= 0:
                break
            choice = rand_choice(pool)
            pool.remove(choice)

            # replace the worst
            population[len(population)-1-i] = choice

        self.gather_bests()
开发者ID:lorenzoriano,项目名称:Pyevolve,代码行数:28,代码来源:MpiMigration.py


示例10: exchange

    def exchange(self):
        if not self.isReady():
            return

        pool_to_send = self.selectPool(self.getNumIndividuals())

        for genome in pool_to_send:
            self.beforeSerialization(genome)

        pool_received = self.comm.sendrecv(sendobj=pool_to_send,
                                            dest=self.dest,
                                            sendtag=0,
                                            recvobj=None,
                                            source=self.source,
                                            recvtag=0)
        for genome in pool_to_send:
            self.afterSerialization(genome)

        for genome in pool_received:
            self.afterSerialization(genome)

        population = self.GAEngine.getPopulation()

        pool = pool_received
        for i in xrange(self.getNumReplacement()):
            if len(pool) <= 0:
                break

            choice = rand_choice(pool)
            pool.remove(choice)

            # replace the worst
            population[len(population) - 1 - i] = choice

        self.gather_bests()
开发者ID:marcinlos,项目名称:data-replication,代码行数:35,代码来源:island.py


示例11: send_testing_msg

 async def send_testing_msg(self, ctx, bot=False, msg=None):
     server = ctx.message.server
     channel = self.get_welcome_channel(server)
     rand_msg = msg or rand_choice(self.settings[server.id]["GREETING"])
     if channel is None:
         await self.bot.send_message(ctx.message.channel,
                                     "I can't find the specified channel. "
                                     "It might have been deleted.")
         return
     await self.bot.send_message(ctx.message.channel,
                                 "`Sending a testing message to "
                                 "`{0.mention}".format(channel))
     if self.speak_permissions(server):
         msg = self.settings[server.id]["BOTS_MSG"] if bot else rand_msg
         if not bot and self.settings[server.id]["WHISPER"]:
             await self.bot.send_message(ctx.message.author,
                     msg.format(ctx.message.author,server))
         if bot or self.settings[server.id]["WHISPER"] is not True:
             await self.bot.send_message(channel,
                     msg.format(ctx.message.author, server))
     else:
         await self.bot.send_message(ctx.message.channel,
                                     "I do not have permissions "
                                     "to send messages to "
                                     "{0.mention}".format(channel))
开发者ID:irdumbs,项目名称:Dumb-Cogs,代码行数:25,代码来源:welcome.py


示例12: main

def main():
    intervals = {'major 2nd': 2,
                 'minor 3rd': 3, 'major 3rd': 4,
                 'perfect 4th': 5,
                 'perfect 5th': 7}
    interval_lookup = {}
    for key, val in intervals.copy().iteritems():
        # We don't want to modify the dict we're iterating though
        interval_lookup[val] = key  # Add the reverse to the dict

    used_tones = [False] * 12
    notes = len(Note.chromatic)
    tune = []

    def prev_interval():
        """Return the most recent interval"""
        previous_interval = (tune[-2] - tune[-1]) % notes
        # interval might not be in intervals
        if previous_interval in interval_lookup:
            previous_interval = interval_lookup[previous_interval]
        return previous_interval

    def get_new_note(pitch, interval=None):
        """This is embedded so we don't need to pass in used_tones.
        Checks that the note is valid otherwise it picks a new note and sets it
        as used"""
        if interval is not None:
            pitch = (pitch + interval) % len(Note.chromatic)
        if used_tones[pitch] is True and False in used_tones:
            pitch = rand_choice([i for i, used in enumerate(used_tones)
                                 if used is False])
        used_tones[pitch] = True
        return pitch


    tune.append(get_new_note(randint(0, notes - 1)))
    tune.append(get_new_note(tune[-1], rand_choice(intervals.values())))

    while False in used_tones:
        # intelligently choose a new pitch based on the interval between the
        # previous two
        note = get_new_note(randint(0, notes - 1))
        if randint(1, 4) > 1:  # 1 in 4 chance for a random note
            if prev_interval() == 'major 3rd':
                # if the previous interval was a minor 3rd, attempt to follow
                # it with a major 2nd
                # mod is used to stay in the octave
                note = get_new_note(tune[-1], intervals['major 2nd'])
            elif prev_interval == 'perfect 4th':
                # if the previous interval was a major 3rd, attempt to follow
                # by going down a minor 3rd
                note = get_new_note(tune[-1], -1* intervals['major 3rd'])

        tune.append(note)

    mixer.pre_init(44100, -16, 1, 1024)
    pygame.init()
    play_tune([Note.chromatic[note] for note in tune])
    pygame.quit()
开发者ID:solarmist,项目名称:python-learning-experiments,代码行数:59,代码来源:tonerow.py


示例13: GD1BinaryStringSetInitializator

def GD1BinaryStringSetInitializator(genome,**args):
   """ 1D Binary String initializator """
   initial_ruleset_len = 2 #number of rules by default
   for i in range(0,initial_ruleset_len):
   		#create random rule of fixed length
   		rule = [ rand_choice((0,1)) for j in xrange(genome.rule_length) ]
   		rule = ''.join(map(str,rule))
   		genome.addRuleAsString(rule)
开发者ID:andresoSw,项目名称:gabil-ga,代码行数:8,代码来源:BinarystringSet.py


示例14: init

def init(genome, **args):
	_set = []
	size = randrange(1,SET_SIZE +1)
	for i in xrange(size):
		rule = [ rand_choice(('0','1')) for j in xrange(RULE_SIZE)]
		_set = _set + rule
	genome.genomeString = _set
	genome.stringLength = len(_set)
开发者ID:julianaleon8,项目名称:IA2_2014,代码行数:8,代码来源:gabil.py


示例15: getRandomNode

   def getRandomNode(self, node_type=0):
      """ Returns a random node from the Tree

      :param node_type: 0 = Any, 1 = Leaf, 2 = Branch
      :rtype: random node
      """
      lists = (self.nodes_list, self.nodes_leaf, self.nodes_branch)
      cho = lists[node_type]
      if len(cho) <= 0:
         return None
      return rand_choice(cho)
开发者ID:neutrons,项目名称:CrystalPlan,代码行数:11,代码来源:GenomeBase.py


示例16: get_new_note

 def get_new_note(pitch, interval=None):
     """This is embedded so we don't need to pass in used_tones.
     Checks that the note is valid otherwise it picks a new note and sets it
     as used"""
     if interval is not None:
         pitch = (pitch + interval) % len(Note.chromatic)
     if used_tones[pitch] is True and False in used_tones:
         pitch = rand_choice([i for i, used in enumerate(used_tones)
                              if used is False])
     used_tones[pitch] = True
     return pitch
开发者ID:solarmist,项目名称:python-learning-experiments,代码行数:11,代码来源:tonerow.py


示例17: G2DBinaryStringInitializator

def G2DBinaryStringInitializator(genome, **args):
   """ Integer initialization function of 2D Binary String
   
   .. versionadded:: 0.6
      The *G2DBinaryStringInitializator* function
   """
   genome.clearString()
   
   for i in xrange(genome.getHeight()):
      for j in xrange(genome.getWidth()):
         random_gene = rand_choice((0,1))
         genome.setItem(i, j, random_gene)
开发者ID:DamionKing,项目名称:Pyevolve,代码行数:12,代码来源:Initializators.py


示例18: applyFunctions

   def applyFunctions(self, obj, **args):
      """ Generator to apply all function slots in obj

      :param obj: this object is passes as parameter to the function
      :param args: this args dictionary is passed to the function   

      """
      if len(self.funcList) <= 0:
         raise Exception("No function defined: " + self.slotName)
      if not self.rand_apply:
         for f in self.funcList:
            yield f(obj, **args)
      else:
         yield rand_choice(self.funcList)(obj, **args)
开发者ID:abrahamdone,项目名称:cs5600ai,代码行数:14,代码来源:FunctionSlot.py


示例19: create_random_form

 def create_random_form(self):
     code = ""
     for i in range(randint(4, 15)):
         code += rand_choice(COMMANDS)
     tries = 5
     while tries > 0:
         x = randint(0, WORLD_SIZE - 1)
         y = randint(0, WORLD_SIZE - 1)
         if self.worldmap[(x, y)] is None:
             form = LifeForm(self, code, x, y)
             self.lifeforms.append(form)
             self.worldmap[(x, y)] = form
             break
         tries -= 1
开发者ID:neumond,项目名称:natural-selection,代码行数:14,代码来源:world.py


示例20: random_place

def random_place(request):
    """
    If a random place is in the cache, use it and return that to the user.
    If not, generate one right now.
    
    Before returning to the user, queue up a background task that generates
    the next random place, to save DB/CPU usage when responding to user. (Prevents
    this view from locking up while Django picks a suitable random object.)
    """
    response = None
    while not response:
        try:
            PlaceClass = rand_choice([State,County])
            
            # Cached list of all of the ID numbers for this place type.
            cache_key = "all_ids: %s" % (PlaceClass.__name__)
            all_ids = safe_get_cache(cache_key)
            if not all_ids:
                all_ids = PlaceClass.objects.only('id').order_by().values_list('pk') # [(0,),(1,),...]
                all_ids = map(lambda x: x[0], all_ids) # pull ID out of tuples for a "regular" list
                safe_set_cache(cache_key,all_ids,604800)
            
            rand_id = rand_choice(all_ids)
            
            if PlaceClass.__name__ == "County":
                place = PlaceClass.objects.get(pk=rand_id)
                url = reverse("places:county_detail",args=(place.state.abbr.lower(),urlencode(place.name.lower())),current_app="places")
            else:
                place = PlaceClass.objects.only('slug').get(pk=rand_id)
                url = reverse("places:state_detail",args=(place.slug,),current_app="places")
            response = HttpResponseRedirect(url)
        except:
            from traceback import print_exc
            print_exc()
            response = None
    return response
开发者ID:mtigas,项目名称:cs4970_capstone,代码行数:36,代码来源:views.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python random.rand_gauss函数代码示例发布时间:2022-05-26
下一篇:
Python random.rand函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap