示例#1
0
文件: team.py 项目: devlabsf/Sandlot
 def set_fielding(self, player_name, pitch_catches, pitch_pitches, catch_catches, catch_first, catch_second, catch_throws, in_throws, in_grounders, in_catches, out_flyballs, out_catches, out_big_throws, out_throws, out_grounders):
   pitcher_catches = random.randint(5,30)
   pitcher_pitches = random.randint(50,100)
   self.pitch_catches = pitcher_catches
   self.pitch_pitches = pitcher_pitches
   catcher_catches = random.randint(50,100)
   catcher_1st = random.randint(5,20)
   catcher_2nd = random.randint(20,50)
   catcher_throws = random.randint(30,50)
   self.catch_catches = catcher_catches
   self.catch_first = catcher_1st
   self.catch_second = catcher_2nd
   self.catch_throws= catcher_throws
   infield_throws = random.randint(50,80)
   infield_grounders = random.randint(50,80)
   infield_catches = random.randint(50,80)
   self.in_throws = infield_throws
   self.in_grounders = infield_grounders
   self.in_catches = infield_catches
   outfield_flyballs = random.randint(50,90)
   outfield_catches = random.randint(50,90)
   outfield_big_throws = random.randint(15,30)
   outfield_throws = random.ranint(50,90)
   outfield_grounders = random.randint(50,90)
   self.out_flyballs = outfield_flyballs
   self.out_catches = outfield_catches
   self.out_big_throws = outfield_big_throws
   self.out_throws = outfield_throws
   self.out_grounders = outfield_grounders
def annealing_optimaize(domain,costf,T=1000.0,cool=0.95,step=1):
	#创建一个随机解
	vec = [float(random.ranint(domain[i][0],domain[i][1]) for i in len(domain))]
	
	while T > 0.1:
		#选择一个索引值
		i = random.randint(0,len(domain)-1)
		#选择一个改变索引值的方向
		dir = random.randint(-step,step)
		
		#创建一个代表题解的新列表,改变其中的一个值
		vecb = vec[:]
		vecb[i] +=dir
		if vecb[i] < domain[i][0]:
			wecb[i] = domain[i][0]
		if vecb[i] > domain[i][1]:
			wecb[i] = domain[i][1]
			
		#计算当前的成本和新的成本
		ea = costf(vec)
		eb = costf(vecb)
		
		if (eb < ea) or (random.random() < math.pow(math.e,-(eb-ea)/T)):
			vec = vecb
		T = t *cool
	return vec
def hillclimb(domain,costf):
	#创建一个随机解
	sol = [random.ranint(domain[i][0],domain[i][1]) for i in len(domain)]
	
	min_cost = 999999.9
	best_sol_index = -1
	#主循环
	while 1:
		neighbors = []
		co
		for i in rangge(len(domain)):
			if sol[i] > domain[i][0]:
				neighbors.append(sol[0:i]+[sol[i]-1]+sol[i+1:])
			if sol[i] < domain[i][1]:
				neighbors.append(sol[0:i] + [sol[i]+1],sol[i+1:])
		
		current_cost = costf(sol)
		min_cost = current_cost
		for j in range(len(neighbors)):
			cost = costf(neighbors[j])
			if cost < min_cost:
				min_cost = cost
				best_sol_index = j
		sol = neighbors[best_sol_index]
		
		if min_cost == current_cost:  #获取的是局部最优解并非全局最优解
			break
示例#4
0
def addABunch():
    print ("we're going to add a bunch of numbers to your list!")
    numToAdd = input("How many new integers would you like to add?  ")
    numRang = input("And how high would you like these numbers to go?  ")
    for x in range(0,int(numToAdd)):
        myList.append(random.ranint(0,  int(numrange)))
    print("Your list is complete!")
