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

Python random.randint函数代码示例

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

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



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

示例1: run

    def run(self):
        self.auge_machen()
        xbew = random.randint(-1,1)/1000
        ybew = random.randint(-1,1)/1000
        zaehler = 0

        while self.pos[2] > self.spielfeldpos[2]+2.5:
            rate(25)
            self.pos -= vector(0,0,1)
            self.rotate(angle=pi/4, axis=(0,1,0))
            self.rotate(angle=pi/4, axis=(0,0,1))
            self.rotate(angle=pi/4, axis=(1,0,0))
            self.pos[0] -= xbew*(zaehler^2)
            self.pos[1] -= ybew*(zaehler^2)
            zaehler    += 1

        augenzahl=2

        if augenzahl == 2:
            self.axis=(0,1,0)
            self.axis=(1,0,0)
            self.axis=(0,0,1)
            self.rotate(angle=pi/2, axis=(1,0,0))

        if augenzahl == 3:
            self.axis=(0,1,0)
            self.axis=(1,0,0)
            self.axis=(0,0,-1)
            
        if augenzahl == 4:
            self.axis=(0,1,0)
            self.axis=(1,0,0)
            self.axis=(0,0,1)
开发者ID:huegit,项目名称:q11,代码行数:33,代码来源:wuerfel2.py


示例2: enter

    def enter(self):
        print "You do a dive roll into the Weapon Armory, crouch and scan the room"
        print "for more Gothons that might be hiding. It's dead quiet, too quiet."
        print "You stand up and run to the far side of the room and find the"
        print "neutron bomb in its container. There's a keypad lock on the box"
        print "and you need the code to get the bomb out. If you get the code"
        print "wrong 10 times then the lock closes forever and you can't"
        print "get the bomb. The code is 3 digits."
        code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))

        print code

        guesses = 0

        while guesses < 10:
            guess = raw_input("[keypad]> ")
            if guess == code:
                break
            print "BZZZZEDDD!"
            guesses += 1

        if guess == code:
            print "The container clicks open and the seal breaks, letting gas out."
            print "You grab the neutron bomb and run as fast as you can to the"
            print "bridge where you must place it in the right spot."
            return 'the_bridge'
        else:
            print "The lock buzzes one last time and then you hear a sickening"
            print "melting sound as the mechanism is fused together."
            print "You decide to sit there, and finally the Gothons blow up the"
            print "ship from their ship and you die."
            return 'death'
开发者ID:VsevolodM95,项目名称:Python_training,代码行数:32,代码来源:tutorial_43.py


示例3: comp_attack

def comp_attack(computer):
	misses = []
	if computer.hits == []:
		while True:
			x = random.randint(0, 9)
			y = random.randint(0, 9)
			if (x, y) in computer.misses:
				continue
			elif (x, y) in computer.hits:
				continue
			else:
				return (x, y)
	else:
		while True:
			xy = random.choice(computer.hits)
			change = random.choice(((0, 1), (1, 0)))
			xy = update_coordinate(xy, change)
			if xy in computer.misses:
				misses.append(0)
			elif xy in computer.hits:
				misses.append(0)
			else:
				return xy
			if len(misses) >= 5:
				while True:
					x = random.randint(0, 9)
					y = random.randint(0, 9)
					if (x, y) in computer.misses:
						continue
					elif (x, y) in computer.hits:
						continue
					else:
						return (x, y)
开发者ID:rmotr-group-assignments,项目名称:pyp-c2-a1-b4-g3-t2,代码行数:33,代码来源:Battleship_Separate.py


示例4: loop

def loop():
    global CAT_POSITION, MICE
    MICE = [Mouse() for i in range(4)]

    while True:
        for e in pg.event.get():
            if e.type == pg.QUIT:
                pg.quit()
                sys.exit()

        # keyboard logic
        key_pressed = pg.key.get_pressed()
        if key_pressed[pg.K_q] == 1 or key_pressed[pg.K_ESCAPE] == 1:
            pg.event.post(pg.event.Event(pg.QUIT))

        if pg.mouse.get_focused():
            CAT_POSITION = set_cat_after_mouse()

        for mouse in MICE:
            if random.randint(0, 30) == 0:
                mouse.direction = random.randint(0, 3)
            mouse.run_away()

        if len(MICE) > 0 and len(MICE) <= 23 and random.randint(0, 50) == 0:
            new_mouse = Mouse()
            new_mouse.position = MICE[-1].position
            MICE.append(new_mouse)

        draw()
        clock.tick(24)
