def play(col, row, n_cols, n_rows): length_tour = 0 chess = Game(n_cols, n_rows) board = Board(n_cols, n_rows) while True: length_tour += 1 chess.set_visited(col, row) positions = chess.look_ahead(col, row) if len(positions) == 0: if length_tour == n_cols * n_rows: print("What a great tour! Congratulations!") else: print("No more possible moves!") print(f"Your knight visited {length_tour} squares!") break board.update(col, row) board.render(col, row, positions) while True: next_position = get_input("Enter your next move: ", "Invalid move!") if not chess.is_explored(*next_position) and contains( next_position, positions): col, row = next_position break else: print("Invalid move!", end=" ")
def authenticate(): # Get client ID and secret from auth.ini config = get_config() config.read('auth.ini') client_id = config.get('credentials', 'client_id') client_secret = config.get('credentials', 'client_secret') client = ImgurClient(client_id, client_secret) # Authorization flow, pin example (see docs for other auth types) authorization_url = client.get_auth_url('pin') print("\n\nGo to the following URL: {0}".format(authorization_url)) #open it up in a new web browser webbrowser.open(authorization_url, new=2, autoraise=True) # Read in the pin, handle Python 2 or 3 here. pin = utilities.get_input("Enter pin code: ") # ... redirect user to `authorization_url`, obtain pin (or code or token) ... credentials = client.authorize(pin, 'pin') client.set_user_auth(credentials['access_token'], credentials['refresh_token']) print("Authentication successful! Here are the details:") print(" Access token: {0}".format(credentials['access_token'])) print(" Refresh token: {0}".format(credentials['refresh_token'])) return client
def get_options(): """ Returns a dictionary of options necessary for the program. """ options = {} should_resume = get_input("Would you like to resume from where you left off or start over?: (r)esume/(s)tart over:", set(["r", "s"]), wait=False) should_resume = should_resume == "r" should_append = should_resume options["resume"] = should_resume options["append"] = should_append return options
def run(self): '''Run the main part of the hangman game''' while self.check_status(): display = Display(self.chances, self.output, self.guessed) display.std_output() user_input = get_input(self.guessed, list(self.output)) guess = Guess(user_input, self.guessed, self.secret.word) index = guess.get_indices() if index: print(f"Letter \"{guess.letter}\" is in the mystery word...") self.output = insert(user_input, index, self.output) else: print( f"Letter \"{guess.letter}\" is NOT in the mystery word...") self.guessed.append(user_input) self.chances -= 1 print(self.print_status())
def play_trick(self, leader): current_trick = trick() # Initialize trick skip_player = -1 if self.alone: skip_player = get_player(self.caller.id + 2) for i in range(leader, leader + 4): # For each player after dealer if get_player(i) == skip_player: continue player = self.players[get_player(i)] # Given player print(player.name + ' is up, cards are: ') num_cards = player.list_cards(self.trump, current_trick.lead) prompt = 'Choose card to play' card_index = get_input(prompt, list(range(num_cards))) card_played = player.hand[card_index] print('\n' + player.name + ' played ' + str(card_played) + '\n') current_trick.add_card(card_played, self.trump) # Add card to trick player.playCard(card_played) # Remove card from hand card_index = current_trick.get_winner() # Index of card in trick player_id = (card_index - (leader + 1)) % 4 # Get player id from play index player = self.players[player_id] # Player with winning card # Get winning team team_zero_win = self.teams[0].is_on_team(player) # Check if team 0 won win_team_index = 0 if team_zero_win: win_team_index = 1 winning_team = self.teams[win_team_index] winning_team.add_trick(current_trick) # Give winning team the trick print('\nTeam ' + str(win_team_index) + ' won the trick \n') return player_id
import sys sys.path.insert(0, "../") from utilities import success, get_input from typing import * from itertools import product input = get_input(whole=True) images = set() for image in input.split("\n\n"): id = int(image.split("\n")[0].split(" ")[1].strip(":")) images.add((id, tuple(image.split("\n")[1:]))) def yield_symmetric_images(image): """Yield the possible rotations of the image.""" for h in (True, False): # horizontal for v in (True, False): # vertical for d in (True, False): # diagonal new_image = list(image) if v: new_image = list(reversed(new_image)) if h: new_image = [row[::-1] for row in new_image]
import sys sys.path.insert(0, "../") from utilities import success, get_input lines = get_input() for i in range(len(lines)): lines[i] = list(lines[i]) def neighbours(x, y): empty = 0 occupied = 0 for xd, yd in ( (1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1), ): xn, yn = x + xd, y + yd if not (0 <= xn < len(lines[0]) and 0 <= yn < len(lines)): continue if lines[yn][xn] == "L": empty += 1
from utilities import get_input, contains from knight import Board, Game import player import computer n_cols, n_rows = get_input("Enter your board dimensions: ", "Invalid dimensions") position = get_input("Enter the knight's starting position: ", "Invalid positions", cols=n_cols, rows=n_rows) col, row = position length_tour = 0 choice = " " while True: choice = input("Do you want to try the puzzle?(y/n) ") if choice == "y" or choice == "n": break print("Invalid choice") if choice == "y": if n_rows < 4 and n_cols < 4: print("No solution exists!") else: player.play(col, row, n_cols, n_rows) else: game = Game(n_cols, n_rows)
def __init__(self): (self.distance, self.metric, self.target) = u.get_input('distance', self.Metrics)
import sys sys.path.insert(0, "../") from utilities import success, get_input input = get_input(as_int=True) target = 2020 saw = set() for value in input: if target - value in saw: success(value * (target - value)) saw.add(value)
import sys sys.path.insert(0, "../") from utilities import success, get_input instructions = get_input() acc = 0 ptr = 0 visited = set() while True: if ptr in visited: success(acc) visited.add(ptr) opt, arg = instructions[ptr].split(" ") if opt == "acc": acc += int(arg) elif opt == "jmp": ptr += int(arg) continue ptr += 1
def __init__(self): (self.weight, self.metric, self.target) = u.get_input('weight', self.Metrics)
import sys sys.path.insert(0, "../") from utilities import success, get_input instructions = get_input(as_int=True) numbers = [] preamble = 25 def adds_up_to(target): for i in range(len(numbers)): for j in range(i + 1, len(numbers)): if numbers[i] + numbers[j] == target: return True return False for n in instructions[:preamble]: numbers.append(n) for n in instructions[preamble:]: if not adds_up_to(n): success(n) numbers.pop(0) numbers.append(n)
def __init__(self): (self.size, self.metric, self.target) = u.get_input('size', self.Metrics)
def find_annotations(content, **options): """ Finds possible annotations in the text and puts them in equations. For each possible annotation, prompts the user for input on whether it is actually an annotation, and (if it is one) on its properties. Returns an updated version of content. """ indicators = [ "When", "Where", "If", "Then", "For", "With", "As", "Throughout", "In", "Over" ] indicators.extend([indicator.lower() for indicator in indicators]) sentence_pat = re.compile(r'([^.!?\s][^.!?]*(?:[.!?](?!\s|$)[^.!?]*)*[.!?]?(?=\s|$))', re.DOTALL) label_pat = re.compile(r'\\(?:label|eqref){(?P<eq_id>eq:.*?)}') eq_range_pat = re.compile(r'\\eqref{(?P<start>eq:(?P<main_name>.*?\..*?\..*?).+?)}\s*--\s*\\eqref{(?P<end>eq:.*?)}') definition_pat = re.compile(r'\$(?P<var_name>.)\$ defined by \\eqref{(?P<eq_id>.*?)}') responses = OrderedDict() doc_start = content.find("\\begin{document}") every_sentence = list(sentence_pat.finditer(content[doc_start:])) num_sentences = len(every_sentence) rem_offset = doc_start start = 0 #set offset and start if options["resume"]: start = options["start"] #go through each sentence for snum, sentence_match in enumerate(every_sentence): #don't start till we get to starting point if snum < start: continue assoc_equations = [] annotation_lines = [] sentence = sentence_match.group() before = "" #this isn't the first sentence, get the previous sentence if snum != 0: before = every_sentence[snum - 1].group() after = "" #this isn't the last sentence, get the next sentence if snum != num_sentences - 1: after = every_sentence[snum + 1].group() sentence = sentence.strip() sentence = re.sub(r'\n{2,}', r'\n', sentence) sectioning = "" #see if the section or subsection is referenced if "this subsection" in sentence: sectioning = "subsection" if "this section" in sentence: sectioning = "section" if "this chapter" in sentence: sectioning = "chapter" #either the seciton or subsection was referenced if sectioning: before = "" sentence = sentence[sentence.find("\\" + sectioning):] line_ind = snum + 2 #keep adding sentences to after while (line_ind < num_sentences and ("\\" + sectioning) not in after): after = ''.join([after, every_sentence[line_ind].group()]) line_ind += 1 to_join = [] after_lines = after.split("\n") line_ind = 0 current = after_lines[line_ind] #keep adding lines until the start of the next section while (("\\" + sectioning) not in current and line_ind + 1 < len(after_lines)): to_join.append(current) line_ind += 1 current = after_lines[line_ind] to_join.append(current) after = '\n'.join(to_join) found_range = False #include ranges of equations if they are referenced for match in eq_range_pat.finditer(sentence): found_range = True current = snum + 2 start_id = match.group("start") end_id = match.group("end") main_name = match.group("main_name") #keep adding to after until we have the whole range while (current < num_sentences and r'\label{' + end_id + '}' not in after): to_add = every_sentence[current].group() #only add if it has a relevant equation in it if r'\label{' in to_add: if main_name not in to_add: to_add = "" after = ''.join([after, to_add]) current += 1 before = "" start_loc = sentence.find(r'\begin{equation}\label{' + start_id + '}') #first equation is in this sentence if start_loc != -1: sentence = sentence[start_loc:] else: start_loc = after.find(r'\begin{equation}\label{' + start_id + '}') #found an equation range, cut out after after last end equaiton if found_range: after = after[:after.rfind(r'\end{equation}') + len(r'\end{equation}')] #if variable is defined by an equation, replace eqref with text for match in definition_pat.finditer(sentence): eq_id = match.group("eq_id") eq_pat = re.compile(r'\\begin{equation}\\label{' + eq_id + r'}.*?\n(?P<content>.*?)\n?\\end{equation}', re.DOTALL) search_text = before eq_match = eq_pat.search(search_text) current = snum - 2 #keep looking backward until we have a match while not eq_match and current > 0: search_text = ''.join([every_sentence[current].group(), search_text]) eq_match = eq_pat.search(search_text) current -= 1 #make sure we found something if eq_match: sentence = sentence.replace(r'\eqref{' + eq_id + '}', eq_match.group("content").strip().rstrip(".")) context = before + "\n" + sentence + "\n" + after #find the equation ids of all the equations that may be associated with this annotation for label_match in label_pat.finditer(context): assoc_equations.append(label_match.group("eq_id")) #take out the eq labels from the range if they exist if found_range: assoc_equations = assoc_equations[2:] seen = set() indicator_found = False #go through each indicator for indicator in indicators: #only reset the tracker if we haven't found an indicator yet if not indicator_found: ind_loc = 0 #go through each line in the sentence so we can print out the one with the indicator for line in sentence.split("\n"): #store each line that may contain an annotation if (line not in seen and (" " + indicator + " " in line) or (indicator + " " in line and line.startswith(indicator)) or (" " + indicator + ". " in line)): annotation_lines.append("{0}: {1}".format(indicator, line.lstrip())) indicator_found = True seen.add(line) #increment tracker until we find first indicator if not indicator_found: ind_loc += len(line) + 1 #don't do anything else if there aren't any indicators in the sentence if not indicator_found: continue #ask user about each possible annotation for line in annotation_lines: to_write = "{0}{1}".format(_create_comment_string(responses), snum) result = _check_and_quit(make_annotation_query(line, context, assoc_equations), to_write, content, options) #map each InputResponse to the sentence number for response in result: responses[response] = snum begin_loc = sentence_match.start() + rem_offset + ind_loc end_loc = sentence_match.end() + rem_offset before = (begin_loc, end_loc) #if there is an end equation at the beginning of the sentence, move past it if content[begin_loc:].strip().startswith(r'\end{equation}'): begin_loc = content.find(r'\end{equation}', begin_loc, end_loc) + len(r'\end{equation}') #if an equation is in the sentence, only remove until there if r'\begin{equation}' in content[begin_loc:end_loc]: end_loc = content.find(r'\begin{equation}', begin_loc, end_loc) #fragment has an index in it, stop before then if r'\index' in content[begin_loc:end_loc]: end_loc = content.find(r'\index', begin_loc, end_loc) - 1 newline_loc = content.find('\n', begin_loc, end_loc) #first line of the fragment is very short if 0 < newline_loc - begin_loc < 5: #and ending character is }, probably shouldn't be included if content[newline_loc - 1] == "}": begin_loc = newline_loc + 1 should_delete = get_input("Would you like to delete this sentence (fragment):\nSTART\n{0}\nEND\n(y/n)".format(content[begin_loc:end_loc]), valid=set("ynq"), wait=False) #user wants to quit if should_delete == "q": to_write = "{0}{1}".format(_create_comment_string(responses), snum) _quick_exit(to_write, content, options) should_delete = should_delete == "y" #we need to delete the sentence (at least up to the first equation) if should_delete: content = content[:begin_loc] + "~~~~REM_START~~~~" + content[begin_loc:end_loc] + "~~~~REM_END~~~~" + content[end_loc:] rem_offset += len("~~~~REM_START~~~~") rem_offset += len("~~~~REM_END~~~~") #shouldn't delete sentence, ask about keywords else: should_add_word = get_input("Would you like to add a keyword? (y/n)", valid=set("yn"), wait=False) #user wants to quit if should_add_word == "q": to_write = "{0}{1}".format(_create_comment_string(responses), snum) _quick_exit(to_write, content, options) should_add_word = should_add_word == "y" #user wants to add a keyword if should_add_word: new_keyword = get_input("Enter the new keyword:") indicators.append(new_keyword) indicators.append(new_keyword.title()) store_current = get_input("Would you like to store an annotation on this line? (y/n)", valid=set("yn"), wait=False) #user wants to quit if store_current == "q": to_write = "{0}{1}".format(_create_comment_string(responses), snum) _quick_exit(to_write, content, options) store_current = store_current == "y" #user wants to store an annotation on this line if store_current: to_write = "{0}{1}".format(_create_comment_string(responses), snum) result = _check_and_quit(make_annotation_query("", context, assoc_equations), to_write, content, options) #map each InputResponse to its sentence number for response in result: responses[response] = snum comment_str = _create_comment_string(responses) content = comment_str + content comment_insertion_pat = re.compile(r'^(?:\d+:)?{(?P<eq_id>.*?)}% *\\(?P<name>.*?){(?P<annotation>.*?)}(?P<between>.*?)(?P<equation>\\begin{equation}\\label{(?P=eq_id)}.*?\\end{equation})', re.DOTALL) #as long as there is a match in content, keep replacing while comment_insertion_pat.match(content): content = comment_insertion_pat.sub(_insert_comment, content) content = content[1:] #take out empty line removal_fix_pat = re.compile(r'(\s*)~~~~REM_START~~~~(.*?)\n(\s*)\\end{equation}') content = removal_fix_pat.sub(r'\1\2\n\3\\end{equation}', content) removal_fix_pat = re.compile(r'\\index{(.*?)}\s*~~~~REM_END~~~~') content = removal_fix_pat.sub(r'~~~~REM_END~~~~\\index{\1}', content) removal_pat = re.compile(r'~~~~REM_START~~~~.*?~~~~REM_END~~~~', re.DOTALL) content = removal_pat.sub('', content) save_state(comment_str, content, options) current_loc = 0 in_eq = False start_frag = True fragment = [] sectioning_pat = re.compile(r'\\((?:sub)?section|paragraph|label|index)') #go through each line, building the fragments as we go #to remove a fragment, perform one sub with empty string for line in content.split("\n"): #starting fragment, set start location if start_frag: start_frag = False fragment = [] does_start_eq = line.strip().startswith(r'\begin{equation}') is_sectioning = bool(sectioning_pat.search(line)) #end of fragment if starting eq or index if does_start_eq or is_index or is_sectioning: if does_start_eq: in_eq = True elif is_sectioning: frag_start = True #only ask to remove if fragment is not empty if any(f.strip() for f in fragment) and fragment: print("\n") should_remove = get_input("Would you like to delete this fragment?\nSTART\n{0}\nEND\n(y/n)".format('\n'.join(fragment)), valid=set("yn"), wait=False) #quit if user wants if should_remove == "q": _quick_exit(comment_str, content, options) should_remove = should_remove == "y" #sub out the fragment one time if should_remove: content = remove_one(fragment, content, current_loc) start_frag = True #not in equation if not in_eq: #not in index either, add to line if not is_index: fragment.append(line) #we're exiting an equation if line.strip().startswith(r'\end{equation}'): in_eq = False current_loc += len(line) #delete the save file when we're done try: os.remove(SAVE_FILE) except OSError: print(("THE SAVE FILE COULD NOT BE REMOVED. PLEASE REMOVE IT " "MANUALLY WITH rm .save")) print("DONE") return content
import sys sys.path.insert(0, "../") from utilities import success, get_input numbers = list(map(int, get_input(whole=True).split(","))) positions = {} for i, n in enumerate(numbers): positions[n] = [i] n = 0 i = len(numbers) while i < 30000000 - 1: if n not in positions: positions[n] = [i] else: positions[n].append(i) if len(positions[n]) == 1: n = 0 else: n = positions[n][-1] - positions[n][-2] i += 1 success(n)
def make_annotation_query(line, context, assoc_eqs): """ Queries the user for information about the possible annotation. Will ask the user a series of questions about the annotation and returns a list of InputResponse tuples containing the result of the query. If the annotation was incorrectly identified (i.e. it is not an annotation) a list containing an empty tuple will be returned. """ to_join = context.split("\n") #place -----> marker in front of vital line for num, l in enumerate(to_join): if l.strip() and l == line[line.find(": ") + 2:]: to_join[num] = "----->" + l context = "\n".join(to_join) yes_no_responses = set(["y", "n", "yes", "no"]) print("\n----------------------------------------\nIdentified the following:") print(line) print("") print("In the context of:") print(context) print("----------------------------------------\n") valid_check = get_input("Is this an annotation? (y/n or q to quit):", yes_no_responses, wait=False) #quit if the user types q if valid_check == "q": return ["QUIT"] #not actually an annotation, return empty if valid_check == "n" or valid_check == "no": return [()] to_return = [] num_annotations = get_input("Enter the number of annotations on the line (1-9):", set(["1","2","3","4","4","5","6","7","8","9"]), wait=False) #user wants to quit if num_annotations == "q": return ["QUIT"] num_annotations = int(num_annotations) #create however many annotations there are for i in range(num_annotations): annotation_type = get_input("Enter the type of annotation: (c)onstraint, (s)ubstitution, (n)ote, na(m)e, (p)roof:", set(["c", "s", "n", "m", "p"]), wait=False) #quit if user presses q if annotation_type == "q": return ["QUIT"] annotation = get_input("Enter the actual text of the annotation:") print("\nThe predicted associated equations are:") #print out the equation label of each associated equation for eq in assoc_eqs: print("\t{0}".format(eq)) correct_eqs = get_input("Are these correct? (y/n):", yes_no_responses, wait=False) #if the equations are incorrect, find out if we need to add equations or remove them while correct_eqs != "y" or len(assoc_eqs) == 0: #quit if the user types q if correct_eqs == "q": return ["QUIT"] add_remove = get_input("Would you like to add, remove, or select equations?: (a)dd/(r)emove/(s)elect:", set(["a", "r", "s"]), wait=False) #quit if user presses q if add_remove == "q": return ["QUIT"] #inform user that they need an equation with the annotation if len(assoc_eqs) == 0: print("Must have at least one associated equation.") add_remove = "a" #display adding menu if add_remove == "a": eq_label = get_input("Enter the label for the equation you would like to add:", preserve_case=True) assoc_eqs.append(eq_label) print("Equation added") #display removal menu if add_remove == "r": #user can't remove equations if there aren't any if len(assoc_eqs) == 0: print("There are no equations to remove") else: _print_eqs(assoc_eqs) to_remove = get_input("What equation(s) would you like to remove (separate with commas):", set(map(str, xrange(len(assoc_eqs) + 1))), list=True) to_remove = _parse_list(to_remove) #remove each equation in reverse for rem_ind in sorted(to_remove, reverse=True): del assoc_eqs[rem_ind] print("Equation(s) removed") #display selection menu if add_remove == "s": #can't select if there are no equations if len(assoc_eqs) == 0: print("There are no equaitons to select") else: _print_eqs(assoc_eqs) to_select = get_input("What equation(s) would you like to select (separate with commas):", set(map(str, xrange(len(assoc_eqs) + 1))), list=True) to_select = _parse_list(to_select) assoc_eqs[:] = [eq for i, eq in enumerate(assoc_eqs) if i in to_select] print("Equation(s) selected") print("The predicted associated equations are:") #print out the equation label of each associated equation for eq in assoc_eqs: print("\t{0}".format(eq)) correct_eqs = get_input("Are these correct? (y/n):", yes_no_responses, wait=False) print("Annotation added\n---------------------------------------------") to_return.append(InputResponse(annotation_type, annotation, frozenset(assoc_eqs))) return to_return
import sys sys.path.insert(0, "../") from utilities import success, get_input wait = int(get_input()[0]) times = get_input()[1].split(",") minimum_time = float("+inf") minimum_bus = 0 for time in times: if time == "x": continue time = int(time) if time - wait % time < minimum_time: minimum_time = time - wait % time minimum_bus = time success(minimum_time * minimum_bus)
import sys sys.path.insert(0, "../") from utilities import success, get_input from itertools import product memory = {} mask = "X" * 36 ones = (1 << 36) - 1 for inst in get_input(): opt, val = inst.split(" = ") if opt == "mask": mask = val else: index = int(opt.split("[")[1].strip("]")) number = int(val) floats = [] for i, c in enumerate(reversed(mask)): if c != "X": if c == "1": index = index & (ones ^ (1 << i)) | 1 << i else: floats.append(i) for p in product((0, 1), repeat=len(floats)): v = index
def __init__(self): (self.temperature, self.metric, self.target) = u.get_input('temperature', self.Metrics)
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization, Conv2D, MaxPool2D, MaxPooling2D from imblearn.over_sampling import RandomOverSampler from imblearn.under_sampling import RandomUnderSampler import json import utilities as ut import models_to_test as mtt logging.info("Running model: '" + args.model_name + "'") if args.tobreak == True: logging.warning("Only using a small subset of data!") logging.info("Number of epochs: " + args.epochs) logging.info("Saving output to: " + args.save_dir) ## Read in XY data tstart = time.time() X, Y = ut.get_input(tobreak=args.tobreak) X = X / 255. tend = time.time() logging.info("Time to read in data: {0:.1f} s.".format(tend - tstart)) logging.debug("Current shapes: " + str(X.shape) + ", " + str(Y.shape)) ## Undersample the IDC(-) data to get even input set: Xbal, Ybal = ut.balance_pos_neg(X, Y) logging.info("*** Describe balanced data ***") ut.describe_data(Xbal, Ybal) ## Shuffle XY data Xs, Ys = ut.shuffle_input(Xbal, Ybal) logging.info("*** Describe shuffled data ***") ut.describe_data(Xs, Ys)
from utilities import success, get_input def fill_ones(ones): """Too lazy to do a proper function :).""" if ones in (0, 1): return 1 elif ones == 2: return 2 elif ones == 3: return 4 elif ones == 4: return 7 inst = sorted(get_input(as_int=True)) deltas = [1] for i in range(len(inst) - 1): deltas.append(inst[i + 1] - inst[i]) deltas.append(3) total = 1 ones = 0 for i in range(len(deltas)): if deltas[i] == 1: ones += 1 else: total *= fill_ones(ones)
import sys sys.path.insert(0, "../") from utilities import success, get_input input = get_input() ids = list() for line in input: row = 0 col = 0 lo = 0 hi = 128 for c in line[:7]: avg = (lo + hi) // 2 if c == "F": hi = avg else: lo = avg row = lo lo = 0 hi = 8 for c in line[7:]: avg = (lo + hi) // 2 if c == "L": hi = avg else: lo = avg col = lo