示例#5
0
def roll(bumptime):
    print("MK2")
    check = bumptime + random.ranint(1, 20)
    if check > 20:
        bumptime = 0
        path = "/home/torsvik/Music/hina/bump.txt"
        fp = open(path, 'r+')
        with open(path, "r") as text_file:

            tracklist.extend(text_file.readlines())

            text_file.close()
        song = random.choice(tracklist)
        song = song.rstrip('\n')
    else:
        bumptime = 0
        path = "/home/torsvik/Music/hina/bump.txt"
        fp = open(path, 'r+')
        with open(path, "r") as text_file:

            tracklist.extend(text_file.readlines())

            text_file.close()
        song = random.choice(tracklist)
        song = song.rstrip('\n')
    track = [bumptime, song]
    return track
示例#6
0
    def SealedBidding(self, item, current_state,sharing = 0.6): #暗标
        valuation = self.GetValuation(item, current_state)
        bidding = random.randint(valuation[0], valuation[1]) * random.uniform(0.4, sharing)
        if bidding > self.Wealth:
            bidding = random.ranint(1, self.Wealth)

        return bidding
示例#7
0
    def roll_dice():
        rolled_dice = []
        for i in range(0, 4):
            rolled_dice.append(random.ranint(1, 6))

        rolled_dice.remove(min(rolled_dice))
        return sum(rolled_dice)
    def getRandom(self) -> int:
        result, node, index = self.head, self.head.next, 1

        while node:
            if random.ranint(0, index) == 0:
                result = node
            node = node.next
            index += 1
        return result.val
示例#9
0
文件: genetico.py 项目: DeathCom/IA
def mutacion(prob, gen):
    #muta un gen con una probabilidad prob
    if random.random < prob:
        cromosoma = random.ranint(0, len(gen))
        if gen[cromosoma] == 0:
            gen[cromosoma] = 1
        else:
            gen[cromosoma] = 0
    return gen
 def select_action(self, current_state, step):
     threshold = min(self.epsilon, step / 1000.)
     if random.random() < threshold:
         #Exploit best option with probability epsilon
         action_q_vals = self.sess.run(self.q, feed_dict={self.x:current_state})
         action_idx = np.argmax(action_q_vals)
         #can be replaced by tensorflow's argmax
         action = self.actions[action_idx]
     else:
         #Explore random option with probability 1 - epsilon
         action = self.actions[random.ranint(0, len(self.actions) - 1)]
         
