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


Python random.randrange函数代码示例

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


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

示例1: draw

def draw(cmds, size=2): #output tree
    stack = []
    for cmd in cmds:
        if cmd=='F':
            turtle.forward(size)
        elif cmd=='-':
            t = random.randrange(0,7,1)
            p = ["Red","Green","Blue","Grey","Yellow","Pink","Brown"]
            turtle.color(p[t])
            turtle.left(15) #slope left
        elif cmd=='+':
            turtle.right(15) #slope right
            t = random.randrange(0,7,1) #рандомная пер. для цвета
            p = ["Red","Green","Blue","Grey","Yellow","Pink","Brown"] #ряд цветов
            turtle.color(p[t]) #выбор цвета из ряда
        elif cmd=='X':
            pass
        elif cmd=='[':
            stack.append((turtle.position(), turtle.heading()))
        elif cmd==']':
            position, heading = stack.pop()
            turtle.penup()
            turtle.setposition(position)
            turtle.setheading(heading)  
            turtle.pendown()
    turtle.update()
开发者ID:Papapashu,项目名称:main,代码行数:26,代码来源:python_three.py

示例2: fightClowns

def fightClowns(clowns):
    global life
    global hit

    if clowns != 0:
        print(str(clowns) + " clowns stagger towards you. Ready your " + str.lower(myWeapons[0]) + "!\n")
        attack = raw_input("Attack, or Run? (A for attack, R for run)\n")
        if (str.upper(attack) == "A"):
            print(str(clowns) + " clowns attacked you!")
            life = life - clownattack*clowns
            hit = (hitMultiplier[random.randrange(0, len(hitMultiplier))]*weapon[myWeapons[0]])
            if hit != 0:
                print("You successfully killed them!")
                print("Your life is now: " + str(life))
            if (hit == 0):
                print("That was a lucky miss. Next time you should attack! (You successfully runned)")
                return 0
        elif str.upper(attack) == "R":
              stumblee = random.randrange(0, 2)
              stumble = random.randrange(1, 7)
              if stumblee > 0:
                  print("Run away from the zombies, you have stumbled and lost " + str(stumble) + " hp")
                  life = life - stumble
              else:
                  print("Nothing was happened.")
    elif clowns == 0:
         print ("But Nobody Came!")
    else:
        hit = (hitMultiplier[random.randrange(0, len(hitMultiplier))]*weapon[myWeapons[0]])
        if hit > 0:
            life = life - clownattack
        print (str(clowns) + " attack you, but you killed them\n" "Life health is now " + str(life))
开发者ID:Yuliafag,项目名称:ss-13,代码行数:32,代码来源:ss13.py

示例3: generate_picture

    def generate_picture(self, file_name="image.png"):
        size = list(self.destination.size)
        if size[0] > 700:
            aspect = size[1] / float(size[0])
            size[0] = 600
            size[1] = int(600 * aspect)
            self.destination = self.destination.resize(
                    size, Image.BILINEAR).convert('RGB')

        # fit the pallet to the destination image
        self.palette = self.palette.resize(size, Image.NEAREST).convert('RGB')
        self.destination.paste(self.palette, (0, 0))

        # randomly switch two pixels if they bring us closer to the image
        for i in xrange(500000):
            first = (random.randrange(0, self.destination.size[0]),
                     random.randrange(0, self.destination.size[1]))
            second = (random.randrange(0, self.destination.size[0]),
                      random.randrange(0, self.destination.size[1]))

            original_first = self.original.getpixel(first)
            original_second = self.original.getpixel(second)

            dest_first = self.destination.getpixel(first)
            dest_second = self.destination.getpixel(second)

            if color_diff(original_first, dest_first) + \
                    color_diff(original_second, dest_second) > \
                    color_diff(original_first, dest_second) + \
                    color_diff(original_second, dest_first):
                self.destination.putpixel(first, dest_second)
                self.destination.putpixel(second, dest_first)

        self.destination.save(file_name)
        return file_name
