Best Python code snippet using locust
day23_2.py
Source:day23_2.py
1from copy import deepcopy2NUM_FISHES = 163class Space:4 def __init__(self, num, is_room):5 self.num = num6 self.is_room = is_room7 self.adjacent = []8 @staticmethod9 def connect(s1, s2):10 s1.adjacent.append(s2)11 s2.adjacent.append(s1)12 def is_in_front_of_door(self):13 return self.num in [3, 5, 7, 9]14 def __str__(self):15 return "Space %d" % self.num16def get_fish_type(fish_ind):17 if fish_ind in [0, 1, 2, 3]:18 return 119 elif fish_ind in [4, 5, 6, 7]:20 return 221 elif fish_ind in [8, 9, 10, 11]:22 return 323 return 424def encode_state(position):25 hash_sum = 026 for ind in range(1, len(position) + 1):27 hash_sum += position[ind - 1] * (30 ** ind)28 return hash_sum29def decode_state(hash_sum, num_items):30 values = []31 for ind in range(num_items, 0, -1):32 values.append(hash_sum // (30 ** ind))33 hash_sum %= 30 ** ind34 return tuple(values[::-1])35target_rooms_for_fish_types = {1: [12, 13, 14, 15], 2: [16, 17, 18, 19], 3: [20, 21, 22, 23], 4: [24, 25, 26, 27]}36#start_positions = (15, 22, 25, 27, 12, 18, 20, 21, 16, 17, 23, 26, 13, 14, 19, 24)37#start_positions = (12, 17, 14, 15, 16, 13, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27)38start_positions = (19, 20, 22, 25, 16, 18, 21, 27, 15, 17, 24, 26, 12, 13, 14, 23)39# Prepare the field by creating spaces and connecting them40nodes = {}41for node_ind in range(1, 28):42 node = Space(node_ind, is_room=(node_ind >= 12))43 if node_ind >= 12:44 node.is_room = True45 nodes[node_ind] = node46for node_ind in range(1, 11): # Connect hallway47 Space.connect(nodes[node_ind], nodes[node_ind + 1])48# Connect hallway <-> room49Space.connect(nodes[3], nodes[12])50Space.connect(nodes[5], nodes[16])51Space.connect(nodes[7], nodes[20])52Space.connect(nodes[9], nodes[24])53for node_ind in [12, 16, 20, 24]: # Connect room <-> room54 Space.connect(nodes[node_ind], nodes[node_ind + 1])55 Space.connect(nodes[node_ind + 1], nodes[node_ind + 2])56 Space.connect(nodes[node_ind + 2], nodes[node_ind + 3])57min_score = 10000000000058step = 059evaluated = {}60initial_state = [encode_state(start_positions), 0]61queue_entry_map = {encode_state(start_positions): initial_state} # Maintain the board states for quick lookup, enc(positions) -> score62queue = [initial_state] # State = (positions, current score)63while queue:64 encoded_state, cur_score = queue.pop(0)65 positions = decode_state(encoded_state, NUM_FISHES)66 queue_entry_map.pop(encoded_state)67 #print("Considering situation %s" % list(positions))68 # Is this a final configuration?69 fish_in_right_rooms = [positions[fish_ind] in target_rooms_for_fish_types[get_fish_type(fish_ind)] for fish_ind in range(NUM_FISHES)]70 if all(fish_in_right_rooms):71 if cur_score < min_score:72 print("New minimum score: %d" % cur_score)73 min_score = cur_score74 continue75 # For each fish, find the possible movements and add them to the queue76 for fish_ind in range(0, NUM_FISHES):77 #print("Looking at movements of fish %d (cur pos: %d)" % (fish_ind, positions[fish_ind]))78 is_in_right_room = positions[fish_ind] in target_rooms_for_fish_types[get_fish_type(fish_ind)]79 if is_in_right_room:80 # Check the fishes 'below' us81 is_ok = True82 cur_room = positions[fish_ind] + 183 while cur_room not in [16, 20, 24, 28]:84 if cur_room in positions:85 # Occupied room86 other_fish_type = get_fish_type(positions.index(cur_room))87 if other_fish_type != get_fish_type(fish_ind):88 is_ok = False89 break90 cur_room += 191 if is_ok:92 continue93 fish_pos_queue = [(positions[fish_ind], [positions[fish_ind]])]94 while fish_pos_queue:95 cur_fish_pos, visited = fish_pos_queue.pop()96 cur_fish_space = nodes[cur_fish_pos]97 for adj_space in cur_fish_space.adjacent:98 if adj_space.num in positions or adj_space.num in visited:99 continue100 #print("Fish %d can move to %d (visited: %s)" % (fish_ind, adj_space.num, visited))101 # The space is free - consider this state if it's not in front of a door102 new_visited = visited.copy()103 new_visited.append(adj_space.num)104 if (adj_space.num, new_visited) not in fish_pos_queue:105 fish_pos_queue.append((adj_space.num, new_visited))106 will_stop = True107 if adj_space.is_in_front_of_door(): # Rule 1108 will_stop = False109 if adj_space.is_room: # Rule 2110 # We move to a room111 # Check if this is the destination112 if adj_space.num not in target_rooms_for_fish_types[get_fish_type(fish_ind)]:113 will_stop = False114 if adj_space.num in [12, 16, 20, 24] and (adj_space.num + 1) not in positions:115 will_stop = False116 if adj_space.num in [13, 17, 21, 25] and (adj_space.num + 1) not in positions:117 will_stop = False118 if adj_space.num in [14, 18, 22, 26] and (adj_space.num + 1) not in positions:119 will_stop = False120 # check if there is no 'conflicting' fish in the adjacent room121 cur_room = adj_space.num + 1122 while cur_room not in [16, 20, 24, 28]:123 if cur_room in positions:124 # Occupied room125 other_fish_type = get_fish_type(positions.index(cur_room))126 if other_fish_type != get_fish_type(fish_ind):127 will_stop = False128 break129 cur_room += 1130 if not nodes[positions[fish_ind]].is_room and not adj_space.is_room: # Rule 3131 will_stop = False132 if will_stop:133 new_positions = list(deepcopy(positions))134 new_positions[fish_ind] = adj_space.num135 new_positions = tuple(new_positions)136 additional_score = len(visited) * (10 ** (get_fish_type(fish_ind) - 1))137 new_score = cur_score + additional_score138 should_add = True139 new_state = encode_state(new_positions)140 if new_state in queue_entry_map:141 # We already have an entry like this in the queue - if the score in the queue is higher, replace the queue score with the new (lower) score142 if queue_entry_map[new_state][1] > new_score:143 queue_entry_map[new_state][1] = new_score144 should_add = False145 if should_add:146 #print("Will append: fish %d move from %d to %d (steps: %d)" % (fish_ind, positions[fish_ind], adj_space.num, len(visited)))147 queue_entry = [new_state, new_score]148 queue.append(queue_entry) # Consider it for a final state149 queue_entry_map[new_state] = queue_entry150 step += 1151 if step % 1000 == 0:...
random_train.py
Source:random_train.py
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3# Copyright (C) 2014 Julian Metzler4# See the LICENSE file for the full license.5"""6Script to display "next stop" information with a random German train station7"""8import argparse9import ibis10import os11import random12import re13import sqlite314import time15def tts_modify(stop):16 tts_stop = re.sub(r"([\s\(])b", r"\1bei", stop)17 tts_stop = re.sub(r"([\s\(])Kr", r"\1Kreis", tts_stop)18 tts_stop = tts_stop.replace(u"Hbf", u"Hauptbahnhof")19 tts_stop = tts_stop.replace(u"Pbf", u"Personenbahnhof")20 tts_stop = tts_stop.replace(u"Gbf", u"Güterbahnhof")21 tts_stop = tts_stop.replace(u"Rbf", u"Rangierbahnhof")22 return tts_stop23def main():24 parser = argparse.ArgumentParser()25 parser.add_argument('-host', '--host', type = str, default = "localhost")26 parser.add_argument('-p', '--port', type = int, default = 4242)27 parser.add_argument('-d', '--display', type = int, choices = (0, 1, 2, 3))28 parser.add_argument('-pr', '--priority', type = int, default = 0)29 parser.add_argument('-cl', '--client', type = str, default = "random_train.py")30 parser.add_argument('-si', '--sequence-interval', type = int, default = 5)31 parser.add_argument('-db', '--database', type = str, default = "db_stations.db")32 parser.add_argument('-j', '--jingle', type = str, default = "station_jingle.wav")33 parser.add_argument('-ij', '--info-jingle', type = str, default = "info_jingle.wav")34 parser.add_argument('-sj', '--stop-jingle', type = str, default = "stop_jingle.wav")35 parser.add_argument('-q', '--quiet', action = 'store_true')36 args = parser.parse_args()37 38 client = ibis.Client(args.host, args.port)39 40 db = sqlite3.connect(args.database)41 cur = db.cursor()42 cur.execute("SELECT * FROM `stations`")43 stations = [row[1] for row in cur.fetchall()]44 45 while True:46 num_stops = random.randint(3, 20)47 stops = random.sample(stations, num_stops)48 target = stops[-1]49 train_type = random.choice(["RB", "RE", "S"])50 train_number = random.randint(1, 99)51 has_stopped = True52 53 print "%s%i %s" % (train_type, train_number, target)54 55 for i in range(num_stops):56 stop = stops[i]57 direction = random.choice(["links", "rechts"])58 will_stop = random.choice([True, False])59 cycle_interval = random.uniform(10, 30)60 61 if direction == "links":62 if will_stop:63 print " [S] <", stop64 else:65 print " <", stop66 elif direction == "rechts":67 if will_stop:68 print " [S] >", stop69 else:70 print " >", stop71 72 client.set_stop_indicator(args.display, False)73 74 idle_sequence = []75 idle_sequence.append(client.make_text("%s%i %s" % (train_type, train_number, target)))76 idle_sequence.append(client.make_time("%d.%m.%Y %H:%M"))77 client.set_sequence(args.display, idle_sequence, args.sequence_interval, priority = args.priority, client = args.client)78 79 if not args.quiet and has_stopped:80 os.popen("aplay -q %s" % args.info_jingle)81 os.popen((u"espeak -v mb/mb-de5 -s 40 '%s %i nach %s'" % (train_type, train_number, tts_modify(target).replace("'", "\\'"))).encode('utf-8'))82 83 wait_time = random.uniform(5, 30)84 time.sleep(wait_time)85 86 sequence = []87 sequence.append(client.make_text("Nächster Halt:"))88 sequence.append(client.make_text(stop))89 sequence.append(client.make_text("Ausstieg %s" % direction))90 client.set_sequence(args.display, sequence, args.sequence_interval, priority = args.priority, client = args.client)91 92 if not args.quiet:93 os.popen("aplay -q %s" % args.jingle)94 if i == num_stops - 1:95 os.popen((u"espeak -v mb/mb-de5 -s 40 'Nähxter Halt: %s. Endstation. Bitte aussteigen. Ausstieg in Fahrtrichtung %s.'" % (tts_modify(stop).replace("'", "\\'"), direction)).encode('utf-8'))96 else:97 os.popen((u"espeak -v mb/mb-de5 -s 40 'Nähxter Halt: %s. Ausstieg in Fahrtrichtung %s.'" % (tts_modify(stop).replace("'", "\\'"), direction)).encode('utf-8'))98 99 if will_stop:100 first_sleep = random.uniform(0, cycle_interval)101 second_sleep = cycle_interval - first_sleep102 time.sleep(first_sleep)103 104 client.set_stop_indicator(args.display, True)105 106 if not args.quiet:107 os.popen("aplay -q %s" % args.stop_jingle)108 109 time.sleep(second_sleep)110 else:111 time.sleep(cycle_interval)112 113 has_stopped = will_stop114 115 print ""116if __name__ == "__main__":...
9028237.py
Source:9028237.py
1import sys23n, T, *t = map(int, sys.stdin.read().split())456def main():7 start = 08 will_stop = T9 running_time = 010 for i in range(1, n):11 cur = t[i]12 if cur < will_stop:13 running_time += cur - start14 else:15 running_time += T16 start = cur17 will_stop = cur + T18 running_time += T1920 return running_time212223if __name__ == "__main__":24 ans = main()
...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!