示例#11
0
def get_comments(songs):  #用歌曲id获取每首歌的评论数,评论大于30000时,写入数据库
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.append(['歌曲名', '评论数'])
    j = 1
    for song_id in songs:
        time.sleep(random.ranint(3, 9))
        try:
            sys.stdout.write('爬取到%s首歌曲,正在处理第%s首......' % (len(songs), str(j)) +
                             ' \r')
            sys.stdout.flush()
            url = "https://music.163.com/weapi/v1/resource/comments/R_SO_4_{}?csrf_token=".format(
                song_id)
            headers = {
                "Accept":
                "*/*",
                "Accept-Encoding":
                "gzip, deflate, br",
                "Accept-Language":
                "zh-CN,zh;q=0.8",
                "Connection":
                "keep-alive",
                "Content-Length":
                "516",
                "Content-Type":
                "application/x-www-form-urlencoded",
                "Cookie":
                "mail_psc_fingerprint=3717713c98660b8885cd78c8f7cb7af4; __gads=ID=d94d974e5f9dc0c5:T=1506045311:S=ALNI_MaEWN6i8X52dDZdYPjqSCSA1oVWOA; vjuids=a5e6341df.15ea74c0e75.0.941115a82a253; usertrack=ezq0pVoKgNdhb/v1BeoIAg==; _ga=GA1.2.1122557775.1510637788; [email protected]:-1:1; NTES_CMT_USER_INFO=127961435%7C%E6%9C%89%E6%80%81%E5%BA%A6%E7%BD%91%E5%8F%8B07E8Br%7C%7Cfalse%7CYnltX2Zpc2hAMTYzLmNvbQ%3D%3D; [email protected]|1533093116|2|study|00&99|sic&1532486568&other#sic&510100#10#0#0|&0||[email protected]; vjlast=1506045333.1534913055.12; vinfo_n_f_l_n3=7c5ee84b19f99a57.1.11.1506045333265.1534749967500.1534913058714; _ntes_nnid=77859a8fd70b848c2e5fdea7a8ec1565,1537943241451; _ntes_nuid=77859a8fd70b848c2e5fdea7a8ec1565; WM_NI=poupJg3ekqazNJteNkBYXZE3CUer804X%2F4YLGcAXX0UMx2%2BdRIwOaQyYTjPM4Rfc1q8HHmfNR8AOCcdk2bq3QZXc06hN7XVvjFDmNx0dNzvu1lcpmungYL9H1okhxsytSWo%3D; WM_NIKE=9ca17ae2e6ffcda170e2e6eea6b47290ac8398d47c9b9e8fa3c15b928f9e84f345a68ff997eb66f1b48792d52af0fea7c3b92ab4b1bb91c96df1bba592e4728e96bc86cd61828798bbc839818bab93bb3cf888e1d5dc4885bd8fb9db3c9793b8d3aa709297b9b0e45bbb879c8bd347f88eaa84b47bfc98888ee54692e88fb0c269a8b5fe83f43993869884b33eac92f9b9d57eaa9a8c8ecd74f4bc829bf57ff3b4ad91f07faeb997adbc44f3b1a589fb79bbac9db8ee37e2a3; WM_TID=%2FpNEMn3K7dpAQRAQVFZ4LRIkhO7GGB%2FE; JSESSIONID-WYYY=IYJQGhbMhvYpNnF3f4iogiPNeGi8GsquRsTrIDWwK9K7Q%2Bh7lrli31qXlZy%2Bk%2FuCRyWYCfqMCXqJIOwAZxtu9nEYVOpCrVTuu65r5xe4C%5Cuuc38QEufvMjTIwTAPH%5CwhQRXN9xWUKFdKfOgb1WyYUPatUQEJrIsiMM8zJ4KYuzcA%5CyIM%3A1540956410507; _iuqxldmzr_=32; __utma=94650624.1651417532.1507777869.1540547393.1540952871.28; __utmb=94650624.15.10.1540952871; __utmc=94650624; __utmz=94650624.1540952871.28.12.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; MUSIC_U=9de0b492647e4661d0d11bc392fe83c4dfe007791dc6e29dc69d1ce280c1d9fd5b1322b5d7d05f61973d23dfe458bad1bff748db9e9cfbf8642a565388478f73305842396b5dfc01; __remember_me=true; __csrf=ffb8bec0672477b21e4ed7532296cfa7",
                "Host":
                "music.163.com",
                "Origin":
                "https://music.163.com",
                "Referer":
                "https://music.163.com/song?id={}".format(song_id),
                "User-Agent":
                "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
            }
            params = 'ZIDK9Nv/D67iZW2GGf49SCAKLOIjH3gFjcT+pO7mK6GEzMGHfBTgpZdTDifpAptBjSSXJLIajcU28SPmL1IpdVHxyWyLgDYW0Tu2rcJBbZptosH9I1bKlajbn6zNBo7iRV0sa5ETl6DoPwzFZvZa3T6OvCAmYnGHMDoeH4lXugQdp7chtCt+aX5eV1qoGlFjLzNumFSfqDCCJ0lqjWvqqZ9WTYzZy1hphjl55cEdeD4='
            encSecKey = '55c149ec4ed08650753e8856c9d96d9df0e9ca4bfcd3a9ca219dd0b0da8e3b818dc64195f1889af0c738edfc31b68e26d89591bf537581b9984d25191e47f2d64bed45947db700a6647cc34c48312daec15b3a917d582208824090f044549702556e757c424a1fa06cf17cafec19422844f9a9ed31322e204d5a2edcb7270133'
            data = {'params': params, 'encSecKey': encSecKey}
            res = requests.post(url, headers=headers, data=data)
            comment = json.loads(res.text)
            song_comment = comment['total']
            if song_comment > 30000:
                sheet.append([songs[song_id], song_comment])
                #print('%s 评论总计==> %s'%(songs[song_id],song_comment))
            else:
                pass
        except Exception as e:
            print('歌曲id ==> %s 报错,原因如下: %s' % (song_id, e))
            continue
        j += 1
    wb.save('wy_count_>1002.xlsx')