开发者ID:SpokenBanana,项目名称:PicturePalet,代码行数:35,代码来源:picture_pallet.py

示例4: run_command

def run_command(command, info):
    if settings.WORKERS_USE_TOR:
        # Initialize and use tor proxy
        socks_port = random.randrange(50000, 60000)
        control_port = random.randrange(50000, 60000)
        directory = '/tmp/%s' % uuid.uuid1()
        os.makedirs(directory)

        # Port collision? Don't worry about that.
        tor_command = "tor --SOCKSPort %s --ControlPort %s --DataDirectory %s" % (socks_port, control_port, directory)
        print "Executing tor command: %s" % tor_command
        tor_command = shlex.split(tor_command)
        proc = subprocess.Popen(tor_command, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        while proc.poll() is None:
            output = proc.stdout.readline()
            if 'Bootstrapped 100%: Done.' in output:
                print 'We have a working connection!'
                break

        command += ' --proxy="127.0.0.1:%s" --proxy-type="socks5"' % socks_port

    j = Job(run_command.request.id, info)
    result = j.run(command)
    j.finish(result)

    if settings.WORKERS_USE_TOR:
        proc.kill()
        shutil.rmtree(directory)
开发者ID:nickhs,项目名称:hermes,代码行数:29,代码来源:runner.py

示例5: test_random_addition_and_slicing

def test_random_addition_and_slicing():
    seed = random.randrange(10000)
    print seed
    random.seed(seed)
    st = "abc"
    curr = LiteralStringNode(st)
    last = None
    all = []
    for i in range(1000):
        a = (chr(random.randrange(ord('a'), ord('z') + 1)) *
                random.randrange(500))
        last = curr
        all.append(curr)
        c = random.choice([0, 1, 2])
        if c == 0:
            curr = curr + LiteralStringNode(a)
            st = st + a
        elif c == 1:
            curr = LiteralStringNode(a) + curr
            st = a + st
        else:
            if len(st) < 10:
                continue
            # get a significant portion of the string
            #import pdb; pdb.set_trace()
            start = random.randrange(len(st) // 3)
            stop = random.randrange(len(st) // 3 * 2, len(st))
            curr = getslice_one(curr, start, stop)
            st = st[start: stop]
        assert curr.flatten_string() == st
    curr = curr.rebalance()
    assert curr.flatten_string() == st
开发者ID:Darriall,项目名称:pypy,代码行数:32,代码来源:test_rope.py

示例6: specialQuestion

def specialQuestion(oldq):
	newq = [oldq[0], oldq[1]]
	qtype = oldq[0].upper()

	if qtype == "!MONTH":
		newq[0] = "What month is it currently (in UTC)?"
		newq[1] = time.strftime("%B", time.gmtime()).lower()
	elif qtype == "!MATH+":
		try:
			maxnum = int(oldq[1])
		except ValueError:
			maxnum = 10
		randnum1 = random.randrange(0, maxnum+1)
		randnum2 = random.randrange(0, maxnum+1)
		newq[0] = "What is %d + %d?" % (randnum1, randnum2)
		newq[1] = spellout(randnum1+randnum2)
	elif qtype == "!ALGEBRA+":
		try:
			num1, num2 = [int(i) for i in oldq[1].split('!')]
		except ValueError:
			num1, num2 = 10, 10
		randnum1 = random.randrange(0, num1+1)
		randnum2 = random.randrange(randnum1, num2+1)
		newq[0] = "What is x? %d = %d + x" % (randnum2, randnum1)
		newq[1] = spellout(randnum2-randnum1)
	else: pass #default to not modifying
	return newq
开发者ID:zonidjan,项目名称:erebus,代码行数:27,代码来源:trivia.py

示例7: createBridge

def createBridge(numOfNodes, edgeProb, bridgeNodes):
	'''
	numOfNodes: Number of nodes in the clustered part of the Bridge Graph
	edgeProb: Probability of existance of an edge between any two vertices.
	bridgeNodes: Number of nodes in the bridge
	This function creates a Bridge Graph with 2 main clusters connected by a bridge.
	'''	
	print "Generating and Saving Bridge Network..."	
	G1 = nx.erdos_renyi_graph(2*numOfNodes + bridgeNodes, edgeProb) #Create an ER graph with number of vertices equal to twice the number of vertices in the clusters plus the number of bridge nodes.
	G = nx.Graph() #Create an empty graph so that it can be filled with the required components from G1
	G.add_edges_from(G1.subgraph(range(numOfNodes)).edges()) #Generate an induced subgraph of the nodes, ranging from 0 to numOfNodes, from G1 and add it to G
	G.add_edges_from(G1.subgraph(range(numOfNodes + bridgeNodes,2*numOfNodes + bridgeNodes)).edges()) #Generate an induced subgraph of the nodes, ranging from (numOfNodes + bridgeNodes) to (2*numOfNodes + bridgeNodes)

	A = random.randrange(numOfNodes) #Choose a random vertex from the first component
	B = random.randrange(numOfNodes + bridgeNodes,2*numOfNodes + bridgeNodes) #Choose a random vertex from the second component

	prev = A #creating a connection from A to B via the bridge nodes
	for i in range(numOfNodes, numOfNodes + bridgeNodes):
		G.add_edge(prev, i)
		prev = i
	G.add_edge(i, B)
	
	StrMap = {}
	for node in G.nodes():
		StrMap[node] = str(node)
	G = nx.convert.relabel_nodes(G,StrMap)
	filename = "BG_" + str(numOfNodes) + "_" + str(edgeProb) + "_" + str(bridgeNodes) + ".gpickle"
	nx.write_gpickle(G,filename)#generate a gpickle file of the learnt graph.
	print "Successfully written into " + filename
开发者ID:vijaym123,项目名称:Bidirectional-Search,代码行数:29,代码来源:AtoB.py

示例8: reset

def reset():
    micek[0] = SIRKA//2 - 10
    micek[1] = VYSKA//2 - 10
    micek[2] = SIRKA//2 + 10
    micek[3] = VYSKA//2 + 10    
    smer[0] = randrange(1,5)
    smer[1] = randrange(-5,5)
开发者ID:zzuzzy,项目名称:PyLadies,代码行数:7,代码来源:myPong.py

示例9: test_merge

 def test_merge(self):
     inputs = []
     for i in range(random.randrange(5)):
         row = sorted(random.randrange(1000) for j in range(random.randrange(10)))
         inputs.append(row)
     self.assertEqual(sorted(chain(*inputs)), list(self.module.merge(*inputs)))
     self.assertEqual(list(self.module.merge()), [])
开发者ID:LinkedModernismProject,项目名称:web_code,代码行数:7,代码来源:test_heapq.py

示例10: say

    def say (self, what):
        sentences=what.split(".")

        for sentence in sentences:
            sentence=sentence.strip()
            if sentence=="":
                continue

            print ("SAYING: ", sentence)
            path=os.path.dirname(os.path.abspath(__file__))+"/speechcache/"
            filename=sentence.lower().replace(" ", "")+".mp3"

            if not filename in self.soundCache:
                tts=googletts.googleTTS(text=''+sentence,lang='es', debug=False)
                tts.save(path+str(self.soundCache["soundIndex"])+".mp3")
                self.soundCache[filename]=str(self.soundCache["soundIndex"])+".mp3"
                self.soundCache["soundIndex"]=self.soundCache["soundIndex"]+1

            song = pyglet.media.load(path+self.soundCache[filename])
            song.play()
            time_speaking=song.duration-0.5
            start_time=time.time()

            while time.time()-start_time<time_speaking:
                pos=random.randrange(10,20)
                self.head.jaw.moveTo(pos)
                time.sleep(0.2)
                pos=random.randrange(30,50)
                self.head.jaw.moveTo(pos)
                time.sleep(0.2)
            self.head.jaw.moveTo(10)
            time.sleep(0.5)
开发者ID:ugogarcia,项目名称:inmoovbrainserver,代码行数:32,代码来源:inmoov.py

示例11: testRun

def testRun():
	# For testing
	# count = [500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500, 7000, 7500, 8000, 8500, 9000, 9500, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000, 60000, 65000, 70000, 75000, 80000, 85000, 90000, 95000, 100000]

	count = 5000

	while count < 5000000000:
	# for num in testList:
		randList = [None] * count
		for n in range(0, count):
			randNum = random.randrange(0, 101)
			if (random.randrange(0, 2) == 0):
				randNum = randNum * -1
			randList[n] = randNum

		startTime = time.clock()
		result = linearSearch(randList)
		stopTime = time.clock()

		resultTime = stopTime - startTime

		print("n: " + str(len(randList)))
		print("Largest Result: " + str(result[2]))
		print("Running Time: " + str(resultTime))

		count = count * 10
开发者ID:gariepyt,项目名称:cs325_project1,代码行数:26,代码来源:linear.py

示例12: generate_bodies

def generate_bodies(place, area, body_amount):
	delta = 0
	bodies = []
	for i in range(body_amount):
		random.seed(i)
		radiusXY = 	(randrange(2*area) - area)*0.05
		radiusZ = 	(randrange(2*area) - area)*0.05
		if (i <= body_amount/4):
			shift = (delta, 0)
		elif (i <= 2*body_amount/4):
			shift = (-delta, 0)
		elif (i <= 3*body_amount/4):
			shift = (0, -delta)
		else:
			shift = (0, delta)
		bodies.append	(
							{															
							'x': place[0] + radiusXY*cos(pi/AMOUNT * i) + shift[0],
							'y': place[1] + radiusXY*sin(pi/AMOUNT * i) + shift[1], 		
							'z': place[0] + radiusZ*sin(pi/AMOUNT * i), 		
							'mass': randrange(10**(SUPERMASS//2), 10**(SUPERMASS-5)), #10**(SUPERMASS-4),
							'radius': 10
							}
						)
	return bodies
开发者ID:vovkd,项目名称:Simula,代码行数:25,代码来源:gm.py

示例13: main

def main():
    l = [random.randrange(-10, 10) for i in range(random.randrange(5, 10))]
    print l

    # function
    print "max value in list:%d" % (max_list(l))
    print "min value in list:%d" % (min_list(l))
开发者ID:xiaoy,项目名称:Exercise,代码行数:7,代码来源:max.py

示例14: __init__

    def __init__(self,numPlayers):

        x = 0
        while x < numPlayers:
            #set random roles
            r = randrange(0,numPlayers,1)
            while self.roles[r][1] == True:
                r = randrange(0,numPlayers,1)
            self.roles[r][1] = True
            self.role.append(self.roles[r][0])
            
            #set health
            if self.role[x] == "Sheriff":
                self.health.append(5)
            else: self.health.append(4)
            #set horse through jail to false and no card
            self.mustang.append([False,None])
            self.scope.append([False,None])
            self.barrel.append([False,None])
            self.dynamite.append([False,None])
            self.jail.append([False,None])
            #set gun to none and volcanic to false
            self.gun.append([1,None])
            self.volcanic.append(False)
            x += 1
开发者ID:phippene,项目名称:AI_Bang,代码行数:25,代码来源:BoardClass.py

示例15: int_generator

def int_generator(count=1, begin=1, end=101, is_fill=False):
    _len = len(str(end))
    for _ in range(count):
        if is_fill:
            yield str(random.randrange(begin,end)).zfill(_len)
        else:
            yield str(random.randrange(begin,end))
开发者ID:jiahut,项目名称:pipeline,代码行数:7,代码来源:gen_define.py


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