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


Python random.rand_choice函数代码示例

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


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


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