示例#12
0
def downloadHtml(url,
                 headers=[],
                 proxy={},
                 timeout=None,
                 decodeInfo="utf-8",
                 num_retries=10,
                 ues_proxy_ratio=5):
    '''
    一个完善的下载网页的逻辑
    支持User-Agent
    支持Proxies
    支持Headers
    超时的考虑
    编码问题,如果不是utf-8怎么处理
    服务器返回5xx的错误
    客户端出现4xx的错误
    考虑延时的问题
    '''
    time.sleep(random.ranint(1, 3))

    #    调整是否使用代理
    if random.randint(1, 10) > ues_proxy_ratio:
        proxy = None

    html = None
    #    创建ProxyHandler
    proxy_support = request.ProxyHandler(proxy)
    #    创建openr
    opener = request.build_opener(proxy_support)
    #    设置user-agent
    opener.add_handlers = headers
    #    安装openr
    request.install_opener(opener)

    try:
        #        可能出现编码异常,网络下载异常:客户端、服务器(404,403)
        res = request.urlopen(url)
        html = res.read().decode(decodeInfo)

    except UnicodeDecodeError:
        print("编码出错")
    except error.URLError or error.HTTPError as e:
        if hasattr(e, 'code') and 400 <= e.code < 500:
            print('客户端错误')
        elif hasattr(e, 'code') and 500 <= e.code < 600:
            print('正在尝试重新获取')
            if num_retries > 0:
                time.sleep(int(200 / num_retries))
                downloadHtml(url, headers, proxy, timeout, decodeInfo,
                             num_retries - 1)

    return html
示例#13
0
    def rain(self):
        # TODO. Append a new Raindrop to this Cloud's list of Raindrops,
        # TODO    where the new Raindrop starts at:
        # TODO      - x is a random integer between this Cloud's x and this Cloud's x + 300.
        # TODO      - y is this Cloud's y + 100.
        randomx = self.x + random.ranint(0, 100)
        raindrop = Raindrop(self.screen, randomx, self.y, "cat.jpg")
        self.raindrops.append(raindrop)

        for k in range(len(self)):
            raindrop = self.raindrops[k]
            raindrop.move()
            raindrop.draw()
def mutateRna(seq, tDimerProb, ranSwapProb, ranDelProb, ranAddProb):
    tDimerLocs = tDimers(seq)
    tDimerProb = 10000000 * tDimerProb
    ranSwapProb = 10000000 * ranSwapProb
    ranDelProb = 10000000 * ranDelProb
    ranAddProb = 10000000 * ranAddProb
    for tDimer in tDimerLocs:
        if random.randint(10000000) <= tDimerProb:
            seq = seq[:tDimer] + seq[tDimer + 1:]
    for i in seq.len():
        if random.randint(10000000) <= ranDelProb:
            seq = seq[:i] + seq[i + 1:]
    for j in seq.len:
        if random.ranint(10000000) <= ranSwapProb:
            baseChoice = random.ranint(4)
            baseList = ["a", "u", "c", "g"]
            seq = seq[:i - 1] + baseList[baseChoice] + seq[i + 1:]
    for k in seq.len():
        if random.ranint(10000000) <= ranAddProb:
            baseChoice = random.ranint(4)
            baseList = ["a", "u", "c", "g"]
            seq = seq[:i] + baseList[baseChoice] + seq[i + 1:]
    return seq
示例#15
0
def costumer():
    tramit = rn.randint(1, 5)
    # 1 -> Deposit, Withdraw, Loan Payment
    # 2 -> Western Union
    # 3 -> Customer Service Information
    # 4 -> Preferred, Prime Account
    # 5 -> Account Opnening
    if tramit == 1:
        time_pross = rn.randint(3, 7)
        print(time_disp)
        print(tramit, ' ', time_pross)
    elif trammit == 2:
        time_pross = rn.randint(3,5)
    elif tramit == 3:
        time_pross = rn.randint(5, 15)
    elif tramit == 4:
        timepross = rn.ranint()