开发者ID:moggers87,项目名称:lazycat,代码行数:30,代码来源:__init__.py


示例5: main

def main():
    print("Code to look at runtime for insertion sort vs. Python's list sort.")
    
    numDig = 5 #number of digits to output
    
    #large list with numElements elements
    numElements = 10000
    data = []
    for i in range(numElements):
        data.append(randint(1, numElements))
        
    print("\nSorting list with " + str(len(data)) + " elements.\n")
    
    start = time.time()
    insertionSort(data)
    end = time.time()
    print("Insertion sort -> " + str(round(end - start, numDig)) + " seconds.")

    #large list with numElements elements
    numElements = 10000
    data = []
    for i in range(numElements):
        data.append(randint(1, numElements))
        
    start = time.time()
    data.sort()
    end = time.time()
    print("Python's sort -> " + str(round(end - start, numDig)) + " seconds.")
开发者ID:jedwardblack,项目名称:PythonPrograms,代码行数:28,代码来源:sortTest.py


示例6: growingtree

def growingtree(width, height, pad=1, choose=splitrandom, symmetric=False, startcentre=True):
    maze = initialclosed(width, height, pad)
    if startcentre:
        start = (width//2, height//2)
    else:
        start = (random.randint(0, width-1), random.randint(0, height-1))
    visited = {start}
    active = [start]
    while active:
        src = choose(active)
        dests = []
        # get unvisited neighbours
        for x, y in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            if src[0] + x < 0 or \
               src[0] + x >= width or \
               src[1] + y < 0 or \
               src[1] + y >= height:
                continue  # out of bounds
            if (src[0]+x, src[1]+y) not in visited:
                dests.append((src[0]+x, src[1]+y))
        if dests:  # if unvisited neighbours, pick one and create path to it
            dest = random.choice(dests)
            maze[src[1] + dest[1] + pad][src[0] + dest[0] + pad] = empty  # cool, hey?
            visited.add(dest)
            active.append(dest)
            if symmetric:
                src2 = (width - src[0] - 1, height - src[1] - 1)
                dest2 = (width - dest[0] - 1, height - dest[1] - 1)
                maze[src2[1] + dest2[1] + pad][src2[0] + dest2[0] + pad] = empty
                visited.add(dest2)
        else:  # if no more unvisited neighbours, remove from active
            active.remove(src)
    return maze
开发者ID:kierendavies,项目名称:umonyamaze,代码行数:33,代码来源:mazegen.py


示例7: populate

def populate(parent, howmany, max_children):
	to_add = howmany
	if howmany > max_children:
		children = randint(2, max_children)
		distribution = []
		for i in xrange(0, children - 1):
			distribution.append(int(howmany / children))
		distribution.append(howmany - sum(distribution, 0))
		for i in xrange(0, children):
			steal_target = randint(0, children - 1)
			while steal_target == i:
				steal_target = randint(0, children -1)
			steal_count = randint(-1 * distribution[i],
					distribution[steal_target]) / 2
			distribution[i] += steal_count
			distribution[steal_target] -= steal_count
		
		for i in xrange(0, children):
			make_dict = randint(0, 1)
			baby = None
			if make_dict:
				baby = {}
			else:
				baby = []
			populate(baby, distribution[i], max_children)
			if isinstance(parent, dict):
				parent[os.urandom(8).encode("hex")] = baby
			else:
				parent.append(baby)
	else:
		populate_with_leaves(parent, howmany)
开发者ID:AlexSnet,项目名称:oneline,代码行数:31,代码来源:test_random_tree.py


示例8: create_pinned_instance

    def create_pinned_instance(self, os_conn, cluster_id,
                               name, vcpus, hostname, meta):
        """Boot VM on specific compute with CPU pinning

        :param os_conn: an object of connection to openstack services
        :param cluster_id: an integer number of cluster id
        :param name: a string name of flavor and aggregate
        :param vcpus: an integer number of vcpus for flavor
        :param hostname: a string fqdn name of compute
        :param meta: a dict with metadata for aggregate
        :return:
        """
        aggregate_name = name + str(random.randint(0, 1000))
        aggregate = os_conn.create_aggregate(aggregate_name,
                                             metadata=meta,
                                             hosts=[hostname])

        extra_specs = {'aggregate_instance_extra_specs:pinned': 'true',
                       'hw:cpu_policy': 'dedicated'}

        net_name = self.fuel_web.get_cluster_predefined_networks_name(
            cluster_id)['private_net']
        flavor_id = random.randint(10, 10000)
        flavor = os_conn.create_flavor(name=name, ram=64, vcpus=vcpus, disk=1,
                                       flavorid=flavor_id,
                                       extra_specs=extra_specs)

        server = os_conn.create_server_for_migration(neutron=True,
                                                     label=net_name,
                                                     flavor=flavor_id)
        os_conn.verify_instance_status(server, 'ACTIVE')
        os_conn.delete_instance(server)
        os_conn.delete_flavor(flavor)
        os_conn.delete_aggregate(aggregate, hosts=[hostname])
开发者ID:mmalchuk,项目名称:openstack-fuel-qa,代码行数:34,代码来源:test_cpu_pinning.py


示例9: __init__

    def __init__(self):
        id_length = random.randint(config.min_id_length, config.max_id_length)
        self.id = utils.random_string(id_length)

        sex = random.choice(['male', 'female'])
        if sex == 'male':
            self.sex = 'M'
        else:
            self.sex = 'F'

        self.first_name = names.get_first_name(sex)
        self.last_name = names.get_last_name()
        self.middle_name = ''
        if config.gen_mid_name:
            if random.random() < config.gen_mid_name_chance:
                if random.randint(0, 1):
                    self.middle_name = names.get_first_name(sex)
                else:
                    self.middle_name = names.get_first_name(sex)[0]

        start = datetime.datetime(1900, 1, 1)
        end = datetime.datetime.now()
        self.birth_date = utils.random_date_between(start, end)

        self.aliases = []
        if config.gen_alias:
            for i in xrange(config.gen_alias_max):
                if random.random() < config.gen_alias_chance:
                    self.aliases.append(self.generate_alias())

        self.studies = self.generate_studies(self.birth_date)
开发者ID:IMAGE-ET,项目名称:dcmenvgen,代码行数:31,代码来源:hierarchy.py


示例10: buildMap

def buildMap(gridSize):
    cells = {}

    # generate a list of candidate coords for cells
    roomCoords = [(x, y) for x in range(gridSize) for y in range(gridSize)]
    random.shuffle(roomCoords)

    roomCount = min(10, int(gridSize * gridSize / 2))
    for i in range(roomCount):
        # search for candidate cell
        coord = roomCoords.pop()

        while not safeToPlace(cells, coord) and len(roomCoords) > 0:
            coord = roomCoords.pop()

        if not safeToPlace(cells, coord):
            break

        width = random.randint(3, CELL_SIZE)
        height = random.randint(3, CELL_SIZE)
        cells[coord] = Room(coord[0], coord[1], width, height)

    grid = Grid()
    grid.rooms = list(cells.values())

    # connect every room to one neighbor
    for coord in cells:
        room = cells[coord]
        room1 = findNearestNeighbor(cells, coord)

        if not grid.connected(room, room1):
            grid.corridors.append(Corridor(room, room1))

    return grid
开发者ID:forestbelton,项目名称:PyRogue,代码行数:34,代码来源:mapGen.py


示例11: capturerImmatr

	def capturerImmatr(self, Voiture):
		"""
		Return a random value to simulate the camera
		"""
		#string.letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
		#Voiture.immatriculation = str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + random.choice(string.ascii_uppercase) + random.choice(string.ascii_uppercase) + str(random.randint(0,9)) + str(random.randint(0,9)) #Voiture.immatriculation
		return str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + random.choice(string.ascii_uppercase) + random.choice(string.ascii_uppercase) + str(random.randint(0,9)) + str(random.randint(0,9))
开发者ID:homeboyno,项目名称:projet,代码行数:7,代码来源:Camera.py


示例12: upsert_df_data

def upsert_df_data(df):

    dwc_batch = []
    for ix, row in df.iterrows():

        if row.data_format == 'pct':
            rand_val = random()

        if row.data_format == 'bool':
            rand_val = randint(0,1)

        if row.data_format == 'int':
            rand_val = randint(0,1000)

        dwc_obj = DataPointComputed(**{
            'indicator_id':row.indicator_id,
            'campaign_id':row.campaign_id,
            'location_id':row.location_id,
            'cache_job_id':-1,
            'value':rand_val
        })

        dwc_batch.append(dwc_obj)

    DataPointComputed.objects.all().delete()
    DataPointComputed.objects.bulk_create(dwc_batch)
开发者ID:mepoole,项目名称:rhizome,代码行数:26,代码来源:0004_populate_fake_computed_data.py


示例13: breed

def breed(newChromes, chromes):
    for n in range(POPSIZE//2):
        r1 = randint(0, chrSize)
        newChromes[2*n] = chromes[0][:r1] + chromes[n+1][r1:]
        r2 = randint(0, chrSize)
        newChromes[2*n+1] = chromes[0][:r2] + chromes[n+1][r2:]
    return newChromes
开发者ID:changarno,项目名称:tjhsst1314,代码行数:7,代码来源:GA1.py


示例14: test4

def test4(count):
    print "*** test4 ***"

    lenx = 7
    leny = 21
    canvas = Canvas(lenx, leny)
    global strip
    strip = canvas.strip2D.strip
    strip.clear([40, 40, 40])

    while count > 0:
        strip.clear([0, 0, 0])
        x = random.randint(0, 6)
        y = random.randint(0, 20)
        cr = random.randint(0, 255)
        cg = random.randint(0, 255)
        cb = random.randint(0, 255)
        for r in range(4):
            canvas.circle(x, y, r, [cr, cg, cb])
            strip.artnet.send(canvas.strip2D.strip)
            time.sleep(1.0)
            count -= 1
        # canvas.strip2D.rotl();
        # strip.artnet.send(canvas.strip2D.strip);

    strip.artnet.close()
开发者ID:5nafu,项目名称:bitlair-ohm2013-ledstrip-contol,代码行数:26,代码来源:tests.py


示例15: _network_options

    def _network_options(self):

        network_options = []
        adapter_id = 0
        for adapter in self._ethernet_adapters:
            #TODO: let users specify a base mac address
            mac = "00:00:ab:%02x:%02x:%02d" % (random.randint(0x00, 0xff), random.randint(0x00, 0xff), adapter_id)
            if self._legacy_networking:
                network_options.extend(["-net", "nic,vlan={},macaddr={},model={}".format(adapter_id, mac, self._adapter_type)])
            else:
                network_options.extend(["-device", "{},mac={},netdev=gns3-{}".format(self._adapter_type, mac, adapter_id)])
            nio = adapter.get_nio(0)
            if nio and isinstance(nio, NIO_UDP):
                if self._legacy_networking:
                    network_options.extend(["-net", "udp,vlan={},sport={},dport={},daddr={}".format(adapter_id,
                                                                                                    nio.lport,
                                                                                                    nio.rport,
                                                                                                    nio.rhost)])

                else:
                    network_options.extend(["-netdev", "socket,id=gns3-{},udp={}:{},localaddr={}:{}".format(adapter_id,
                                                                                                            nio.rhost,
                                                                                                            nio.rport,
                                                                                                            self._host,
                                                                                                            nio.lport)])
            else:
                if self._legacy_networking:
                    network_options.extend(["-net", "user,vlan={}".format(adapter_id)])
                else:
                    network_options.extend(["-netdev", "user,id=gns3-{}".format(adapter_id)])
            adapter_id += 1

        return network_options
开发者ID:shmygov,项目名称:gns3-server,代码行数:33,代码来源:qemu_vm.py


示例16: joinclients

def joinclients(cod, channel, source):
    global slaves, nicks

    number = 1500

    for n in range(number):
        nick = gen_nick()
        while nick in nicks:
            nick = gen_nick()
        nicks.add(nick)
        user = "~lel~"
        host = "%s.%s.%s" %(prefix[randint(0, len(prefix) - 1)].upper(), prefix[randint(0, len(prefix) - 1)].upper(), suffix[randint(0, len(suffix) - 1)].upper())
        host = ".".join(host.split())
        uid = cod.getUID()
        if cod.protocol.gen_uid() is None:  # We are using a protocol that does not support uids
            uid = nick

        slave = makeClient(nick, user, host, "CareFriend", uid)
        slaves.append(slave)
        cod.burstClient(cod, slave)
        cod.join(channel, slave)

        cod.clients[slave.uid] = slave

    cod.notice(source, "%d clients joined to %s" % (number, channel))

    cod.servicesLog("OFC:CLIENTJOIN: %d clients to %s requested by %s" %
            (number, channel, source.nick))
开发者ID:joshtek0,项目名称:cod,代码行数:28,代码来源:ofc.py


示例17: testInsertRandomRemoveRandom

    def testInsertRandomRemoveRandom(self):
        tree = avltree.AVLTree()

        LEN=200

        values = range(LEN)
        inserted = []
        for i in range(LEN-1, -1, -1):
            v = values.pop(random.randint(0, i))
            inserted.append(v)
            tree.insert(v)
            try:
                self.assertOrdered(tree.tree, -1, LEN-i)
                self.assertBalanced(tree.tree)
            except:
                print 'insertion order:', inserted
                raise

        values = range(LEN)
        for i in range(LEN-1, -1, -1):
            v = values.pop(random.randint(0, i))
            savetree = tree.tree
            tree.delete(v)
            try:
                self.assertOrdered(tree.tree, values and values[0]-1 or -1, i)
                self.assertBalanced(tree.tree)
            except:
                print 'while deleting:', v, 'from:', savetree
                avltree.debug(savetree)
                raise
开发者ID:offlinehacker,项目名称:flumotion,代码行数:30,代码来源:test_common_avltree.py


示例18: updateLocation

 def updateLocation(self):
     '''随机更新怪物的位置'''
     
     position = self.baseInfo.getStaticPosition()
     x = position[0]+random.randint(-100,100)
     y = position[1]+random.randint(-100,100)
     self.baseInfo.setPosition((x,y))
开发者ID:9miao,项目名称:firefly_fengyan_OL,代码行数:7,代码来源:Monster.py


示例19: test_get_pagination_qs

 def test_get_pagination_qs(self):
     clt = self.client
     mgr = clt._manager
     test_limit = random.randint(1, 100)
     test_offset = random.randint(1, 100)
     qs = mgr._get_pagination_qs(test_limit, test_offset)
     self.assertEqual(qs, "?limit=%s&offset=%s" % (test_limit, test_offset))
开发者ID:absoludity,项目名称:pyrax,代码行数:7,代码来源:test_cloud_dns.py


示例20: shipeventattpir

 def shipeventattpir(self, a_ship, a_screen):
     ranloss = random.randint(0, 5)
     a_ship.ShipHp -= ranloss
     a_ship.CrewHp -= int(math.ceil(.75 * ranloss))
     self.mess = "You attacked the other pirate, Violence is the language of the sea."
     self.mess += "Unfortunately, there is often a price to pay to speak it"
     self.mess += "You've overpowered the other pirate, showing your dominance, what would you do "
     self.mess += "with whats left of his crew?"
     messobj = StrObj.render(self.mess[0:39], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 5))
     messobj = StrObj.render(self.mess[40:67], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 25))
     messobj = StrObj.render(self.mess[67:104], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 45))
     messobj = StrObj.render(self.mess[105:123], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 65))
     messobj = StrObj.render(self.mess[123:151], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 85))
     messobj = StrObj.render(self.mess[152:183], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 105))
     messobj = StrObj.render(self.mess[184:212], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 125))
     messobj = StrObj.render(self.mess[213:235], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 145))
     redunum = random.randint(0, 5)
     a_ship.CrewHp -= redunum
     a_ship.Resources.Ammunition -= 2
     self.MenuOp.initafterattnonnav(200)
     self.MenuOp.drawmen(a_screen, 0)
开发者ID:mliming,项目名称:Tide-Glory,代码行数:29,代码来源:MyEvents.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python random.random函数代码示例发布时间:2022-05-26
下一篇:
Python random.randchoice函数代码示例发布时间: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