示例#16
0
def lots_of_animals(n):
    animals = []
    while n > 0:
        a_name = random.choice(names)
        a_height = random.randint(5, 501)
        a_weight = random.randint(2, 2001)
        a_color = random.choice(colors)
        a_legs = random.ranint(0, 5)
        a_specices = random.choice(species_names)
        if a_specices == "Rodents" or a_species == "Canine":
            a_mammal = True
        else:
            a_mammal = False

        a_animal = ExoticAnimals(a_name, a_height, a_weight, a_color, a_legs,
                                 a_specices, a_mammal)
        animals.append(a_animal)
        n = n - 1
    return animals
示例#17
0
def tree_topology_build(count, size=None):
    import random
    if not size:
        size = random.randint(2, 20)
    tree_topology = open("tree_topology" + str(count), 'w')
    ES_size = -1
    SW_size = 0
    for i in range(size - 1):
        node_is_SW = random.randint(0, 1)
        if not node_is_SW:
            ES_size += 1
            tree_topology.write("SW" + str(random.randint(0, SW_size)) +
                                " ES" + str(ES_size) + "\n")
        else:
            SW_size += 1
            tree_topology.write("SW" + str(random.ranint(0, SW_size - 1)) +
                                " SW" + str(SW_size) + "\n")
    tree_topology.flush()
    tree_topology.close()
示例#18
0
def puzzle_building_search(allTiles):
    while len(allTiles) > 1:  # while we have more than one tile

        # get up to 20 random tiles from the list
        tempTileArray = []
        if (len(allTiles) > 20):
            for i in xrange(20):
                randomNum = random.ranint(0, len(allTiles) - 1)
                tempTileArray.append(allTiles.pop(randomNum))
        else:
            tempTileArray = allTiles

        # preform a uniform cost search
        tempNode = Node(tempTileArray, [], 0, [], 0,
                        0)  # make a starting node for a uniform cost search
        outputNode, count = uniform_cost(tempNode)  # preform search

        # group tiles together
        newList = find_matches(outputNode.placed_tiles)

        # add tiles back onto the list of tiles
        for i in len(newList):
            allTiles.append(newList[i])
    return allTiles[0]
示例#19
0
def workerNmap(number, delay):
    ip = random.choice(config.ipList)
    ran = random.randint(0, 6)
    for x in range(random.ranint(10, 20)):
        if ran == 0:
            strRun = "nmap " + ip
        elif ran == 1:
            strRun = "nmap –vv –n –sS " + ip
        elif ran == 2:
            strRun = "nmap –vv –n –sT " + ip
        elif ran == 3:
            strRun = "nmap –vv –n –sF " + ip
        elif ran == 4:
            strRun = "nmap –vv –n –sU " + ip
        elif ran == 5:
            strRun = "nmap –vv –sA " + ip
        else:
            strRun = "nmap –vv –sP " + ip
        _file = open('/web/traffic/traffic' + str(number) + '.txt', 'a')
        _file.write(strRun + '\n')
        _file.write(str(delay) + '\n')
        _file.close()
        os.system(strRun)
        time.sleep(str(delay))
def random_word():
    idx = random.ranint(0, len(WORDS) - 1)
    return WORDS[idx]
示例#21
0
def genKey():
    key = []
    # Random integers can be between 2 (1 would make no difference and the amount of characters)
    key.append(random.ranint(2, len(SYMBOLS)))
    key.append(random.ranint(len(SYMBOLS)))
    return key
示例#22
0
import random

highest=10
answer=random.ranint(1,highest)
print(answer)
print("Please guess number between 1 and {}: ".format(highest))
guess = int(input())

while guess !=answer:
    if guess < answer:
       print("Please guess higher")
    else: 
        print ('Please guess lower')

print("You got it the first time")
    

# if guess == answer:
#     print("You got it the first time") 
# else:
#     if guess < answer:
#         print("Please guess higher")
#     else: # guess must be greater than answer, not equal to.
#         print ('Please guess lower')
#     guess = int(input())
#     if guess == answer:
#         print("Well done, you guessed it")
#     else:
#         print("Sorry, you have not guessed correctly")
    
def color_random():
    return [random.ranint(0, 255) for r in range(3)]
示例#24
0
    if snake[0][0] in [0, sh] or snake[0][1] in [0, sw
                                                 ] or snake[0] in snake[1:]:
        curses.endwin()
        quit()

    new_head = [snake[0][0], snake[0][1]]

    if key == curses.KEY_DOWN:
        new_head[0] += 1
    if key == curses.KEY_UP:
        new_head[0] -= 1
    if key == curses.KEY_LEFT:
        new_head[0] -= 1
    if key == curses.KEY_RIGHT:
        new_head[0] += 1

    SNAKE.INSERT(0, new_head)

    if snake[0] == food:
        food = None
        while food is None:
            nf = [random.ranint(1, sh - 1), random.ranint(1, sw - 1)]
        food = nf if nf not in snake else None
        w.addch(food[0], food[1], curses.ACS_PI)
    else:
        tail = snake.pop()
        w.addch(tail[0], tail[1], '')

    w.addch(snake[0][0], snake[0][1], curses.ACS_CKBOARD)
示例#25
0
f = open('game.txt')
score = f.read().split()
game_times=score[0]
min_times=score[1]
totle_times=score[2]
print game_times
print min_times
print totle_times
if game_times > 0:
    avg_times = float(totle_times) / game_times
else:
    avg_times=0
print "you played %d times,the min time is %d,and the avg time is %2f" %(game_times,min_times,avg_times)
f.close()
########guess###############
num = ranint(1,100)
print "what is you name:"
name = raw_input()
print "what i think:"
bingo == False
times = 0
while bingo == False:
    time += 1
    answer = input()
    if answer > num:
        print "too big"
    if answer < num:
        print "too small"
    if answer == num:
        print "bingo!!!!"
        bingo == True
示例#26
0
# Gra jaka to liczba polega na zgadywaniu w jak najmniejszej ilości prób liczb z zakresu od 1 do 1000.

print("Witaj w grze 'Jaka to liczba'")

import random

losowa_liczba = random.ranint(1,1000)

print("Spróbuj zgadnąć w jak najmniejszej liczbie prób liczbę z zakresu od 1 do 1000 ")

liczba = int(input("Podaj szukaną liczbę, z zakresu od 1 do 1000: "))





input("Aby zakończyć program, naciśnij klawisz Enter.")
示例#27
0
def CCPivot(g):
    pivot = g.node[random.ranint(0, len(g.node))]
示例#28
0
        sys.exit(0)

    # Now let's begin feeding teh drive test cases until we can't bear
    # it anymore! CTRl-C to exit the loop and stop fuzzing

    while 1:
        # Open the log file first
        fb = open("my_ioctl_fuzzer.log", "a")

        # Pick a random device name
        current_device = valid_devices[random.randint(0,
                                                      len(valid_devices) - 1)]
        fb.write("[*] Fuzzing: %s\n" % (current_device))

        # Pick a random IOCTL code
        current_ioctl = ioctl_list(random.ranint(0, len(valid_devices) - 1))
        fb.write("[*] With IOCTL: 0x%08x\n" % (current_ioctl))

        # Choose a random length
        current_lenght = random.randint(0, 10000)
        fb.write("[*] Buffer length: %d\n" % (current_lenght))

        # Let's test with a buffer of repating As
        # Fell free to create your own test cases here
        in_buffer = "A" * current_length

        # Give the IOCTL run an out_buffer
        out_buf = (c_char * current_lenght)()
        bytes_returned = c_ulong(current_lenght)

        # Obtain a handle
示例#29
0
def generateReads(genome, numReads, readLen):
    reads = []
    for _ in range(numReads):
        start = random.ranint(0, len(genome) - readLen) - 1
        read.append(genome[star:start + readLen])
    return reads
示例#30
0
def get_random_proxy(ip_list):
    length = len(ip_list)
    random_num = random.ranint(0, length)
    return ip_list[random_num]