text
stringlengths
37
1.41M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 8 10:27:14 2018 @author: MariusD """ #%% def bubble(lst): for j in range(0, len(lst) - 1): for i in range(0, len(lst) - j - 1): if lst[i] > lst[i + 1]: temp = lst[i] lst[i] = lst[i + 1] lst[i + 1] = temp #%% def merge_sort(lst): if len(lst) <= 1: return lst middle = len(lst) // 2 left = lst[:middle] right = lst[middle:] return merge(merge_sort(left), merge_sort(right)) #%%
import unicode import board from game_state import GameState # Initialize GameState to key track if the game has ended. game_state = GameState() print(" Welcome to WeThinkCode (Group 26) MineSweeper.\n\n" "-----------------------------------------------------------\n" "| Rules:" + (" " * 50) + "|\n" "-----------------------------------------------------------\n" f"| * Number of rows must be greater then or equal to {board.MIN_NUMBER_COLUMNS}." + (" " * 4) + "|\n" f"| * Number of columns must be greater then or equal to {board.MIN_NUMBER_ROWS}. |\n" "| * Rows " + unicode.ARROW_DOWN + (" " * 48) + "|\n" "| * Columns " + unicode.ARROW_RIGHT + (" " * 45) + "|\n" "-----------------------------------------------------------\n") columns = int(input("Enter the number of columns: ")) rows = int(input("Enter the number of rows: ")) if columns < board.MIN_NUMBER_COLUMNS and rows < board.MIN_NUMBER_ROWS: print(f"Please re-enter the correct number of rows or columns.") exit() game_board = board.generate(columns, rows) display_board = board.generate(columns, rows, True) def copy_box(board: list, row: int, column: int, value: int) -> list: board[row][column] = value return board while game_state.state(): print(board.display(display_board)) selected_row = int(input("Select row: ")) if board.row_exists(game_board, selected_row) is False: print(f"The row selected ({selected_row}) row does not exists.\n\n") continue selected_column = int(input("Select column: ")) if board.column_exists(game_board, selected_column) is False: print(f"The column ({selected_column}) selected does not exists.\n\n") continue opened_box = board.make_move(game_board, selected_row, selected_column) if board.is_bomb(opened_box): print(board.display(game_board)) print(f"Sorry you have opened a bomb " + unicode.BOOM) exit() display_board = copy_box(display_board, selected_row, selected_column, opened_box)
def jogar(): import random print("*********************************") print("Bem-vindo no jogo de Adivinhação!") print("*********************************") numero_secreto = random.randrange(1,101) total_de_tentativas = 0 pontos = 1000 print("""Qual nível de dificuldade? (1) Fácil (2) Médio (3) Difícil """) nivel = int(input(">> ")) if (nivel == 1): total_de_tentativas = 20 elif (nivel == 2): total_de_tentativas = 10 else: total_de_tentativas = 5 for rodada in range(1,total_de_tentativas+1): print("Tentativas: {} de {} ".format(rodada, total_de_tentativas)) chute = int(input("Digite um número entre 0 e 100: ")) print("Você digitou", chute) acertou = chute == numero_secreto maior = chute > numero_secreto if (acertou): print("Você acertou!") print("Total de pontos: ", pontos) break else: pontos_perdidos = numero_secreto - chute pontos -= abs(pontos_perdidos) if (maior): print("Você errou! O seu chute foi maior que o número secreto.") else: print("Você errou! O seu chute foi menor que o número secreto.") print('Fim do jogo. O número secreto era o ', numero_secreto) if (__name__ == "__main__"): jogar()
class Calc(object): display = "" curnumber = None numbers = None operations = None def __init__(self): self.operations = [] self.numbers = [] self.curnumber = "" def add_number(self): self.numbers.append(int(self.curnumber)) self.curnumber = "" def clear(self): self.curnumber = "" self.operations = [] self.numbers = [] self.display = "" def press(self, symbol): if symbol.lower() == 'c': self.clear() return self.display += symbol if symbol.isdigit(): self.curnumber += symbol elif symbol == '+': self.operations.append("+") self.add_number() elif symbol == '=': self.add_number() while len(self.operations) > 0: op = self.operations.pop() left, right = self.numbers.pop(), self.numbers.pop() if op == '+': res = left + right self.display = str(res) self.curnumber = str(res) self.numbers.append(res)
def max_list_recursive(lst): """ recursive method to find maximum in a list :param: lst - list with > operator defined :return: max value """ pass # @todo -fix this def sum_list_recursive(lst): """ recursive method to find sum of a list :param lst: :return: sum of list, 0 if empty """ pass # @todo -fix this def calc_seq(index): """ Write a function `calc_seq` that returns the value of a sequence at a given index. The sequence is defined as the prior element minus the second and third prior elements . The 0th element returns 0, element 1 returns 1, and element 2 returns 2. The calculation for element 3 returns 1 (i.e. 2-1-0=1) The first seven elements are: element: 0 1 2 3 4 5 6 7 ... value : 0 1 2 1 -2 -5 -4 3 ... :param index: :return: """ pass # @todo -fix this
import math """ Methods used to generate data files, provided here to allow for testing after reading files """ def make_csv_data(nsteps): iv=[] x=[] y=[] for i in range(0,nsteps): iv.append(i) x.append(2.0*math.pi*i/nsteps) y.append(math.cos(x[i])) return iv,x,y def make_binary_data(nsteps): x=[] y=[] iv=[] for i in range(0,nsteps): iv.append(i) x.append(6.0*math.pi*i/nsteps) y.append(math.sin(x[i])*math.cos(x[i])) return x,y,iv def make_sample_binary_data(nsteps): x=[] y=[] for i in range(0, nsteps): x.append(i) y.append(i ** 3) return x,y
""" Demo the cost of recursion for Fibonacci sequences """ class FibonacciDemo: def __init__(self): self.loop_count = 0; self.rec_count = 0; def fib_loop(self, n): a = 0 b = 1 while (n > 0): oldA = a a = b b = oldA + b n-=1 self.loop_count+=1 return a def print_level(self, level, string): for i in range(level): print("\t",end='') print(" l({:3d}) r({:3d}) >{}".format( level,self.rec_count,string)) def fib_recursion(self, n, level): self.rec_count+=1 if (n < 1): self.print_level(level, " fibR(" + str(n) + ")"); return 0 if (n == 1): self.print_level(level, " fibR(" + str(n) + ")"); return 1 self.print_level(level, "fibR({:3d}) = fibR({:3d}) + fibR({:3d})".format(n, n - 1, n - 2)); a = self.fib_recursion(n - 1, level + 1) b = self.fib_recursion(n - 2, level + 1) self.print_level(level, " fibR({:3d}) = {:3d} + {:3d}".format(n, a, b)); return a + b if __name__ == '__main__': for i in range(8,9): # Reset counters for each top level call fib = FibonacciDemo() print("fib["+str(i) + "] = loop:" + str(fib.fib_loop(i)) + " cnt(" + str(fib.loop_count) + ") recursion:" + str(fib.fib_recursion(i, 0)) + " (" + str(fib.rec_count) + ") ")
""" EXCEPTION Program 3 module tries to catch various exceptions. As is written, the main block raises three exceptions. Rewrite three functions so that they handle specific exceptions. Catch the exception and print the error message. Each shall also have catch all exception handler with the generic error message. If the program does not crash, then you have succeeded. @author <Elijah Weske> """ import sys def catch_file_not_found_error(filename): try: f = open(filename, 'r') except FileNotFoundError as e: print('Exception caught: File not found.') except Exception as e: print('Exception caught:', e) def catch_division_by_zero_error(dividend, divisor): try: if divisor == 0: raise ValueError return dividend / divisor except ValueError: print('Exception Caught: Value Error - cannot divide by 0.') except Exception as e: print('Exception caught:', e) def catch_index_error(list, index): try: if len(list) <= index: raise IOError('Index out of range.') return list[index] except IOError as e: print('Exception caught:', e) except Exception as e: print('Exception caught:', e) if __name__ == '__main__': catch_file_not_found_error(sys.argv[0]) catch_file_not_found_error('non_existing_file') # exception error catch_division_by_zero_error(2, 3) catch_division_by_zero_error(2, 0) # exception error catch_index_error([1, 2, 3], 0) catch_index_error([1, 2, 3], 2) catch_index_error([1, 2, 3], 3) # exception error
total = 1000 def IsPythagorean(a, b, c): return (a**2 + b**2) == c**2 def AddsToTotal(a, b, c): return a + b + c == total def Find(): for i in range(1, total): for j in range(i, total): for k in range(j, total): # print '{} {} {}'.format(i,j,k) if (IsPythagorean(i,j,k) and AddsToTotal(i,j,k)): print i*j*k return Find()
maximum = 20 divisors = range(1, maximum)[::-1] answer = maximum nope = False while(True): for divisor in divisors: if (answer % divisor != 0): nope = True break else: nope = False if (nope): answer += 1 else: break print answer
import os path = input("What is the path you would like to go to: ") while True: os.chdir(path) os.makedirs(input("What directory would you like to make")) if input("Would you like to make another directory (yes/no): ") == "yes": if input("Would you like to change the path (yes/no): ") == "yes": path = input("What is the path you would like to go to: ") else: quit()
#1 for x in range(0,100,2): print(x + 1, end=" ") #2 kaboom_string = "KABOOM" for x in kaboom_string: print((x + " ") * 3, end="") #3 string_3 = "askaliceithinkshe'llknow" for x in range(0, len(string_3), 2): print(string_3[x:x+1], end=" ") #4 # ? #5 listoflists = [['mn', 'pa', 'ut'], ['b', 'p', 'c'], ['echo', 'charlie', 'tango']] labels = {"state": "US State Abbr:", "element": "Chemical Element:", "alpha": "Phonetic Call:"} for x in range(0,len(listoflists)): print(list(labels.values())[x] + " " + listoflists[x][0].upper()) print(list(labels.values())[x] + " " + listoflists[x][1].upper()) print(list(labels.values())[x] + " " + listoflists[x][2].upper())
# Factorials ''' def factorial(number): if number == 1: print(number, " = ", end=" ") return 1 else: print(number, " * ", end=" ") return number * factorial(number-1) print(factorial(int(input('Which number would you like the factorial of? ')))) ''' # Pascal's Triangle def pascal(number): if number == 0: return [1] else: line = [1] previous_line = pascal(number-1) for i in range(len(previous_line)-1): line.append(previous_line[i] + previous_line[i+1]) line += [1] return line x_range = int(input("How many levels would you like to see? ")) # 27 fills up the whole page for x in range(0, x_range): row = str(pascal(x))[1:][:-1].center(200) row = row.replace(",", " ") print(row) ''' Extension Exercise: Use Pascal's Triangle to calculate Fibonacci numbers (These are calculated by adding together all numbers in a diagonal starting from the right side up until you hit the left) '''
# This is a guess the number game # You have 5 tries or you'll lose the game # The game tracks wins/loses ratio __author__ = 'jaime.alv.fdz@gmail.com' import random win_global = 0 lose_global = 0 name_global = '' def greetings(): global name_global print('Hi. What is your name?') name = input() while True: if name != '': print('Hello, ' + name + ". Nice to meet you!") print('Do you want to play a guessing game?(y/n)') name_global = name yes_no() else: print('That is not a valid name. Please, tell me your name') name = input() def yes_no(): yes = ['y', 'ja', 'yes', 'sí', 'si', 'oui'] prime = input() prime = prime.lower() for i in yes: if i == prime: game() else: print('Have a nice day ' + name_global + '!') quit() def check_input(): while True: print('Can you guess it?') number = input() if number.isdigit(): return int(number) def game(): global win_global global lose_global print("I'm thinking of a number between 1 and 50") guess_number = random.randint(1, 50) for tries in range(1, 6): guess = check_input() if guess > guess_number: print('Your guess is to high') elif guess < guess_number: print('Your guess is too low') else: break if guess == guess_number: print('Good job ' + name_global + '. You needed ' + str(tries) + ' tries.') win_global += 1 else: print('Sorry. It was ' + str(guess_number)) lose_global += 1 restart() def restart(): print('This is the score:') print('Wins: ' + str(win_global)) print('Loses: ' + str(lose_global)) print('Do you want to play again?(y/n)') yes_no() if __name__ == "__main__": greetings()
#this comment will be in GitHub Repository #a=10 input simple assign data,Keyboard entered data, data from file or DB #b=20 # Variable - Container which contains data for Processing (temp) its logical name for memory address a=int(input("Please enter the first number : ")) b=int(input("Please enter the second number : ")) print("A address is : ", id(a), "B Address is : ", id(b)) div=a/b # wrote logice to do some process print ("Divide value is ", div) # Output """ each data have to be stored in memory - memory address - 34534534534534 - a 45345345345345345 - b """
def take(count, iterable): counter = 0 for item in iterable: if counter == count: return counter += 1 yield item def run_take(): items = range(50) for item in take(40, items): print(item) if __name__ == '__main__': run_take()
X = str(input('')) if 'H' in X: print('YES') elif 'Q' in X: print('YES') elif '9' in X: print('YES') else: print('NO')
class Course: def __init__(self, grade, credits, name = "N/A"): self.grade = score[grade] self.letter = grade self.credits = credits self.name = name score = { 'A' : 4.000, 'A-': 3.667, 'B+': 3.333, 'B' : 3.000, 'B-': 2.667, 'C+': 2.333, 'C' : 2.000, 'C-': 1.667, 'D+': 1.333, 'D' : 1.000, 'D-': 0.667, 'F' : 0.000 } spring2018 = [ Course('A', 4, "Operating Systems"), Course('B', 4, "Algorithms"), Course('A-', 4, "GIS"), Course('A-', 4, "Finite Mathematics") ] def gpa(semester): total_score = 0 total_credits = 0 for course in semester: score = course.grade * course.credits total_score += score total_credits += course.credits gpa = total_score / total_credits return gpa print (gpa(spring2018))
import csv import codecs # def write_to_csv(datalist, header): # pass def write_data(datalist, header, file_name='data.csv'): # 指定编码为 utf-8, 避免写 csv 文件出现中文乱码 with codecs.open(file_name, 'w+', 'utf-8') as csvfile: # filednames = ['书名', '页面地址', '图片地址'] writer = csv.DictWriter(csvfile, fieldnames=header) writer.writeheader() for data in datalist: print(data) try: writer.writerow({'书名':data, '页面地址':data, '图片地址': data}) except UnicodeEncodeError: print("编码错误, 该数据无法写到文件中, 直接忽略该数据") print('将数据写到 ' + file_name + '成功!')
import numpy as np def GrahamEvaluate(point_list, point): """ evaluate the addition of a point to a point_list for a Graham Scan if point_list doesn't contain at least 2 values, then add the point and return otherwise, evaluate if the point, together with theh last 2 points makes a clockwise, counter-clockwise, or colinear. If clockwise, add the point and done. If CCW, remove the last point, and call function again if colinear, replace the last point with the current one """ # step 1: check edge cases if len(point_list) == 0: point_list.append(point) return if point == point_list[-1]: return if len(point_list) < 2: point_list.append(point) return # step 2: calculuate cross product formed by new point and last 2 points prev_1, prev_2 = point_list[-2], point_list[-1] cross_pod = (prev_2[0] - prev_1[0]) * (point[1] - prev_1[1]) - (prev_2[1] - prev_1[1]) * (point[0] - prev_1[0]) # step 3: evalute what to do if cross_pod > 0: point_list.append(point) return elif cross_pod == 0: point_list.pop(-1) point_list.append(point) return else: point_list.pop(-1) return GrahamEvaluate(point_list, point) return def calculate_slope(point_1, point_2, epsilon=0): """ calculate the slope between 2 points """ dy = point_1[1] - point_2[1] dx = point_1[0] - point_2[0] + epsilon return dy / dx def GrahamScan(points): """ perform the Graham scan (https://en.wikipedia.org/wiki/Graham_scan) to create a convex hull around a set of points Inputs: points - a Nx2 numpy array of N 2-dimensional points Outputs: conv_points - a nx2 numpy array of n 2-dimensional points that make up the outline of the convex hull """ # step 1: find point with yowest x-value # in case of multiple such points, find one with lowest y-value lowest_value = points[:,0].min() sub_points = points[points[:,0]==lowest_value,:] ind = np.argmin(sub_points[:,1]) lowest_point = sub_points[ind,:] # step 2: sort points by angle to lowest point # since we are comparing to the leftmost point, this is equivalent to sorting # with respect ot angle with the point # to avoid division by 0 error, we add epsilon = 1e-6 to division epsilon = 1e-6 slopes = (points[:,1] - lowest_point[1]) / (epsilon + points[:,0] - lowest_point[0]) idx = np.argsort(slopes) point_order = points[idx,:] # step 3: put together list lowest_point = (lowest_point[0], lowest_point[1]) point_list = [lowest_point] for point in point_order: point = (point[0], point[1]) GrahamEvaluate(point_list, point) # step 4: make sure that the line connects back to the starting point if point_list[-1] != lowest_point: point_list.append(lowest_point) point_list = np.array(point_list) return point_list def get_perpendicular_vector(line): """ find unit vector perpendicular to a line """ point_1, point_2 = line if point_2[0] == point_1[0]: perp_unit = np.array([1,0]) elif point_2[1] == point_1[1]: perp_unit = np.array([0,1]) else: slope = (point_2[1]-point_1[1]) / (point_2[0] - point_1[0]) perp = np.array([1, -1/slope]) perp_unit = perp / np.sqrt(np.sum(np.square(perp))) return perp_unit def shift_line(line, points, shift=0.02): """ Shift a line away from a set of points by some fraction The function finds the point further from the line, and shifts it by a fraction of that distance Requires that all points be on one side of a line to work correctly Inputs: line - a tuple of 2 2-dimensional points that make a line points - a Nx2 numpy array of points shift - the fraction by which to shift the line Outputs: shift_line - a tuple of 2 2-dimensional points that make a shifted line """ # step 1: Get unit vector perpendicular to the line point_1, point_2 = line perp_unit = get_perpendicular_vector(line) # step 2: get direction vector of points to 1 point in the line distance = np.copy(points) distance[:,0] = distance[:,0] - point_1[0] distance[:,1] = distance[:,1] - point_1[1] # step 3: use dot product, to get distance perpendicular to line projection = distance[:,0] * perp_unit[0] + distance[:,1] * perp_unit[1] # step 4: make sure that all points are in the right direction, and get maximum distance epsilon = np.abs(projection).max() * 1e-5 assert (projection.min() >= -epsilon) or (projection.max() <= epsilon) if projection.min() >= -epsilon: distance = projection.max() else: distance = projection.min() # step 5: shift line by correct amount shift_vector = -distance * perp_unit * shift point_1 = point_1 + shift_vector point_2 = point_2 + shift_vector shift_line = (point_1, point_2) return shift_line def make_arc(line_1, line_2, count=10, contain_ends=False): """ create an arc connection the end points of 2 lines Inputs: line_1 - the point whose end the arc starts at line_2 - the point whose beginning the arc starts at count - the number of points in the arc contain_ends - whether to contain the end points in the arc. Default: False Ouptuts: arc - a line of points forming the arc """ if not contain_ends: count += 2 # step 1: find the 2 slopes slope_1 = calculate_slope(line_1[0], line_1[1], epsilon=1e-6) slope_2 = calculate_slope(line_2[0], line_2[1], epsilon=1e-6) # step 2: handle edge cases start = line_1[1] end = line_2[0] if np.array_equal(start, end): return [start] if slope_1 == slope_2: return [start, (start+end)/2, end] # step 3: create a quadratic parametric equation that connects the two lines # while preserving the slope x0, y0 = start x1, y1 = end a0 = x0 b0 = y0 a1 = (2*slope_2*(x1-x0) - 2*(y1-y0)) / (slope_2-slope_1) b1 = slope_1*a1 b2 = y1 - y0 - slope_1*a1 a2 = x1 - x0 - a1 tvals = np.linspace(0,1,count) if not contain_ends: tvals = tvals[1:-1] xvals = a0 + a1 * tvals + a2 * np.square(tvals) yvals = b0 + b1 * tvals + b2 * np.square(tvals) arc = [(xval, yval) for xval, yval in zip(xvals, yvals)] return arc def ExpandBorder(points, shift=0.02): """ Often a minimally drawn border is too tight; some points lie exactly on the border, and edges are sharp This function shifts the borders out by a small amount and curves the edges Inputs: points - the points that make up the border shift - what fraction to shift out by Outputs: border_points - the points that make up the new border """ # Step 1: Break down the border into a set of lines Lines = [(points[i], points[i+1]) for i in range(len(points)-1)] # Step 2: Shift outwards the lines Lines = [shift_line(line, points, shift=shift) for line in Lines] # Step 3: Add arcs between edges of lines Arcs = [make_arc(line_1, line_2) for line_1, line_2 in zip(Lines[:-1], Lines[1:])] Arcs.append(make_arc(Lines[-1], Lines[0], contain_ends=True)) border_items = [item for Line, Arc in zip(Lines, Arcs) for item in (Line, Arc)] border_points = np.array([point for item in border_items for point in item]) return border_points def ShiftedGrahamScan(points, shift=0.1): point_list = GrahamScan(points) border = ExpandBorder(point_list, shift=shift) return border
import numpy as np import pandas as pd from Modules import file_navigation """ This is a python module for reading in the raw and embedded data values This is here to ensure that all other modules and notebooks only call the functions here, instead of writing their own """ def read_embedding_data(dataset, age_cutoff=-1, translabels=False, usecols=[], colnames=[]): """ read in already calculated embedding data the function merely exists to not have to remember location of the file Inputs: dataset - name of dataset to read age_cutoff - whether to remove cells below a certain age. Default: -1, only works if value >=0 translabels - to use the more complete transcriptioal_labels file instead of the labels file. Default: False usecols - to use only a certain subset of labels. Default: [] colnames - names to use for labels. Default: [] Outputs: df_embed - pandas dataframe of embedding data. Rows are cells with cell type labels """ # define keyword arguments kwargs = {'sep':'\t', 'header':0, 'index_col':0} # read in embedded data fname = 'Mapping/Embeddings/%s-tpm.tsv' % dataset df_embedding_tpm = pd.read_csv(fname, **kwargs) # read in labels if translabels: fname = 'Datasets/%s-transcriptional_labels.tsv' % dataset else: fname = 'Datasets/%s-labels.tsv' % dataset df_labels = pd.read_csv(fname, na_values='Other', **kwargs) if age_cutoff >= 0: df_labels = df_labels.loc[df_labels.Age>age_cutoff] df_embedding_tpm = df_embedding_tpm.loc[df_labels.index,:] if len(usecols) > 0: df_labels = df_labels.loc[df_embedding_tpm.index,use_cols].copy() if len(colnames) > 0: df_labels.columns = colnames return df_embedding_tpm, df_labels def read_labeled_embedding_data(dataset, labels=['CellType'], label_names=[], embedding_args={}): """ read in embedding data, with a multilevel index Inputs: dataset - string of dataset name labels - list of labels aside from name to have for each cell. Default: 'CellType' label_names - list of what to call the labels in the multi index. If shorter than labels, rest of the values are filled by those from labels. Default: [] embedding_args - dictionary of keyword arguments for read_embedding_data. Default: {} Outputs: df - pandas dataframe """ # read in data df, df_labels = read_embedding_data(dataset, **embedding_args) # create multiindex if len(label_names) < len(labels): label_names += labels[len(label_names):] arrays = [df_labels.index] + [df_labels[label] for label in labels] names = ['Cell'] + label_names index = pd.MultiIndex.from_arrays(arrays, names=names) # give index labels df.index = index return df def read_tpm_data(dataset, qc=True, log=False, translabels=False, age_cutoff = -1, sort=False, sort_by='', drop=[]): """ a function to read in the tpm data for a dataset as a pandas dataframe Inputs: dataset - string of dataset name qc - whether to read in qualit controlled data. Default: True log - whether to log normalize the data. Default: False age_cutoff - whether to remove cells below a certain age. Default: -1, only works if value >=0 sort - whether to put cells into alphanumeric order. Default: False sort_by - an option to sort by a cell label column. Only runs if value is not ''. Default: '' Outputs: df - pandas dataframe rows are gene names columns are cell names df_labels - pandas dataframe rows are cells columns are cell labels """ # read in the data if not qc: dataset = dataset + '-non_QC' kwargs = {'sep':'\t', 'header':0, 'index_col':0} fname = 'Datasets/%s-tpm.tsv' % dataset df = pd.read_csv(fname, **kwargs) # read in labels if translabels: fname = 'Datasets/%s-transcriptional_labels.tsv' % dataset else: fname = 'Datasets/%s-labels.tsv' % dataset df_labels = pd.read_csv(fname, na_values='Other', dtype={'Cell':str}, sep='\t', header=0).set_index('Cell') # sort cells if sort == True: order = sorted(df.columns, key=file_navigation.natural_keys) df = df.loc[:,order] df_labels = df_labels.loc[order,:] if len(sort_by) > 0: df_labels.sort_values(sort_by, inplace=True) df = df.loc[:,df_labels.index] if age_cutoff >=0 and 'Age' in df_labels.columns: df_labels = df_labels.loc[df_labels.Age > age_cutoff,:] df = df.loc[:,df_labels.index] if len(drop) > 0: df_labels = df_labels.loc[~df_labels.iloc[:,0].isin(drop),:] df = df.loc[:,df_labels.index] if log: df = np.log2(1+df) return df, df_labels def read_labeled_tpm_data(dataset, labels=['CellType'], label_names=[], tpm_args={}): """ read in tpm data, with a multilevel index Inputs: dataset - string of dataset name labels - list of labels aside from name to have for each cell. Default: 'CellType' label_names - list of what to call the labels in the multi index. If shorter than labels, rest of the values are filled by those from labels. Default: [] tpm_args - dictionary of keyword arguments for read_tpm_data. Default: {} Outputs: df - pandas dataframe """ # read in data df, df_labels = read_tpm_data(dataset, **tpm_args) # create multiindex if len(label_names) < len(labels): label_names += labels[len(label_names):] arrays = [df_labels.index] + [df_labels[label] for label in labels] names = ['Cell'] + label_names columns = pd.MultiIndex.from_arrays(arrays, names=names) # give column labels df.columns = columns return df def read_dataset_labels(dataset): """ a function to just read the labels for a dataset """ df = pd.read_csv('Datasets/%s-labels.tsv' % dataset, sep='\t', header=0, index_col=0) return df def read_type_data(dataset, tpm_args={}, column='CellType'): """ a function to read in the tpm data or dataset, and then set a cell label as a column index Inputs: dataset - string of dataset name tpm_args - arguments for the read_tpm_data function column - cell label to use for column. Default: CellType Outputs: df - pandas dataframe of tpm data """ df, df_labels = read_tpm_data(dataset, **tpm_args) arrays = [df_labels.index, df_labels.loc[:,column]] names = ('Cell', column) df.columns = pd.MultiIndex.from_arrays(arrays, names=names) return df def read_sub_data(subname, dataset): # read in data kwargs = {'sep':'\t', 'header':0, 'index_col':0} fname = 'Mapping/DataSubsets/%s.tsv' % subname df = pd.read_csv(fname, **kwargs) # read in labels fname = 'Datasets/%s-labels.tsv' % dataset df_labels = pd.read_csv(fname, na_values='Other', dtype={'Cell':str}, sep='\t', header=0).set_index('Cell') df = df.loc[:,df.columns.isin(df_labels.index)] df_labels = df_labels.loc[df.columns,:] # create column multiindexing arrays = [df_labels.index, df_labels.CellType] names = ('Cell', 'CellType') df.columns = pd.MultiIndex.from_arrays(arrays, names=names) return df def add_continents(df, axis='index', refname='Harris_Continents.txt'): fname = 'References/%s' % refname params = {'sep':'\t', 'header':0, 'index_col':0} df_labels = pd.read_csv(fname, **params) if axis.lower() == 'index': df_labels = df_labels.loc[df.index.get_level_values('CellType'),:] arrays = [df.index.get_level_values('Cell'), df_labels.index, df_labels.Continent] names = ('Cell', 'CellType', 'Continent') df.index = pd.MultiIndex.from_arrays(arrays, names=names) else: df_labels = df_labels.loc[df.columns.get_level_values('CellType'),:] arrays = [df.columns.get_level_values('Cell'), df_labels.index, df_labels.Continent] names = ('Cell', 'CellType', 'Continent') df.columns = pd.MultiIndex.from_arrays(arrays, names=names) return df def read_ephys_data(age_cutoff=0): """ read in ephystiological data Inputs: age_cutoff - remove all cells younger than the age cutoff. Default: 0 Outputs: df - pandas dataframe of ephys data """ # read in dataset fname = 'References/Lab_Pvalb-electro.tsv' params = {'sep':'\t', 'header':0, 'index_col':0} df = pd.read_csv(fname, **params).iloc[:,1:] # get cell labels, to remove too young cells fname = 'Datasets/Lab_Pvalb-labels.tsv' df_labels = pd.read_csv(fname, **params) df_labels = df_labels.loc[df_labels.Age>age_cutoff] df = df.loc[df.index.isin(df_labels.index)] # order the columns columns = [ 'Resting membrane potential (mV)', 'Input resistance (MOhm)', 'Capacitance (pF)', 'AP firing threshold (pA)', 'Latency (ms)', 'AP peak amplitude (mV)', 'AP halfwidth (ms)', 'Frequency Slope (Hz/pA)', 'Attenuation', 'Sag potential' ] df = df.loc[:,columns] return df
L = [4,6,5,1,3,2,7,11,9,10,8] def bubbleSort(L): for i in range(len(L)): j = i + 1 for j in range(i, len(L)): if L[i] > L[j]: L[i], L[j] = L[j], L[i] return L print(bubbleSort(L))
""" Let’s say we have some customer records in a text file (customers.txt, see below) – one customer per line, JSON-encoded. We want to invite any customer within 100km of our Dublin office (GPS coordinates 53.3381985, -6.2592576) for some food and drinks on us. Write a program that will read the full list of customers and output the names and user ids of matching customers (within 100 km), sorted by user id (ascending). """ import sys from math import cos, sin, asin, sqrt, radians class Converter(object): def from_degrees_to_radians_point(self, point): return map(radians, [point.latitude, point.longitude]) class SpatialPoint(object): def __init__(self, latitude, longitude, description = None): self.latitude = float(latitude) self.longitude = float(longitude) self.description = description def __repr__(self): return str(self.__dict__) class SpatialSearch(object): def __init__(self, entries, converter = None): # Prohibit creating class instance if self.__class__ is SpatialSearch: raise TypeError('SpatialSearch abstract class cannot be instantiated') self.entries = entries self.converter = converter def search_all_nearby(self, location, radius): elem_nearby = self._get__all_nearby(location, radius) return elem_nearby def _get__all_nearby(self, location, radius): raise NotImplementedError() def _apply_converter(self, point): if self.converter: return self.converter(point) else: return (point.latitude, point.longitude) def haversine(self, p1, p2): lat1, lon1 = self._apply_converter(p1) lat2, lon2 = self._apply_converter(p2) delta_lat = lat2 - lat1 delta_lon = lon2 - lon1 # Kilometeres R = 6367 a = pow(sin(delta_lat / 2), 2) + cos(lat1) * cos(lat2) * pow(sin(delta_lon / 2), 2) c = 2 * asin(sqrt(a)) distance = R * c return distance class NaiveSpatialSearch(SpatialSearch): def _get__all_nearby(self, location, radius): nearby = [] for entry in self.entries: distance = self.haversine(location, entry) if distance < radius: nearby.append(entry) return nearby class RTreeSpatialSearch(SpatialSearch): def _get__all_nearby(self, location, radius): pass class Customer(object): def __init__(self, user_id, name): self.user_id = user_id self.name = name def __lt__(self, other): return self.user_id < other.user_id def __repr__(self): return str(self.__dict__) class CustomerSpatial(Customer, SpatialPoint): def __init__(self, user_id, name, latitude, longitude): SpatialPoint.__init__(self, latitude, longitude, "Customer") Customer.__init__(self, user_id, name) import json class Parser(object): def parse_customer_spatial_data(self, customer_raw_data): customers = [] for customer_raw in customer_raw_data: customer_parsed = json.loads(customer_raw) user_id = customer_parsed["user_id"] name = customer_parsed["name"] latitude = customer_parsed["latitude"] longitude = customer_parsed["longitude"] customer = CustomerSpatial(user_id, name, latitude, longitude) customers.append(customer) return customers class CustomerProvider(object): def __init__(self): self.path = 'customers.txt' def get_customer_data(self): customers_raw = [] try: with open(self.path, 'r') as file_content: customers_raw = file_content.read().splitlines() except: raise return customers_raw class CustomersWrapper(object): def get_customers_nearby(self, location, distance): customers_nearby = [] try: customer_provider = CustomerProvider() customer_raw_data = customer_provider.get_customer_data() parser = Parser() customers = parser.parse_customer_spatial_data(customer_raw_data) converter = Converter() spatial_search = NaiveSpatialSearch(customers, converter.from_degrees_to_radians_point) customers_nearby = spatial_search.search_all_nearby(location, distance) customers_nearby.sort() except: e = sys.exc_info()[0] print ( "Error: {}".format(e) ) return customers_nearby if __name__ == '__main__': dublin_office = SpatialPoint(53.3381985, -6.2592576, "Dublin Office") distance = 100 customers_wrapper = CustomersWrapper() customers_wrapper.get_customers_nearby(dublin_office, distance)
# coding:utf-8 # Possibilitats: PE, PA, TI # Total 9: 3 empat, 6 guanyador # jugador1 humà # jugador2 machine from random import randint #Jugador humà jugador1=raw_input("SR Possi la jugada (PE/PA/TI): ") #Jugador machine aleatori=randint(1,3) if (aleatori==1): jugador2="PE" if (aleatori==2): jugador2="PA" if (aleatori==3): jugador2="TI" print "La meva jugada és:" , jugador2 # Empat (3 combinacions) if (jugador1==jugador2): print "Empat" else: # 6 combinacions # Guanya jugador1 (3 combinacions) if ( (jugador1=="PE" and jugador2=="TI") or (jugador1=="PA" and jugador2=="PE") or (jugador1=="TI" and jugador2=="PA") ): print "Tu guanyes!!!!!" else: # Guanya jugador2 (3 combinacions) print "Ets un .... has perdut !!!!"
#Carol Castro #88710391 import json import wof_computer import random import time NUM_HUMAN = 1 NUM_PLAYERS = 3 VOWEL_COST = 250 VOWELS = ['A', 'E', 'I', 'O', 'U'] # Load the wheel wheelFile = open('wheel.json', 'r') wheel = json.loads(wheelFile.read()) wheelFile.close() # Load the phrase set phraseFile = open('phrases.json', 'r') phrases = json.loads(phraseFile.read()) phraseFile.close() wof_computer.train(phrases) # Uncomment these to see the structure of wheel and phrases # print(json.dumps(wheel,indent=3)) # print(json.dumps(phrases,indent=3)) # Get a random item from wheel def spinWheel(): return random.choice(wheel) # Get a random phrase and category def getRandomCategoryAndPhrase(): category = random.choice(list(phrases.keys())) phrase = random.choice(phrases[category]) return (category, phrase.upper()) def createPlayer(isComputer, player_num): if isComputer: name = 'Computer {}'.format(player_num) else: name = input('Enter your name: ') return WheelOfFortunePlayer(name, isComputer) class WheelOfFortunePlayer(): def __init__(self, name, isComputer): self.name = name self.prizeMoney = 0 self.prizes = [] if isComputer: self.computer = wof_computer.WOFComputer(difficulty = random.randint(1,9)) else: self.computer = False def addMoney(self, amount): self.prizeMoney += amount def subtractMoney(self, amount): return self.addMoney(-amount) def goBankrupt(self): self.prizeMoney = 0 def addPrize(self, prize): self.prizes.append(prize) def getMove(self, *args, **kwargs): if(self.computer): return self.computer.getMove(*args, **kwargs) return ("{} guesses {}".format(self.name, guesses)) else: return input('{}, Enter your guess: '.format(self.name)).upper() def __str__(self): return '{} (${})'.format(self.name, self.prizeMoney) def completephrase(guessed, phrase): return all([(letter in guessed) or (not letter.isalnum()) for letter in phrase]) #checks to see if all values are true. def obscurePhrase(phrase, guesses): word='' for m in phrase: if m.isalnum() == True and m not in guesses: #should underscore: word+= '_' else: word+=m return word def letter_count(letter, phrase): let=0 for x in phrase: if x == letter: let+=1 return let def buyvowel(player): player.subtractMoney(VOWEL_COST) return player.prizeMoney def playround(): for play in playGame: response= input('Play or Pass: ') if response=="Play": player.playGame() def playGame(): players = [createPlayer(player_num>=NUM_HUMAN, player_num+1) for player_num in range(NUM_PLAYERS)] guessed = [] category, phrase = getRandomCategoryAndPhrase() playerIndex = 0 while True: player = players[playerIndex] wheelPrize = spinWheel() print("\n...{} spins...".format(player.name)) if wheelPrize['type'] == 'cash': obscuredPhrase = obscurePhrase(phrase, guessed) print('\nGuessed: {}'.format(','.join(guessed))) print('\nCategory is {}: '.format(category)) print(obscuredPhrase) if wheelPrize['prize']!= False: print('Spin: {} and {}'.format(wheelPrize['text'], wheelPrize['prize'])) else: print('Spin: {}'.format(wheelPrize['text'])) print(player) print('='*40) while True: guess= player.getMove(player.prizeMoney, category, obscuredPhrase, guessed, wheelPrize) time.sleep(1) if guess in guessed: print("{} was already guessed. Guess again!".format(guess)) time.sleep(1) continue if guess.isalnum()==True and len(guess)==1: if guess in VOWELS: if player.prizeMoney>=250: buyvowel(player) print("{} bought a vowel for $250".format(player.name)) else: print("Not enough money to buy a vowel. Guess again.") continue num_inst=0 if len(guess)==1: for char in phrase: if guess ==char: num_inst+=1 if player.computer == False: if num_inst==0: print("...There are 0 {}'s\n".format(guess)) elif num_inst==1: print("...There is 1 {}\n".format(guess)) else: print("...There are {} {}'s\n".format(num_inst, guess)) else: print("{} guesses {}".format(player.name, guess)) if num_inst==0: print("...There are 0 {}'s\n".format(guess)) elif num_inst==1: print("...There is 1 {}\n".format(guess)) else: print("...There are {} {}'s\n".format(num_inst, guess)) if guess in phrase: if wheelPrize['type']=='cash': player.addMoney(wheelPrize['value']* letter_count(guess, phrase)) if wheelPrize["prize"]!=False: player.addPrize(wheelPrize['prize']) guessed.append(guess) if completephrase(guessed, phrase)==True: print("Correct! The phrase was {}".format(phrase)) if player.prizes==[]: print("Congratulations! {} wins ${}".format(player.name, player.prizeMoney)) else: print("Congratulations! {} wins ${} and {}".format(player.name, player.prizeMoney, ','.join(player.prizes))) return None print ('{} was in the phrase! Guess again!'.format(guess)) print('\nGuessed: {}'.format(','.join(guessed))) print('\nCategory is {}: '.format(category)) obscuredPhrase=obscurePhrase(phrase, guessed) print(obscuredPhrase) wheelPrize = spinWheel() if wheelPrize['type']=='cash': print("\n...{} spins...".format(player.name)) if wheelPrize['prize']!= False: print('Spin: {} and {}'.format(wheelPrize['text'], wheelPrize['prize'])) else: print('Spin: {}'.format(wheelPrize['text'])) print(player) print('='*40) continue elif wheelPrize['type'] == 'bankrupt': #bankrupt print ('\n{} has gone Bankrupt!'.format(player.name)) player.goBankrupt() #print ('='*40) pass elif wheelPrize['type'] == 'loseturn': print ('\n{} Lost a turn!'.format(player.name)) player.addMoney(0) #print ('='*40) pass guessed.append(guess) break if guess.isalnum()==False and len(guess)==1: print("guess is invalid") print("Guess again") continue elif len(guess)>1: if guess == phrase: player.addMoney(wheelPrize['value']) if wheelPrize["prize"]!=False: player.addPrize(wheelPrize['prize']) print("{} guessed {}".format(player.name, guess)) print("Correct! Phrase was {}".format(guess)) if player.prizes==[]: print("Congratulations! {} wins ${}".format(player.name, player.prizeMoney)) else: print("Congratulations, {} wins ${} and {}".format(player.name, player.prizeMoney, ','.join(player.prizes))) return None elif guess=="PASS": print("{} passed their turn".format(player.name)) break else: print("Phrase {} is incorrect".format(guess)) break elif guess.isalnum() ==False and len(guess)==1: print('Your guess {} was invalid. Guess again.'.format(guess)) continue elif wheelPrize['type'] == 'bankrupt': #bankrupt print ('\n{} has gone Bankrupt!\n'.format(player.name)) player.goBankrupt() print ('='*40) pass elif wheelPrize['type'] == 'loseturn': print ('\n{} Lost a turn!\n'.format(player.name)) print ('='*40) pass playerIndex += 1 playerIndex = playerIndex%len(players) playGame()
''' The Fibonacci sequence is the integer sequence defined by the recurrence relation: F(n) = F(n-1) + F(n-2), where F(0) = 0 and F(1) = 1. In other words, the nth Fibonacci number is the sum of the prior two Fibonacci numbers. Below are the first few values of the sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144... Given a number n, print the n-th Fibonacci Number. Examples: Input: n = 3 Output: 2 Input: n = 7 Output: 13 Here's a starting point: ''' class Solution(): def fibonacci(self, n): value = 0 next_value = 1 for _ in range(n): tmp = next_value next_value += value value = tmp return value n = 9 print(Solution().fibonacci(n)) # 34 print(Solution().fibonacci(7))
''' An IP Address is in the format of A.B.C.D, where A, B, C, D are all integers between 0 to 255. Given a string of numbers, return the possible IP addresses you can make with that string by splitting into 4 parts of A, B, C, D. Keep in mind that integers can't start with a 0! (Except for 0) Example: Input: 1592551013 Output: ['159.255.101.3', '159.255.10.13'] ''' def ip_addresses(s, ip_parts = []): if len(ip_parts) == 4 and len(s) > 0: return [] if len(ip_parts) < 4 and len(s) == 0: return [] if len(ip_parts) == 4 and len(s) == 0: r = [ip_parts[0] + '.' + ip_parts[1] + '.' + ip_parts[2] + '.' + ip_parts[3]] return r ip_parts = [] if ip_parts is None else ip_parts result = [] k = min(3, len(s)) if s[0] == "0": tmp = ip_parts.copy() tmp.append([s[0]]) if len(s) > 1: x = s[1:] r = ip_addresses(x, tmp) if r: result += r else: for i in range(k): tmp = ip_parts.copy() part = s[:i + 1] if int(part) > 255: continue tmp.append(part) x = s[i + 1:] r = ip_addresses(x, tmp) if r: result += r return result result = ip_addresses('1592551013') print(result) # ['159.255.101.3', '159.255.10.13']
#You are given a singly linked list and an integer k. Return the linked list, removing the k-th last element from the list. #Try to do it in a single pass and using constant space. #Here's a starting point: class Node: def __init__(self, val, next=None): self.val = val self.next = next def __str__(self): current_node = self result = [] while current_node: result.append(current_node.val) current_node = current_node.next return str(result) def remove_kth_from_linked_list(head, k): current = head for _ in range(k + 1): current = current.next previous = head while current: previous = previous.next current = current.next tmp = previous.next previous.next = tmp.next tmp.next = None return head head = Node(1, Node(2, Node(3, Node(4, Node(5))))) print(head) # [1, 2, 3, 4, 5] head = remove_kth_from_linked_list(head, 3) print(head) # [1, 2, 4, 5]
#Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. #An input string is valid if: #- Open brackets are closed by the same type of brackets. #- Open brackets are closed in the correct order. #- Note that an empty string is also considered valid. #Example: #Input: "((()))" #Output: True #Input: "[()]{}" #Output: True #Input: "({[)]" #Output: False class Solution: #starting_brackets = {'(', '[', '{'} #ending_brackets = {')', ']', '}'} matched = {')':'(', ']':'[', '}':'{'} def isValid(self, s): # Fill this in. stack = [] for bracket in s: if bracket in self.matched: if len(stack) == 0: return False if stack[-1] == self.matched[bracket]: stack.pop() else: return False else: stack.append(bracket) return len(stack) == 0 # Test Program s = "()(){(())" # should return False print(Solution().isValid(s)) s = "" # should return True print(Solution().isValid(s)) s = "([{}])()" # should return True print(Solution().isValid(s))
''' You are given an array of integers. Find the maximum sum of all possible contiguous subarrays of the array. Example: [34, -50, 42, 14, -5, 86] Given this input array, the output should be 137. The contiguous subarray with the largest sum is [42, 14, -5, 86]. Your solution should run in linear time. Here's a starting point: ''' def max_subarray_sum(arr): max_sum = arr[0] tmp_sum = arr[0] for i in range(1, len(arr)): tmp_sum += arr[i] if tmp_sum > max_sum: max_sum = tmp_sum if arr[i] > tmp_sum: tmp_sum = arr[i] return max_sum print(max_subarray_sum([34, -50, 42, 14, -5, 86])) # 137
def fib_set(k): fib = [0] * (k + 2) fib[1] = 1 i = 2 while fib[i - 1] <= k: fib[i] = (fib[i - 1] + fib[i - 2]) i += 1 return set(fib) print(fib_set(20))
''' You are given an array. Each element represents the price of a stock on that particular day. Calculate and return the maximum profit you can make from buying and selling that stock only once. For example: [9, 11, 8, 5, 7, 10] Here, the optimal trade is to buy when the price is 5, and sell when it is 10, so the return value should be 5 (profit = 10 - 5 = 5). Here's your starting point: ''' def buy_and_sell(arr): #Fill this in. current_min = arr[0] max_profit = 0 for price in arr: if price - current_min > max_profit: max_profit = price - current_min if current_min > price: current_min = price return max_profit print(buy_and_sell([9, 11, 8, 5, 7, 10])) # 5
''' You are given the root of a binary tree. Find and return the largest subtree of that tree, which is a valid binary search tree. Here's a starting point: ''' class TreeNode: def __init__(self, key): self.left = None self.right = None self.key = key def __str__(self): # preorder traversal answer = str(self.key) if self.left: answer += str(self.left) if self.right: answer += str(self.right) return answer def largest_bst_subtree(root): # Fill this in. return check_tree(root)[1] def check_tree(node): if not node: return 0, None, True left_ok = not node.left or node.left.key < node.key right_ok = not node.right or node.right.key > node.key is_correct_node = left_ok and right_ok left_size, left_node, left_correct_tree = check_tree(node.left) right_size, right_node, right_correct_tree = check_tree(node.right) if right_correct_tree and left_correct_tree and is_correct_node: return left_size + right_size + 1, node, True else: if left_size > right_size: return left_size, left_node, False else: return right_size, right_node, False # 5 # / \ # 6 7 # / / \ # 2 4 9 node = TreeNode(5) node.left = TreeNode(6) node.right = TreeNode(7) node.left.left = TreeNode(2) node.right.left = TreeNode(4) node.right.right = TreeNode(9) print(largest_bst_subtree(node)) #749
''' The h-index is a metric that attempts to measure the productivity and citation impact of the publication of a scholar. The definition of the h-index is if a scholar has at least h of their papers cited h times. Given a list of publications of the number of citations a scholar has, find their h-index. Example: Input: [3, 5, 0, 1, 3] Output: 3 Explanation: There are 3 publications with 3 or more citations, hence the h-index is 3. Here's a starting point: ''' from collections import defaultdict def hIndex(publications): citations = {} for p in set(publications): citations[p] = 0 for p in publications: for key in citations.keys(): if p >= key: citations[key] += 1 res = 0 for key in citations.keys(): if key <= citations[key] and key > res: res = key return res print(hIndex([5, 3, 3, 1, 0])) # 3
''' Return the longest run of 1s for a given integer n's binary representation. Example: Input: 242 Output: 4 242 in binary is 0b11110010, so the longest run of 1 is 4. ''' def longest_run(n): longest = 0 tmp_longest = 0 while n > 0: if n & 1 == 1: tmp_longest += 1 longest = max(tmp_longest, longest) else: tmp_longest = 0 n = n >> 1 return longest print(longest_run(242)) # 4 print(longest_run(0)) print(longest_run(3)) print(longest_run(8))
#!/usr/bin/env python3 # # IndyCar Preternship Project # University of Notre Dame - CSE 20312 # Creators: Emma Fredin, Aidan Gordon, Jonathon Vasilak, and Mark Schermerhorn # # This program gathers race results in real-time and compiles statistics in a convenient way, particularly concerning the use of Push to Pass and passes occurring on-track import json import sys import operator import os import re import time ''' displayScreen This function calls the get functions to display all of the information to the terminal. PARAMETERS: race - complete dictionary containing dictionaries of all events occurring in the race. It also contains information concerning drivers and timelines. combined_data - nested dictionaries containing many of the calculations newEntry - current entry that is being recorded P2PBool - value from checkOvertakes function to determine use of P2P driver_list - list containing all car numbers P2PInit = number from main describing how many seconds of P2P are given at the start of the race The terminal is cleared before every new event and continually updated ''' def displayScreen(race, combined_data, newEntry, P2PBool, driver_list, P2PInit): os.system('clear') print('NTT INDYCAR SERIES') print() print(f'LATEST EVENTS - LAP {race["Passings"][-1]["LeaderLap"]}') race = mostRecentEvent(race, newEntry, P2PBool) print() print() # Most Passes using Push to Pass max_P2P = max_position_P2P(combined_data["Passes"], driver_list) for key, value in max_P2P.items(): if value != 0: print(f'MOST P2P PASSES: {race["CarNotoName"][str(key)]} - {value}') else: print(f'MOST P2P PASSES: NONE') print() # Most Passes not using Push to Pass max_notP2P = max_position_nonP2P(combined_data["Passes"], driver_list) for key, value in max_notP2P.items(): if value != 0: print(f'MOST NON-P2P Passes: {race["CarNotoName"][str(key)]} - {value}') else: print(f'MOST NON-P2P PASSES: NONE') print() # Most Lapped Passes using Push to Pass maxLappedP2P = max_lapped_P2P(combined_data["Lapped Passes"], driver_list) for key, value in maxLappedP2P.items(): if value != 0: print(f'MOST P2P LAPPED PASSES: {race["CarNotoName"][str(key)]} - {value}') else: print(f'MOST P2P LAPPED PASSES: NONE') print() # Most Lapped Passes using Push to Pass maxLappednonP2P = max_lapped_nonP2P(combined_data["Lapped Passes"], driver_list) for key, value in maxLappednonP2P.items(): if value != 0: print(f'MOST NON-P2P LAPPED PASSES: {race["CarNotoName"][str(key)]} - {value}') else: print(f'MOST NON-P2P LAPPED PASSES: NONE') print() print() # Percentage of Passes for Position, Total Number of Passes, and Avg Lab use of P2P print(f'INDIVIDUAL DRIVER STATISTICS') print(f' % PASSES FOR POSITION') print(f' DRIVER: P2P NON-P2P TOTAL PASSES AVG LAP # USE OF P2P P2P LEFT BEST TIMELINE') for i in driver_list: percent = calc_percentage(combined_data["Passes"][i]["Overtaker"]["P2P"], combined_data["Passes"][i]["Overtaker"]["~P2P"], True) percentNonP2P = calc_percentage(combined_data["Passes"][i]["Overtaker"]["P2P"], combined_data["Passes"][i]["Overtaker"]["~P2P"], False) average = averageLap(combined_data["Overtake Mode"], i) secP2PLeft = P2PLeft(race, i, P2PInit) maxTimeValDict = best_timeline_passes_func(race, i) for timeline, val in maxTimeValDict.items(): if val == 1 and timeline != 0: print(f'{race["CarNotoName"][str(i)]:>25}:{round(percent):>5}%{round(percentNonP2P):>11}%{race["TotalPasses"][str(i)]:>17}{round(average):>23}{secP2PLeft:>26}{timeline:>16} - {val} pass') elif timeline != 0: print(f'{race["CarNotoName"][str(i)]:>25}:{round(percent):>5}%{round(percentNonP2P):>11}%{race["TotalPasses"][str(i)]:>17}{round(average):>23}{secP2PLeft:>26}{timeline:>16} - {val} passes') else: print(f'{race["CarNotoName"][str(i)]:>25}:{round(percent):>5}%{round(percentNonP2P):>11}%{race["TotalPasses"][str(i)]:>17}{round(average):>23}{secP2PLeft:>26} N/A') print(f' TOTAL: {len(race["RacePasses"])}') print() # Display Number of Passes occurring at each timeline print("TIMELINE STATISTICS") print(" TIMELINE : # PASSES % PASSES WITH P2P PASSES WITHOUT P2P BEST DRIVER DRIVER USING MOST P2P") maxTimelinePasses(race, combined_data, driver_list) print() # time.sleep(0.2) ''' mostRecentEvent This function compiles the race['RaceEvents'] dictionary that is a dictionary of strings containing all of the Passes and Uses of Overtake in the race. The function also prints the latest 5 events to the terminal PARAMETERS: race - dictionary containing all data read in from the timelines. It is needed to store the string descriptions. newEntry - most recent entry detected from timelines P2PBool - boolean value determining if the car is using Push to Pass Return Value - This function then returns the race dictionary ''' def mostRecentEvent(race, newEntry, P2PBool): if 'ForPosition' in newEntry: if P2PBool: if newEntry['Position'] != 0: race['RaceEvents'].append(f'{race["CarNotoName"][newEntry["CarNo"]]} (#{newEntry["CarNo"]}) passed {race["CarNotoName"][newEntry["CarPassed"]]} (#{newEntry["CarPassed"]}) WITH P2P for P{newEntry["Position"]} at Timeline {newEntry["TimelineID"]}.') else: race['RaceEvents'].append(f'{race["CarNotoName"][newEntry["CarNo"]]} (#{newEntry["CarNo"]}) lapped {race["CarNotoName"][newEntry["CarPassed"]]} (#{newEntry["CarPassed"]}) WITH P2P at Timeline {newEntry["TimelineID"]}.') else: if newEntry['Position'] != 0: race['RaceEvents'].append(f'{race["CarNotoName"][newEntry["CarNo"]]} (#{newEntry["CarNo"]}) passed {race["CarNotoName"][newEntry["CarPassed"]]} (#{newEntry["CarPassed"]}) WITHOUT P2P for P{newEntry["Position"]} at Timeline {newEntry["TimelineID"]}.') else: race['RaceEvents'].append(f'{race["CarNotoName"][newEntry["CarNo"]]} (#{newEntry["CarNo"]}) lapped {race["CarNotoName"][newEntry["CarPassed"]]} (#{newEntry["CarPassed"]}) WITHOUT P2P at Timeline {newEntry["TimelineID"]}.') elif 'OvertakeNo' in newEntry: carNo = transponder_to_carNo(race['Competitors'], int(newEntry['TranNr'])) if newEntry["SecondsOfPush"] != 1: race['RaceEvents'].append(f'{race["CarNotoName"][str(carNo)]} (#{str(carNo)}) has used {newEntry["SecondsOfPush"]} seconds of P2P at Timeline {newEntry["TimelineID"]}.') else: race['RaceEvents'].append(f'{race["CarNotoName"][str(carNo)]} (#{str(carNo)}) has used {newEntry["SecondsOfPush"]} second of P2P at Timeline {newEntry["TimelineID"]}.') if len(race['RaceEvents']) >= 5: for i in range(-1,-6,-1): print(race['RaceEvents'][i]) else: print(race['RaceEvents'][-1]) return race ''' best_timeline Parameters: overtake_data - the dictionary containing information on overtake presses for all drivers TimelineID - the number of the checkpoint being checked Return Value - this function returns a dictionary containg a driver number and the number of overtakes completed by the driver at the checkpoint number passed to this function This function will compare all drivers' statistics regarding overtake presses at a certain timeline to determine which driver has used it the most at a specific timeline ''' def best_timeline(overtake_data, TimelineID): return_dictionary = {} max_val = 0 driver_numbers = [] for driver in overtake_data: if TimelineID in overtake_data[driver]["TimelineIDs"]: if(max_val <= overtake_data[driver]["TimelineIDs"][TimelineID]): max_val = overtake_data[driver]["TimelineIDs"][TimelineID] driver_numbers.append(driver) for driver in driver_numbers: return_dictionary[driver] = max_val return return_dictionary ''' best_timeline_passes_func This function returns a dictionary containing the timeline and passes for the best timeline of a specific driver. PARAMETERS: race - dictionary containing the passes-by-timeline data for each car CarNo - specific car we want to find the best timeline for ''' def best_timeline_passes_func(race, CarNo): maxTimeVal = {} tmpTimeline = 0 tmpMax = 0 for timeline, value in race['best_timeline_passes'][CarNo].items(): if value > tmpMax: tmpMax = value tmpTimeline = timeline maxTimeVal[tmpTimeline] = tmpMax return maxTimeVal ''' most_passes_by_timeline This function returns a dictionary containing the car number and the number of passes for the car that has passed the most people at a specific timeline PARAMETERS: race - dictionary containing the passes-by-timeline data for each car TimelineID - specific timeline we are referencing driver_info - list containing all of the driver numbers ''' def most_passes_by_timeline(race, TimelineID, driver_info): maxTimeVal = {} tmpCarNo = 0 tmpMax = 0 for CarNo in driver_info: if race['best_timeline_passes'][CarNo][TimelineID] > tmpMax: tmpCarNo = CarNo tmpMax = race['best_timeline_passes'][CarNo][TimelineID] maxTimeVal[tmpCarNo] = tmpMax return maxTimeVal ''' maxTimelinePasses This function is called from displayScreen and prints the timelines and the number of passes completed at each one, if any. If there is not any passes completed, then it does not print that timeline for space conservation. It also records the percentages of how many passes occurred at each specific timeline. PARAMETERS: race - The race dictionary contains the max_timelines dictionary that contains each timeline as a key and values as the number of passes completed at each one. combined_data - another dictionary containing information concerning timelines driver_info - list containing all car numbers ''' def maxTimelinePasses(race, combined_data, driver_info): for timeline, num in race['max_timelines'].items(): return_dictionary = best_timeline(combined_data["Overtake Mode"], int(timeline)) timeline_driver_dict = most_passes_by_timeline(race, int(timeline), driver_info) for driver, p2pNum in return_dictionary.items(): for carNum, passes in timeline_driver_dict.items(): if num != 0: if p2pNum != 1 and passes != 1: print(f'{timeline:>25} :{num:>7}{round(num/len(race["RacePasses"])*100):>10}%{race["max_timelines_P2P"][timeline]:>15}{race["max_timelines_NonP2P"][timeline]:>22}{race["CarNotoName"][str(carNum)]:>29} - {passes} passes{race["CarNotoName"][str(driver)]:>29} - {p2pNum} uses') break elif p2pNum == 1 and passes != 1: print(f'{timeline:>25} :{num:>7}{round(num/len(race["RacePasses"])*100):>10}%{race["max_timelines_P2P"][timeline]:>15}{race["max_timelines_NonP2P"][timeline]:>22}{race["CarNotoName"][str(carNum)]:>29} - {passes} passes{race["CarNotoName"][str(driver)]:>29} - {p2pNum} use') break elif p2pNum != 1 and passes == 1: print(f'{timeline:>25} :{num:>7}{round(num/len(race["RacePasses"])*100):>10}%{race["max_timelines_P2P"][timeline]:>15}{race["max_timelines_NonP2P"][timeline]:>22}{race["CarNotoName"][str(carNum)]:>29} - {passes} pass{race["CarNotoName"][str(driver)]:>29} - {p2pNum} uses') break elif p2pNum == 1 and passes == 1: print(f'{timeline:>25} :{num:>7}{round(num/len(race["RacePasses"])*100):>10}%{race["max_timelines_P2P"][timeline]:>15}{race["max_timelines_NonP2P"][timeline]:>22}{race["CarNotoName"][str(carNum)]:>29} - {passes} pass{race["CarNotoName"][str(driver)]:>29} - {p2pNum} use') break break ''' averageLap Parameters: overtake_presses - a dictionary containing information on overtakes driver_number - car number being searched for Return value: this function will return the average lap number a driver uses P2P This function assumes the overtake_presses dictionary will be in the same form as the dictionary built in the initialize_overtakes function ''' def averageLap(overtake_presses, driver_number): totalLaps = 0 keys = list(overtake_presses[driver_number]["Laps"].keys()) iterator = 0 for i in overtake_presses[driver_number]["Laps"]: totalLaps += (keys[iterator] + 1) * overtake_presses[driver_number]["Laps"][i] iterator += 1 if overtake_presses[driver_number]["Overtake"] > 0: return totalLaps / overtake_presses[driver_number]["Overtake"] else: return 0 ''' transponder_to_carNo Parameters: driver_info - a dictionary containing information separated by driver, this dictionary must contain "TranNr" and "CarNo" keys for this function to work search_number - the transponder number the function searches for in the dictionary Return value: function returns the Car Number of the car with the matching transponder number, if there is not car with a matching transponder number, the function returns NULL This function searches a dictionary containing driver information to determine the car number that corresponds with a transponder number passed to the function. If the value is found, then the Car Number is returned. ''' def transponder_to_carNo(driver_info, search_number): for driver in driver_info: if driver["TranNr"] == search_number: return driver["CarNo"] return NULL ''' P2PLeft This function returns the number of seconds remaining of P2P for a certain driver PARAMETERS: race - dictionary containing all racing statistics driver_number - Car Number If a driver has used Push to Pass, his or her most recent entry will be found. The number of seconds of Push to Pass remaining will be returned, or 200 will be returned if no entries are found for that driver ''' def P2PLeft(race, driver_number, P2PInit): for entry in reversed(race["Overtakes"]): if driver_number == transponder_to_carNo(race["Competitors"], entry["TranNr"]): return entry["OvertakeRemain"] return P2PInit ''' calcP2PPosition Parameters: racePasses - a dictionary containing information on lapped Passes isP2P - a boolean variable, denotes if the values for P2P or nonP2P needs to be calculated Return value: this function will return the number of P2P or nonP2P passes for overtaken cars This function assumes the racePasses dictionary will be in the same form as the dictionary built in the initialize_racePasses function ''' def calcP2PPosition(racePasses, isP2P): if isP2P: P2Psum = 0 for car in racePasses: P2Psum += racePasses[car]['Overtaker']['P2P'] return P2Psum else: nonP2Psum = 0 for car in racePasses: nonP2Psum += racePasses[car]['Overtaker']['~P2P'] return nonP2Psum ''' calc_lapped_P2P Parameters: lappedPasses - a dictionary containing information on lapped Passes isP2P - a boolean variable, denotes if the values for P2P or nonP2P needs to be calculated Return value: this function will return the number of P2P or nonP2P passes for lapped cars This function assumes the lappedPasses dictionary will be in the same form as the dictionary built in the initialize_lappedPasses function ''' def calc_lapped_P2P(lappedPasses, isP2P): if isP2P: P2Psum = 0 for car in lappedPasses: P2Psum += lappedPasses[car]['LeadCar']['P2P'] return P2Psum else: notP2Psum = 0 for car in lappedPasses: notP2Psum += lappedPasses[car]['LeadCar']['~P2P'] return notP2Psum ''' max_position_P2P This function calculates and returns the car number and number of passes for positionof the driver that has passed the most cars using Push to Pass. Parameters: racePasses_data - a dictionary containing information on passes for position driver_list - list of car numbers ''' def max_position_P2P(racePasses_data, driver_list): max_val = 0 max_key = driver_list[0] for i in driver_list: if racePasses_data[i]["Overtaker"]["P2P"] > max_val: max_val = racePasses_data[i]["Overtaker"]["P2P"] max_key = i maximum = {} maximum[max_key] = max_val return maximum ''' max_position_nonP2P This function calculates and returns the car number and number of passes for position of the driver that has passed the most cars not using Push to Pass. Parameters: racePasses_data - a dictionary containing information on passes for position driver_list - list of car numbers ''' def max_position_nonP2P(racePasses_data, driver_list): max_val = 0 max_key = driver_list[0] for i in driver_list: if racePasses_data[i]["Overtaker"]["~P2P"] > max_val: max_val = racePasses_data[i]["Overtaker"]["~P2P"] max_key = i maximum = {} maximum[max_key] = max_val return maximum ''' max_lapped_P2P This function calculates and returns the car number and number of lapped passes of the driver that has lapped the most cars using P2P. Paramenters: lappedPasses_data - dictionary containing information on lapped passes driver_list - list of car numbers ''' def max_lapped_P2P(lappedPasses_data, driver_list): max_val = 0 max_key = driver_list[0] for i in driver_list: if lappedPasses_data[i]["LeadCar"]["P2P"] > max_val: max_val = lappedPasses_data[i]["LeadCar"]["P2P"] max_key = i maximum = {} maximum[max_key] = max_val return maximum ''' max_lapped_nonP2P This function calculates and returns the car number and number of lapped passes of the driver that has lapped the most cars not using P2P. lappedPasses_data - dictionary containing information on lapped passes driver_list - list of car numbers ''' def max_lapped_nonP2P(lappedPasses_data, driver_list): max_val = 0 max_key = driver_list[0] for i in driver_list: if lappedPasses_data[i]["LeadCar"]["~P2P"] >= max_val: max_val = lappedPasses_data[i]["LeadCar"]["~P2P"] max_key = i maximum = {} maximum[max_key] = max_val return maximum ''' max_timeline Parameters: overtake_data - a dictionary passes to the function containing data concerning the number of times drivers used overtake mode at a checkpoint on track driver_number - the transponder number referring to the driver's data the function will be checking Return value - this function returns a dictionary with single key, being the number corresponding to a checkpoint, and value, the number of times overtake mode is used at that checkpoint This function will calculate the maximum value in the overtake_data[driver_number]["TimelineIDs"] dictionary and return a dictionary with the max value and corresponding key ''' def max_timeline(overtake_data, driver_number): max_val = max(overtake_data[driver_number]["TimelineIDs"].values()) max_keys = [] for i in overtake_data[driver_number]["TimelineIDs"]: if overtake_data[driver_number]["TimelineIDs"][i] == max_val: max_keys.append(i) max_dict = {} max_dict["Key(s)"] = max_keys max_dict["Value"] = max_val return max_dict ''' initialize_lappedPasses Parameters: lappedPasses - a dictionary that will be intitialized in this function driver_list - a data structure containing the transponder numbers of participating drivers The function will return the "lappedPasses" dictionary after its is initialized. The lappedPasses dictionary is initialized in the following format. ''' def initialize_lappedPasses(lappedPasses, driver_list): for Transponder_Number in driver_list: if Transponder_Number not in lappedPasses: lappedPasses[Transponder_Number] = {} lappedPasses[Transponder_Number]["LappedCar"] = {} lappedPasses[Transponder_Number]["LeadCar"] = {} lappedPasses[Transponder_Number]["LappedCar"]["OppP2P"] = 0 lappedPasses[Transponder_Number]["LappedCar"]["~OppP2P"] = 0 lappedPasses[Transponder_Number]["LeadCar"]["P2P"] = 0 lappedPasses[Transponder_Number]["LeadCar"]["~P2P"] = 0 return lappedPasses ''' update_lappedPasses Parameters: lapped_car - the number of the driver who is being lapped lead_car - the number of the driver who is passing the lapped car lappedPasses - a dictionary containing information on lapped Passes use_P2P - a boolean variable, denotes if the passing driver has push to pass enabled Return value: this function will return an updated version of the lappedPasses dictionary This function assumes the lappedPasses dictionary will be in the same form as the dictionary built in the initialize_lappedPasses function ''' def update_lappedPasses(lapped_car, lead_car, lappedPasses, use_P2P): if use_P2P: lappedPasses[lapped_car]["LappedCar"]["OppP2P"] += 1 lappedPasses[lead_car]["LeadCar"]["P2P"] += 1 else: lappedPasses[lapped_car]["LappedCar"]["~OppP2P"] += 1 lappedPasses[lead_car]["LeadCar"]["~P2P"] += 1 return lappedPasses ''' calc_percentage Parameters: calc_P2P - a boolean variable passed to the function, determines whether the function will return the percentage of Push to Pass overtakes completed or non Push to Pass overtakes completed, default value is false P2P - the number of passes completed by a driver using Push to Pass, default value is 0 not_P2P - the number of passes completed by a driver not using Push to Pass, the default value is 0 totalPasses - the total number of passes completed by the driver during the race The value returned by this function is the percentage of passes completed either using or not using Push to Pass, depending on the calc_P2P variable. The return value is a double value which should be between 0 and 100. DRIVER_P2P_Percentage = calc_percentage(True, P2P=data[TransponderNumber][Overtaker][P2P], total_passes=) ''' def calc_percentage(P2P=0, not_P2P=0, calc_P2P=False): totalPasses = not_P2P + P2P if totalPasses == 0: return 0 if calc_P2P == True: return (P2P/totalPasses) * 100 return (not_P2P/totalPasses) * 100 ''' initialize_racePasses Parameters: racePasses - the dictionary that is being initialized in this function driver_list - a data structure containing the transponder numbers of participating drivers This function will initialize the data dictionary, putting it in the formatt used by the update_racePasses function. Within the dictionary, there are multiple nested dictionaries. The keys of the dictionary are: Overtaker - contains data regarding instances when this driver is the one doing the overtaking Overtaken - contains data regarding instances when this driver is the one being overtaken P2P - situations, either where the driver is overtaking another driver or is being overtaken, where Push to Pass is active for this driver ~P2P - situations where Push to Pass is not active for this driver OppP2P - situations where Push to Pass is active for the other driver involved in the overtake ~OppP2P - situations where Push to Pass is not active for the other driver involved in the overtake ''' def initialize_racePasses(racePasses, driver_list): for Transponder_Number in driver_list: if Transponder_Number not in racePasses: racePasses[Transponder_Number] = {} racePasses[Transponder_Number]["Overtaker"] = {} racePasses[Transponder_Number]["Overtaken"] = {} racePasses[Transponder_Number]["Overtaker"]["P2P"] = 0 racePasses[Transponder_Number]["Overtaker"]["~P2P"] = 0 racePasses[Transponder_Number]["Overtaker"]["OppP2P"] = 0 racePasses[Transponder_Number]["Overtaker"]["~OppP2P"] = 0 racePasses[Transponder_Number]["Overtaken"]["P2P"] = 0 racePasses[Transponder_Number]["Overtaken"]["~P2P"] = 0 racePasses[Transponder_Number]["Overtaken"]["OppP2P"] = 0 racePasses[Transponder_Number]["Overtaken"]["~OppP2P"] = 0 return racePasses ''' update_racePasses Parameters: passing_driver - the transponder number of the driver who has completed the overtake passed_driver - the transponder number of the driver who has just been overtaken racePasses - the dictionary containing data on pass statistics which is being updated and returned in this function passing_P2P - a boolean value that is true if passing_driver has Push to Pass active, default is false passed_P2P - a boolean value that is true if passed_driver has Push to Pass active, default is false The function update_racePasses returns an updated version of the dictionary "data", which is a parameter passed to this fuction. Which values in the dictionary are updated is determined by whether passing_P2P or passed_P2P is true. Since all values in the dictionary that may be updated are integers, they are updated by adding one to the value each time. This function assumes the dictionary "data" will be in the following format, where the '0's are the numbers being updated: data{ Transponder_Number: {Overtaker{"P2P": 0, "~P2P": 0, "OppP2P": 0, "~OppP2P": 0}, Overtaken{"P2P": 0, "~P2P": 0, "OppP2P": 0, "~OppP2P": 0}}, Transponder_Number: {Overtaker{"P2P": 0, "~P2P": 0, "OppP2P": 0, "~OppP2P": 0}, Overtaken{"P2P": 0, "~P2P": 0, "OppP2P": 0, "~OppP2P": 0}}, ..., Transponder_Number: {Overtaker{"P2P": 0, "~P2P": 0, "OppP2P": 0, "~OppP2P": 0}, Overtaken{"P2P": 0, "~P2P": 0, "OppP2P": 0, "~OppP2P": 0}} } ''' def update_racePasses(passing_driver, passed_driver, racePasses, passing_P2P=False, passed_P2P=False): if(passing_P2P): racePasses[passing_driver]["Overtaker"]["P2P"] += 1 racePasses[passed_driver]["Overtaken"]["OppP2P"] += 1 else: racePasses[passing_driver]["Overtaker"]["~P2P"] += 1 racePasses[passed_driver]["Overtaken"]["~OppP2P"] += 1 if(passed_P2P): racePasses[passing_driver]["Overtaker"]["OppP2P"] += 1 racePasses[passed_driver]["Overtaken"]["P2P"] += 1 else: racePasses[passing_driver]["Overtaker"]["~OppP2P"] += 1 racePasses[passed_driver]["Overtaken"]["~P2P"] += 1 return racePasses ''' initialize_overtakes Parameters: overtake_presses - the dictionary that will be initialized and returned from the function driver_list - a data structure containing the transponder number of all the drivers This function will build the dictionary needed by the update_overtakes function. The format of "data" in this function will be made to match the format of data in that function. The keys of the dictionary will be: Transponder_Number - the transponder number of the driver using the overtake button "Laps" - contains a dictionary containing lap numbers corresponding to the laps the driver used the overtake button "TimelineIDs" - a dictionary the next TimelineIDs passed by the driver after pushing the overtake button being the keys "Overtake" - contains a dictionary that will take contain keys for the beginning and end of the driver using overtake mode "Start" - the next TimelineID passed after a driver uses push to pass "End" - the final TimelineID passed while a driver is using push to pass ''' def initialize_overtakes(overtake_presses, driver_list): for Transponder_Number in driver_list: if Transponder_Number not in overtake_presses: overtake_presses[Transponder_Number] = {} overtake_presses[Transponder_Number]["Laps"] = {} overtake_presses[Transponder_Number]["TimelineIDs"] = {} overtake_presses[Transponder_Number]["Overtake"] = 0 return overtake_presses ''' update_overtakes Parameters: driver_number - the number of the driver whose information is being updated overtake_presses - dictionary containing various statistics about a driver's use of P2P lap_number - lap number that overtake is used TimelineID = specific timeline P2P was used This function will update "data" to contain information including, how many times does a driver use overtake mode on each lap, how many times does a driver use overtake mode at each TimelineID on the track, and where does the driver press and release the overtake button each time they use it. The data dictionary will need to be in the following format to work properly: data{ Transponder_Number: {"Laps": {'0': 0, 1: 0, ...}, "TimelineIDs": {'1': 0, 2: 0, ...}, "Overtake" {1: {"Start": 1, "End": 3}, ...}}, Transponder_Number: {"Laps": {'0': 0, 1: 0, ...}, "TimelineIDs": {'1': 0, 2: 0, ...}, "Overtake" {1: {"Start": 1, "End": 3}, ...}}, ..., Transponder_Number: {"Laps": {0: 0, 1: 0, ...}, "TimelineIDs": {1: 0, 2: 0, ...}, "Overtake" {1: {"Start": 1, "End": 3}, ...}} } ''' def update_overtakes(driver_number, overtake_presses, lap_number, Timeline_ID): if lap_number not in overtake_presses[driver_number]["Laps"]: overtake_presses[driver_number]["Laps"][lap_number] = 1 else: overtake_presses[driver_number]["Laps"][lap_number] += 1 if Timeline_ID not in overtake_presses[driver_number]["TimelineIDs"]: overtake_presses[driver_number]["TimelineIDs"][Timeline_ID] = 1 else: overtake_presses[driver_number]["TimelineIDs"][Timeline_ID] += 1 overtake_presses[driver_number]["Overtake"] += 1 return overtake_presses ''' readEntries This function is a Python generator that takes in the live data. For creation purposes, we set stream to sys.stdin and read the data from there. PARAMETERS: stream = sys.stdin or other place that data should be read from in a JSONL format line = inidividual line taken from input The data must be in the following JSONL format to work properly: {"PassingID": 187739, "PassingTime": 424841964, "TranNr": 5596122, "TimelineID": 4, "Pit": false, "Flag": 8, "ElapsedTime": 0, "LapCount": 0, "LeaderLap": 0} ''' def readEntries(stream): for line in stream: yield line ''' checkOvertake This function accesses the given dictionaries to match a certain pass occurring on-track and the time that it occurred to determine if the driver utilized Push to Pass to perform the pass. This function iterates through the race["Passings"] dictionary to find the timeline entry containing the same PassingID. Then, a comparison is made to determine if the passing driver was aided by Push to Pass. From there, information will be sent to stdout and other statistics functions to provide the user. PARAMETERS: race = the dictionary containing all of the statistics and timeline-generated entries from the race PassingID = the current ID given to the pass that just occurred on-track that can be matched to a particular timeline and ElapsedTime entry in race driverOvertakes = the dictionary that uses the driver transponder numbers as keys and stores the last elapsed time value + 30 seconds of when the driver last used Push to Pass ''' def checkOvertake(race, PassingID, driverOvertakes): for entry in race["Passings"]: if PassingID == entry["PassingID"]: if entry["ElapsedTime"] < driverOvertakes[entry["TranNr"]]: return True else: return False ''' initializeRaceDictionary This function creates the race dictionary that handles all of the input taken in from the timelines around the racetrack. This function calls the initializeDriverInfo function to initialize the driver and timeline information before the race begins. It then returns the race dictionary. PARAMETERS: race = the dictionary containing all of the statistics and timeline-generated entries from the race ''' def initializeRaceDictionary(): race = {} race = initializeDriverInfo(race) race = initializeCarNotoName(race) race['TotalPasses'] = {} race['max_timelines'] = {} race['max_timelines_P2P'] = {} race['max_timelines_NonP2P'] = {} race['best_timeline_passes'] = {} race['Passings'] = [] race['Overtakes'] = [] race['RacePasses'] = [] race['RaceEvents'] = [] return race ''' initializeCarNotoName This function creates a dictionary within the race dictionary that uses the car numbers as keys and formats the drivers' first and last names as values. This function also initializes a value to keep track of whether a certain car is currently in the pits which would invalidate a pass. PARAMETERS: race = The race['CarNotoName'] dictionary is initialized ''' def initializeCarNotoName(race): race['CarNotoName'] = {} race['InPit'] = {} for entry in race['Competitors']: race['CarNotoName'][entry['CarNo']] = f'{entry["FirstName"]} {entry["LastName"]}' race['InPit'][entry['CarNo']] = False return race ''' initializeDriverInfo This function is called within the initializeRaceDictionary function. This function takes in a file called "initial.jsonl" and parses out the information about the competitors and the timelines around the racetrack. Then, this function loads that data into the race dictionary and returns it to the other function. PARAMETERS: race = the dictionary containing all of the statistics and timeline-generated entries from the race The format of the initial.jsonl file must be as follows: { "Competitors" : [ {"FirstName": "Felix", "LastName": "Rosenqvist", "CarNo": "10", "TranNr": 3463610}, {"FirstName": "Will", "LastName": "Power", "CarNo": "12", "TranNr": 5596122}, ... ], "Timelines" : [ {"TimelineID": 1, "Name": "SF", "Order": 0}, {"TimelineID": 2, "Name": "SFT", "Order": 1}, ... ] } ''' def initializeDriverInfo(race): with open('initial.jsonl') as json_file: race = json.load(json_file) return race ''' initializeDriverOvertakesDict This function takes in the race dictionary and initializes the driverOvertakes dictionary. This dictionary will be used to store a value that is 30 seconds after the driver last used Push to Pass. These values are stored under the corresponding key that is equal to the transponder number of each car. PARAMETERS: race = the dictionary containing all of the statistics and timeline-generated entries from the race driverOvertakes = the dictionary that contains the transponder number of each car as keys. Each key contains a value that is 30 seconds more than the last time each driver used Push to Pass. The driverOvertakes dictionary is formatted as follows: { 3463610 : 10035000, 5596122 : 25674978, ... } ''' def initializeDriverOvertakesDict(race): driverOvertakes = {} for driverDict in race['Competitors']: driverOvertakes[driverDict['TranNr']] = 0 return driverOvertakes ''' entryComparisons This function is called from the main function after every line is taken in from stdin. It essentially sorts the newEntry dictionary to see if it is a "Passings" entry, a "Overtakes" entry, or a "RacePasses" entry. Then it performs additional checks before appending that dictionary to the correct list. It also updates the driverOvertakes dictionary every time a new "Overtakes" entry is detected. PARAMETERS: race = the dictionary containing all of the statistics and timeline-generated entries from the race newEntry = the dictionary taken in from stdin that is updated during every iteration driverOvertakes = the dictionary that contains the transponder number of each car as keys. Each key contains a value that is 30 seconds more than the last time each driver used Push to Pass. combined_data = another dictionary containing various race statistics driver_list = list containing all car numbers P2PInit = number from main describing how many seconds of P2P are given at the start of the race The race dictionary will continue to be updated in the following format: { "Competitors" : [ {"FirstName": "Felix", "LastName": "Rosenqvist", "CarNo": "10", "TranNr": 3463610}, {"FirstName": "Will", "LastName": "Power", "CarNo": "12", "TranNr": 5596122}, ... ], "Timelines" : [ {"TimelineID": 1, "Name": "SF", "Order": 0}, {"TimelineID": 2, "Name": "SFT", "Order": 1}, ... ], "Passings" : [ {"PassingID": 189954, "PassingTime": 428647957, "TranNr": 4718059, "TimelineID": 1, "Pit": false, "Flag": 1, "ElapsedTime": 2124557, "LapCount": 2, "LeaderLap": 2}, ... ], "Overtakes": [ {"TranNr": 8193597, "OvertakeNo": 3, "OvertakeRemain": 189, "SecondsOfPush": 3, "SecondsBeforeTimeline": 5, "TimelineID": 1, "Lap": 4, "PassingTime": 430842219}, ... ], "RacePasses" : [ {"CarNo": "26", "CarPassed": "9", "Lap": 0, "TimelineID": 8, "ForPosition": true, "PassingID": 188308, "Position": 14}, ... ] } ''' def entryComparisons(race, newEntry, driverOvertakes, combined_data, driver_list, P2PInit): P2P_check = False # If Statement Places newEntry in Correct Nested Dictionary with Additional Conditions # This If Statement takes in any newEntry that contains data from cars passing timelines. if 'ElapsedTime' in newEntry: # Conditional Statement to Avoid Appending Unnecessary Data to Dictionary if newEntry['ElapsedTime'] >= 0 and newEntry['Flag'] == 1 and not newEntry['Pit']: driverNum = transponder_to_carNo(race["Competitors"], newEntry["TranNr"]) race['InPit'][driverNum] = newEntry['Pit'] race['Passings'].append(newEntry) return combined_data # This Elif Statement appends any data associated with Overtakes. elif 'OvertakeNo' in newEntry: P2P_check = False race['Overtakes'].append(newEntry) update_overtakes(transponder_to_carNo(race["Competitors"], newEntry["TranNr"]), combined_data["Overtake Mode"], newEntry["Lap"], newEntry["TimelineID"]) # This For Loop checks to find the corresponding Timeline Pass for a car when they use Push to Pass and logs that time with an added 30 seconds into a dictionary. for Passing in race['Passings']: if newEntry['PassingTime'] == Passing['PassingTime']: driverOvertakes[newEntry['TranNr']] = Passing['ElapsedTime'] + 300000 - (newEntry['SecondsBeforeTimeline'] * 10000) break # This Elif Statement appends any data associated with Passes elif 'CarPassed' in newEntry: for entry in race["Passings"]: if entry["PassingID"] == newEntry["PassingID"] and not entry["Pit"] and race["Passings"][-1]["Flag"] == 1: race['RacePasses'].append(newEntry) race['TotalPasses'][str(newEntry['CarNo'])] += 1 race['max_timelines'][str(newEntry['TimelineID'])] += 1 race['best_timeline_passes'][newEntry['CarNo']][newEntry['TimelineID']] += 1 if newEntry["ForPosition"]: P2P_check = checkOvertake(race, newEntry["PassingID"], driverOvertakes) update_racePasses(newEntry['CarNo'], newEntry['CarPassed'], combined_data["Passes"], P2P_check, False) if P2P_check and not race["InPit"][newEntry["CarNo"]] and not race["InPit"][newEntry["CarPassed"]]: race['max_timelines_P2P'][str(newEntry['TimelineID'])] += 1 elif not P2P_check and not race["InPit"][newEntry["CarNo"]] and not race["InPit"][newEntry["CarPassed"]]: race['max_timelines_NonP2P'][str(newEntry['TimelineID'])] += 1 break else: P2P_check = checkOvertake(race, newEntry["PassingID"], driverOvertakes) update_lappedPasses(newEntry['CarPassed'], newEntry['CarNo'], combined_data["Lapped Passes"], P2P_check) if P2P_check and not race["InPit"][newEntry["CarNo"]] and not race["InPit"][newEntry["CarPassed"]]: race['max_timelines_P2P'][str(newEntry['TimelineID'])] += 1 elif not P2P_check and not race["InPit"][newEntry["CarNo"]] and not race["InPit"][newEntry["CarPassed"]]: race['max_timelines_NonP2P'][str(newEntry['TimelineID'])] += 1 break displayScreen(race, combined_data, newEntry, P2P_check, driver_list, P2PInit) return combined_data ''' initializeTotalPasses This function is called from the main function and initializes the TotalPasses and max_timelines dictionaries to zero. The TotalPasses dictionary records how many passes each driver makes. The max_timelines dictionary records how many passes occur at each timeline. PARAMETERS: race = dictionary that contains these two nested dictionaries and others driver_list = list containing the car numbers The race dictionary is returned ''' def initializeTotalPasses(race, driver_list): for num in driver_list: race['TotalPasses'][str(num)] = 0 race['best_timeline_passes'][num] = {} for timeline in race['Timelines']: race['max_timelines'][str(timeline['TimelineID'])] = 0 race['max_timelines_P2P'][str(timeline['TimelineID'])] = 0 race['max_timelines_NonP2P'][str(timeline['TimelineID'])] = 0 for num2 in driver_list: race['best_timeline_passes'][num2][timeline['TimelineID']] = 0 return race ''' print_to_stream This function is called from the main function at the end of program execution to create a txt file containing the final results of the race that can be analyzed by IndyCar and distributed to racing teams and other stakeholders PARAMETERS: race = dictionary containing data from race and track sensors combined_data = dictionary containing data and calculations newEntry = current race entry P2P_check = boolean to check if P2P was used driver_list = list of car numbers P2PInit = number from main describing how many seconds of P2P are given at the start of the race A text file (completerace.txt) will be created by calling the displayScreen function. ''' def print_to_stream(race, combined_data, newEntry, P2P_check, driver_list, P2PInit): original_stdout = sys.stdout with open('completerace.txt', 'w') as f: sys.stdout = f displayScreen(race, combined_data, newEntry, P2P_check, driver_list, P2PInit) sys.stdout = original_stdout displayScreen(race, combined_data, newEntry, P2P_check, driver_list, P2PInit) ''' print_to_json This function prints the collected dictionaries to an external JSON file that can be accessed after the race. PARAMETERS: race - dictionary to be printed combined_data - dictionary to be printed A JSON file called "currentRaceDictionaries.json" will be created. ''' def print_to_json(race, combined_data): outfile = open("currentRaceDictionaries.json", "w") json.dump(race, outfile, indent=4) json.dump(combined_data, outfile, indent=4) outfile.close() def main(): # Initialize stdin and dictionaries stream = sys.stdin P2PInit = 200 race = initializeRaceDictionary() driver_list = [] for i in race["Competitors"]: driver_list.append(i["CarNo"]) newEntry = {} driverOvertakes = initializeDriverOvertakesDict(race) race = initializeTotalPasses(race, driver_list) overtake_data = {} overtake_data = initialize_overtakes(overtake_data, driver_list) racePasses_data = {} racePasses_data = initialize_racePasses(racePasses_data, driver_list) lappedPasses_data = {} lappedPasses_data = initialize_lappedPasses(lappedPasses_data, driver_list) combined_data = {} combined_data["Passes"] = racePasses_data combined_data["Overtake Mode"] = overtake_data combined_data["Lapped Passes"] = lappedPasses_data # For Loop Receives One Entry Per Loop From The Generator And Parses It From JSON to a Python Dictionary for line in readEntries(stream): if "False" in line: line = re.sub("False", "false", line) elif "True" in line: line = re.sub("True", "true", line) line = re.sub(r"\'", r'"', line) newEntry = json.loads(line) combined_data = entryComparisons(race, newEntry, driverOvertakes, combined_data, driver_list, P2PInit) print_to_stream(race, combined_data, {}, False, driver_list, P2PInit) print_to_json(race, combined_data) if __name__ == '__main__': main()
n=int(input("enter the number")) i=0 temp=n while n>0: r=n%10 i=i+(r**3) n=n//10 if temp==i: print('it is armstrong number') else: print('not a armstrong number')
import math, random class Solver(): def __init__(self, puzzle): self.num_grid = puzzle.num_grid self.cell_map = puzzle.cell_map self.board = self.start_search(puzzle.board) def start_search(self, board): board = self.constraint_propagation(board) if board == False: return False if self.solved_value_len(board) == 81: return board _, index = self.get_min_multiple(board) for each_val in board[index[0]][index[1]][index[2]]: new_board = board.copy() new_board[index[0]][index[1]][index[2]] = each_val return_value = self.start_search(new_board) if return_value is not False: return return_value def get_min_multiple(self, board): multiple_list = [] for cell_no in range(self.num_grid): for row in range(int(math.sqrt(self.num_grid))): for col in range(int(math.sqrt(self.num_grid))): if len(board[cell_no][row][col]) > 1: multiple_list.append((len(board[cell_no][row][col]), (cell_no, row, col))) return min(multiple_list) def constraint_propagation(self, board): stalled = False while not stalled: before = self.solved_value_len(board) board = self.perform_elimination(board) board = self.fill_in_only_choice(board) after = self.solved_value_len(board) if before == after: stalled = True if self.empty_value_reached(board): return False return board def empty_value_reached(self, board): for cell_no in range(self.num_grid): for row in range(int(math.sqrt(self.num_grid))): for col in range(int(math.sqrt(self.num_grid))): if len(board[cell_no][row][col]) == 0: return True return False def solved_value_len(self, board): solved = 0 for cell_no in range(self.num_grid): for row in range(int(math.sqrt(self.num_grid))): for col in range(int(math.sqrt(self.num_grid))): if len(board[cell_no][row][col]) == 1: solved += 1 return solved def perform_elimination(self, board): for cell_no in range(self.num_grid): for row in range(int(math.sqrt(self.num_grid))): for col in range(int(math.sqrt(self.num_grid))): if len(board[cell_no][row][col]) == 1: board = self.remove_from_peer(cell_no, row, col, board) return board def remove_from_peer(self, cell_no, row, col, board): value = board[cell_no][row][col] for row_peer in self.cell_map[cell_no]['row']: for col_val in range(3): if value in board[row_peer][row][col_val]: board[row_peer][row][col_val] = board[row_peer][row][col_val].replace(value, '') for col_peer in self.cell_map[cell_no]['col']: for row_val in range(3): if value in board[col_peer][row_val][col]: board[col_peer][row_val][col] = board[col_peer][row_val][col].replace(value, '') for cell_row in range(int(math.sqrt(self.num_grid))): for cell_col in range(int(math.sqrt(self.num_grid))): if value in board[cell_no][cell_row][cell_col] and cell_row != row and cell_col != col: board[cell_no][cell_row][cell_col] = board[cell_no][cell_row][cell_col].replace(value, '') return board def fill_in_only_choice(self, board): for digit in '123456789': for cell_no in range(self.num_grid): index_list = [] for row in range(int(math.sqrt(self.num_grid))): for col in range(int(math.sqrt(self.num_grid))): if digit in board[cell_no][row][col]: index_list.append({'cell_no': cell_no, 'row': row, 'col': col}) if len(index_list) == 1: board[index_list[0]['cell_no']][index_list[0]['row']][index_list[0]['col']] = digit for grid_row in range(0, 9, 3): for row in range(3): index_list = [] for grid_col in range(3): cell_no = grid_row + grid_col for col in range(3): if digit in board[cell_no][row][col]: index_list.append({'cell_no': cell_no, 'row': row, 'col': col}) if len(index_list) == 1: board[index_list[0]['cell_no']][index_list[0]['row']][index_list[0]['col']] = digit for grid_col in range(3): for col in range(3): index_list = [] for grid_row in range(0, 9, 3): cell_no = grid_row + grid_col for row in range(3): if digit in board[cell_no][row][col]: index_list.append({'cell_no': cell_no, 'row': row, 'col': col}) if len(index_list) == 1: board[index_list[0]['cell_no']][index_list[0]['row']][index_list[0]['col']] = digit return board def get_puzzle_grid(self): # for i in range(3): # print(self.board[0][i], self.board[1][i], self.board[2][i]) # for i in range(3): # print(self.board[3][i], self.board[4][i], self.board[5][i]) # for i in range(3): # print(self.board[6][i], self.board[7][i], self.board[8][i]) grid = '' num = 0 for k in range(3): for i in range(3): for j in range(3): cell = num + j for each in self.board[cell][i]: grid += str(each) num += 3 return grid def display(self): grid = self.get_puzzle_grid() print(' ---------------------------------------') for grid_row in range(3): for row in range(3): row_string = ' | ' cell_row = grid_row * 3 + row for grid_col in range(3): for col in range(3): cell_col = grid_col * 3 + col row_string += grid[cell_row * 9 + cell_col] + ' ' row_string += ' | ' print(row_string) print(' ---------------------------------------') print("\n\n")
def getadd(): # addr = 12345 # addr = 12346 addr = 12347 # addr = 12348 return addr # if state == 0 and len(tmp) > 11 or (len(tmp) > 10 and not tmp.endswith("\a")): # wrong = 1 # if state == 1 and len(tmp) > 6 or (len(tmp) > 5 and not tmp.endswith("\a")): # wrong = 1 # if (state == 2 or state == 3) and (len(tmp) > 11 or (len(tmp) > 10 and not tmp.endswith("\a"))): # wrong = 1 # if state == 4 and (len(tmp) > 99 or (len(tmp) > 98 and not tmp.endswith("\a"))): # wrong = 1
import unittest class Node(object): def __init__(self): self.root_node = {} def add_word(self, word): current_node = self.root_node is_new_word = False for character in word: if character not in current_node: is_new_word = True current_node[character] = {} current_node = current_node[character] if "End Of Word" not in current_node: is_new_word = True current_node["End Of Word"] = {} return is_new_word # Tests class Test(unittest.TestCase): def test_t_usage(self): t = Node() result = t.add_word('catch') self.assertTrue(result, msg='new word 1') result = t.add_word('cakes') self.assertTrue(result, msg='new word 2') result = t.add_word('cake') self.assertTrue(result, msg='prefix of existing word') result = t.add_word('cake') self.assertFalse(result, msg='word already present') result = t.add_word('caked') self.assertTrue(result, msg='new word 3') result = t.add_word('catch') self.assertFalse(result, msg='all words still present') result = t.add_word('') self.assertTrue(result, msg='empty word') result = t.add_word('') self.assertFalse(result, msg='empty word present') unittest.main(verbosity=2)
#Sort the given array A = [] n = int(input('Enter number of elements : ')) print('Enter elements : ') for i in range(n): A.append(int(input())) A.sort(reverse= True) print('Sorted array is :', A)
# Union of two sorted arrays with handling of duplication def unionSort(a, b , n ,m): ''' a= Sorted array 1 n= Size of aaray 1 (a) b= Sorted array 2 m= Size of aaray 2 (b) ''' c= list() #a list or array for storing the result i, j =0, 0 while i<n and j<m : while i+1<n and a[i+1]==a[i]: i+=1 while j+1<m and b[j+1]==b[j]: j+=1 if a[i]<b[j]: c.append(a[i]) i+=1 elif a[i]>b[j]: c.append(b[j]) j+=1 else: c.append(b[j]) i+=1 j+=1 while i<n: while i+1<n and a[i+1]==a[i]: i+=1 c.append(a[i]) i+=1 while j<m: while j+1<m and b[j+1]==b[j]: j+=1 c.append(b[j]) j+=1 return c a= [6, 8, 8, 10] n= 4 b= [1, 2, 7, 9, 10] m= 5 print(unionSort(a, b, n, m))
#Search the element in array by using Binary Search #*Binary search only works on sorted array* def bianrySearch(arr, n, x): l=0 r= n-1 while(l<=r): mid = (l+r)//2 if (arr[mid]==x): return mid if (arr[mid]<x): l=mid+1 else: r=mid-1 return -1 arr=[2,4,6,8,10,12] n=len(arr) x=10 print(bianrySearch(arr, n, x))
arr=[1, 2, 3, 4] res=[1]*len(arr) left=[1]*len(arr) right=[1]*len(arr) for i in range(len(arr)): left[i]= arr[i-1]*left[i-1] for i in range(len(arr)-2, -1, -1): right[i]= arr[i+1]*right[i+1] for i in range(len(arr)): res[i]=(right[i]*left[i])//len(arr) print (res)
import numpy as np global N N=int(input("Enter N for the size of board : ")) def printSolution(board): for i in range(N): for j in range(N): print (board[i][j], end = " ") print() def isSafe(board, row, col): # Check this row on left side for i in range(col): if board[row][i] == 1: return False # Check upper diagonal on left side for i, j in zip(range(row, -1, -1), range(col, -1, -1)): if board[i][j] == 1: return False # Check lower diagonal on left side for i, j in zip(range(row, N, 1), range(col, -1, -1)): if board[i][j] == 1: return False return True def nQueen(board, col): if col >= N: return True for i in range(N): if (isSafe(board, i , col)): board[i][col]=1 if nQueen(board, col+1)==True: return True board[i][col]=0 return False def solution(): board = np.zeros((N, N), dtype=int) if nQueen(board, 0) == False: print ("Solution does not exist") return False printSolution(board) return True if __name__=="__main__": solution()
from collections import namedtuple import pygame from .constants import Color Move = namedtuple("Move", "column_delta, row_delta") def is_jump(move_tuple): return abs(move_tuple.column_delta) == 2 def get_jumped_move(move_tuple): """Take a move tuple (e.g. 2, 2) and return the jumped equivalent for that move (e.g. 1, 1)""" assert set(abs(x) for x in move_tuple) == set([2]), f"tried to calculate jump on {move_tuple}" return Move( column_delta=(1 if move_tuple.column_delta == 2 else -1), row_delta=(1 if move_tuple.row_delta == 2 else -1) ) class Square(pygame.sprite.Sprite): COLUMNS = ["a", "b", "c", "d", "e", "f", "g", "h"] NUMBERS = ["1", "2", "3", "4", "5", "6", "7", "8"] SQUARE_SIDE_LENGTH = 50 def __init__(self, x, y, column, row, board=None): super().__init__() self.board = board self.image = pygame.Surface((self.SQUARE_SIDE_LENGTH, self.SQUARE_SIDE_LENGTH)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.color = Color.WHITE if column % 2 == row % 2 else Color.BLACK self.is_selected = False self.column = column self.row = row self.is_hover = False self.piece = None # can become either Color.RED or Color.BROWN def __repr__(self): return f"<Square(number={self.number})>" @property def number(self): return self.column + self.row*8 def possible_moves(self, captures_only=False): possible_moves = [ Move(2, 2), Move(2, -2), Move(-2, 2), Move(-2, -2), ] if not captures_only: possible_moves.extend([get_jumped_move(m) for m in possible_moves]) moves_on_the_board = [ m for m in possible_moves if 0 <= m[0] + self.column < 8 # you stay on the horizontal and 0 <= m[1] + self.row < 8 # you stay on the vertical ] moves_in_the_correct_direction = [ m for m in moves_on_the_board if (self.piece.can_move_down and m.row_delta > 0) or (self.piece.can_move_up and m.row_delta < 0 ) ] moves_we_can_enter = [ m for m in moves_in_the_correct_direction if self.can_enter(m)] return [m for m in moves_we_can_enter if not is_jump(m) or self.can_perform_jump(m)] def can_enter(self, move): return self.other_square_from_move(move).piece is None def can_perform_jump(self, jump_move_tuple): """ returns true, when there is an opposing piece diagonally adjacent to you in the direction of the jump""" jumped_move = get_jumped_move(jump_move_tuple) # turn -2, 2 into -1, 1 jumped_square = self.other_square_from_move(jumped_move) return jumped_square.piece is not None and self.piece != jumped_square.piece def other_square_from_move(self, move): return self.board.square_at( column=self.column + move.column_delta, row=self.row + move.row_delta, ) def contains_point(self, x, y): return self.rect.x + Square.SQUARE_SIDE_LENGTH > x > self.rect.x and self.rect.y + Square.SQUARE_SIDE_LENGTH > y > self.rect.y def draw(self): if self.is_selected: pygame.draw.rect(self.board.screen, Color.GREEN, self.rect) # make square green (selected). elif self.is_hover: pygame.draw.rect(self.board.screen, Color.BLUE_DARK, self.rect) # make square blue (hovered). else: pygame.draw.rect(self.board.screen, self.color, self.rect) # square is neither selected nor hovered. if self.piece: self.piece.draw(self.board.screen, self.rect) def update(self): self.draw() # am I hover, selected, or original? Am I empty, have BROWN, or RED piece?
#!/usr/bin/env python import RPi.GPIO as gpio import time gpio.setmode(gpio.BOARD) gpio.setup(11, gpio.IN) state = 0 while True: input = gpio.input(11) if input == state: continue state = input if state == 0: print('Button Pressed Off') else: print('Button Pressed On') time.sleep(0.2)
#!/usr/bin/env python import RPi.GPIO as gpio def loop(): raw_input() state = 0 def btn_press(pin): global state input = gpio.input(11) if state == input: return else: state = input if state == 1: print("button turned on") else: print("button turned off") gpio.setmode(gpio.BOARD) gpio.setup(11, gpio.IN) gpio.add_event_detect(11, gpio.RISING, callback=btn_press, bouncetime=200) loop()
#!/usr/bin/env python ''' ------------------------------------------------------------------------------- Function to replace specific colours in a raster figure. Often you need to change the colour of a raster graphic for some reason, e.g. to increase contrast. Recreating these images can be time consuming. To speed up the process this script reads in an image and changes the colours for you. TODO: - Add example of usage - Add example of using a colour range, rather than specific colour #TARGET COLOURS #light blue = (65,120,250) -> HEX: #4178FA #dark blue = (55,50,200) -> HEX: #3732C8 #light red = (255,100,100) -> HEX: #FF6464 #dark red = (237,42,44) -> HEX: #ED2A2C #DIR = os.path.dirname(os.path.abspath(__file__)) #IMAGE_DIR = os.path.join(DIR, 'Main_data') #OUT_DIR = os.path.join(DIR, 'Main_data') ''' from sys import argv from PIL import Image import numpy as np for i, arg in enumerate(argv): print('argument {} is {}'.format(i, arg)) # IMAGE_DIR = '/home/connor/PhD/study_1/outputs/figures/' # OUT_DIR = '/home/connor/PhD/study_1/outputs/figures/' # # image_in = os.path.join(IMAGE_DIR, 'plot_training.png') # image_list = os.listdir(IMAGE_DIR) # image_out_path = (os.path.join(OUT_DIR, 'adjusted_plot_training.png'))# # # orig_cols = [(65, 120, 250), (55, 50, 200), (225, 2, 2), (255, 100, 100) ] # tar_cols = [(122, 194, 254), (0, 0, 160), (233, 28, 22),(255, 187, 187)] def main(argv_args): if len(argv_args) < 5: print('Please provide details of im_in, \ im_out_path, orig_cols, target_cols') im_in, im_out_path, orig_cols, target_cols = argv_args print im_in im_out = change_colours(im_in, orig_cols, target_cols) im_out.save(im_out_path) def change_colours(image_in, orig_cols, tar_cols): """Replace specific colours in a raster image. args: (1) The image that you want to change. (2) A list of colours that you want to remove. (3) A list of the colours you want to replace them. returns: an image file with the adjusted colours """ im = Image.open(image_in) im = im.convert('RGBA') data = np.array(im) # "data" is a height x width x 4 numpy array red, green, blue, alpha = data.T for orig_col, tar_col in zip(orig_cols, tar_cols): colours_to_change = (red == orig_col[0]) and \ (green == orig_col[1]) and \ (blue == orig_col[2]) data[..., :-1][colours_to_change.T] = tar_col # Need to back transpose im_out = Image.fromarray(data) im_out.show() return im_out if __name__ == "__main__": main(argv[1:])
# name = input('tell me your name, punk: ') # age = input('...and your age: ') # print(name, ' your are ', age) # Calc the area of the circle radius = input('Enter the radius of your circle (m): ') area = 3.142*int(radius)**2 print('The area of your circle is: ', area)
import string def tokenize(main_string, delimeters={" "}, special_tokens={"\\newline"}): """ Returns a list of tokens delimeted by the strings contained in the delimeters set. Punctuation and whitespace characters are treated as individual tokens. Delimeters are not counted as tokens. Multiple delimeters in a row are counted as a single delimeter. string: str Some string to be tokenized delimeters: set of str the delimeters to be used for tokenization special_tokens: set of str strings that should be treated as individual tokens. Cannot contain delimeting characters. """ tokens = [] s = "" for i,char in enumerate(main_string): if s in special_tokens: tokens.append(s) s = "" if char in delimeters: if len(s) > 0: tokens.append(s) s = "" elif char.isalnum(): s += char elif char in string.whitespace: if len(s) > 0: tokens.append(s) tokens.append(char) s = "" else: if len(s) > 0 and s[-1] != "\\": tokens.append(s) s = "" if char == "\\": s += char else: tokens.append(char) if len(s) > 0: tokens.append(s) return tokens def group_sentences(document, delimeters={".","!","?"}, titles={"dr","mr","mrs","ms","prof"}): """ Groups a document string into a list of sentence strings. Sentences are defined by a period followed by a whitespace character. Handles abbreviations by assuming all abbreviations are single, capital characters. Input: document: str delimeters: set of str end of sentence characters. titles: set of str enumerated titles that should be considered. Returns: sentences: list of str a list of all of the sentences in the document. """ sentences = [] running_s = document[0] document = document[1:] for i,c in enumerate(document[:-2]): running_s += c if c in delimeters: prob_dec = not document[i+1].isspace() other = (not document[i+2].isupper()) other = other and not document[i-1].isalnum() prob_abbrev = document[i-1].isupper() prob_title =check_if_title(running_s[:-1],titles) if not(prob_dec or prob_abbrev or prob_title or other): running_s = running_s.strip() if len(running_s) > 0: sentences.append(running_s) running_s = "" running_s = (running_s+document[-2:]).strip() if len(running_s) > 0: sentences.append(running_s) return sentences def check_if_title(s, titles): """ A helper function to check if the last word in the string is contained within a set of strings. s: str the string to determine if the last sequence of characters, delimeted by whitespace, is in the set `titles` titles: set of str the titles that need to be compared against """ prob_title = False for ws_char in string.whitespace: splt = s.strip().split(ws_char) idx = -1 if len(splt) > 1 else 0 title_str = splt[idx].strip().lower() prob_title = prob_title or title_str in titles return prob_title
#!/usr/bin/env python # Copyright (c) 2018 Intel Labs. # authors: German Ros (german.ros@intel.com) # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """ Module with auxiliary functions. """ import math from typing import List, Optional, Tuple import numpy as np import carla from carla.libcarla import World def draw_waypoints(world, waypoints, z=0.5): """ Draw a list of waypoints at a certain height given in z. :param world: carla.world object :param waypoints: list or iterable container with the waypoints to draw :param z: height in meters :return: """ for w in waypoints: t = w.transform begin = t.location + carla.Location(z=z) angle = math.radians(t.rotation.yaw) end = begin + carla.Location(x=math.cos(angle), y=math.sin(angle)) world.debug.draw_arrow(begin, end, arrow_size=0.3, life_time=1.0) def get_speed(vehicle): """ Compute speed of a vehicle in Kmh :param vehicle: the vehicle for which speed is calculated :return: speed as a float in Kmh """ vel = vehicle.get_velocity() return 3.6 * math.sqrt(vel.x ** 2 + vel.y ** 2 + vel.z ** 2) def is_within_distance_ahead(target_transform, current_transform, max_distance, max_degrees=90.0): """ Check if a target object is within a certain distance in front of a reference object. :param max_degrees: maximum allowed angle between the target object and the forward vector of current_transform :param target_transform: location of the target object :param current_transform: location of the reference object :param orientation: orientation of the reference object :param max_distance: maximum allowed distance :return: True if target object is within max_distance ahead of the reference object """ target_vector = np.array([target_transform.location.x - current_transform.location.x, target_transform.location.y - current_transform.location.y]) norm_target = np.linalg.norm(target_vector) # If the vector is too short, we can simply stop here if norm_target < 0.001: return True if norm_target > max_distance: return False fwd = current_transform.get_forward_vector() forward_vector = np.array([fwd.x, fwd.y]) d_angle = math.degrees(math.acos(np.clip(np.dot(forward_vector, target_vector) / norm_target, -1., 1.))) return d_angle < max_degrees def compute_magnitude_angle(target_location, current_location, orientation): """ Compute relative angle and distance between a target_location and a current_location :param target_location: location of the target object :param current_location: location of the reference object :param orientation: orientation of the reference object :return: a tuple composed by the distance to the object and the angle between both objects """ target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y]) norm_target = np.linalg.norm(target_vector) forward_vector = np.array([math.cos(math.radians(orientation)), math.sin(math.radians(orientation))]) d_angle = math.degrees(math.acos(np.clip(np.dot(forward_vector, target_vector) / norm_target, -1., 1.))) return (norm_target, d_angle) def compute_magnitude_angle_new(target_location, current_location, target_orientation, current_orientation): """ Compute relative angle and distance between a target_location and a current_location :param target_location: location of the target object :param current_location: location of the reference object :param orientation: orientation of the reference object :return: a tuple composed by the distance to the object and the angle between both objects """ target_vector = np.array([target_location.x - current_location.x, target_location.y - current_location.y]) x = math.cos(target_orientation) z = math.sin(-target_orientation) target_rotation_as_vector = np.array([x, z]) norm_target = np.linalg.norm(target_vector) forward_vector = np.array( [math.cos(math.radians(current_orientation)), math.sin(math.radians(current_orientation))]) d_angle = math.degrees( math.acos(np.clip(np.dot(target_rotation_as_vector, target_vector) / (norm_target * 1), -1., 1.))) return (norm_target, d_angle) def distance_vehicle(waypoint, vehicle_transform): loc = vehicle_transform.location dx = waypoint.transform.location.x - loc.x dy = waypoint.transform.location.y - loc.y return math.sqrt(dx * dx + dy * dy) def distance_transforms(t1, t2): loc = t1.location dx = t2.location.x - loc.x dy = t2.location.y - loc.y return math.sqrt(dx * dx + dy * dy) def distance_with_dir(t1: carla.Transform, t2: carla.Transform): diff = t2.location - t1.location # type: carla.Location distance = math.sqrt(diff.x * diff.x + diff.y * diff.y) def vector(location_1, location_2): """ Returns the unit vector from location_1 to location_2 location_1, location_2: carla.Location objects """ x = location_2.x - location_1.x y = location_2.y - location_1.y z = location_2.z - location_1.z norm = np.linalg.norm([x, y, z]) + np.finfo(float).eps return [x / norm, y / norm, z / norm] def get_nearest_traffic_light(vehicle: carla.Vehicle) -> Tuple[ carla.TrafficLight, float]: """ This method is specialized to check European style traffic lights. :param lights_list: list containing TrafficLight objects :return: a tuple given by (bool_flag, traffic_light), where - bool_flag is True if there is a traffic light in RED affecting us and False otherwise - traffic_light is the object itself or None if there is no red traffic light affecting us """ world = vehicle.get_world() # type: World lights_list = world.get_actors().filter("*traffic_light*") # type: List[carla.TrafficLight] ego_vehicle_location = vehicle.get_location() """ map = world.get_map() ego_vehicle_waypoint = map.get_waypoint(ego_vehicle_location) closest_traffic_light = None # type: Optional[carla.TrafficLight] closest_traffic_light_distance = math.inf for traffic_light in lights_list: object_waypoint = map.get_waypoint(traffic_light.get_location()) if object_waypoint.road_id != ego_vehicle_waypoint.road_id or \ object_waypoint.lane_id != ego_vehicle_waypoint.lane_id: continue distance_to_light = distance_transforms(traffic_light.get_transform(), vehicle.get_transform()) if distance_to_light < closest_traffic_light_distance: closest_traffic_light = traffic_light closest_traffic_light_distance = distance_to_light return closest_traffic_light, closest_traffic_light_distance """ min_angle = 180.0 closest_traffic_light = None # type: Optional[carla.TrafficLight] closest_traffic_light_distance = math.inf min_rotation_diff = 0 for traffic_light in lights_list: loc = traffic_light.get_location() distance_to_light, angle = compute_magnitude_angle(loc, ego_vehicle_location, vehicle.get_transform().rotation.yaw) rotation_diff = math.fabs( vehicle.get_transform().rotation.yaw - (traffic_light.get_transform().rotation.yaw - 90)) if distance_to_light < closest_traffic_light_distance and angle < 90 and (rotation_diff < 30 or math.fabs(360 - rotation_diff) < 30): closest_traffic_light_distance = distance_to_light closest_traffic_light = traffic_light min_angle = angle min_rotation_diff = rotation_diff # if closest_traffic_light is not None: # print("Ego rot: ", vehicle.get_transform().rotation.yaw, "TL rotation: ", closest_traffic_light.get_transform().rotation.yaw, ", diff: ", min_rotation_diff, ", dist: ", closest_traffic_light_distance) return closest_traffic_light, closest_traffic_light_distance def get_traffic_light_status(player: carla.Vehicle): light, distance = get_nearest_traffic_light(player) green_light = 0 if \ distance <= 20 \ and light is not None \ and light.state != carla.TrafficLightState.Green \ else 1 return green_light
import sys """this is the straight function.""" rank_list = ['x', 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] playerlist1 = ['QS', 'JD', '8H', '10C', '9S'] playerlist2 = ['AS', '5D', '6C', '8H', '7S'] print(playerlist1, "this is the players hand") # PART 1 index_list = [] for i in playerlist1: b = i[0] if b == '1': index = 10 else: index = rank_list.index(b) index_list += [index] # print(index) print(index_list, "this is the index list") # PART 2 Sorting the list A = index_list for i in range(len(A)): min_index = i for j in range(i + 1, len(A)): if A[min_index] > A[j]: min_index = j A[i], A[min_index] = A[min_index], A[i] print(A, "this is the sorted index list") if A[-1] - A[0] == 4: print(playerlist1, "this is a straight hand") else: print(playerlist1, "this is not a straight hand") # print("as the difference is not 4,", "its: ", A[-1] - A[0]) ''' IGNORE THIS FOR NOW # PART 3 Finding the difference diff_list = [A[i + 1] - A[i] for i in range(len(A) - 1)] print(diff_list, "this is the difference list") B = diff_list print(B[0], B[1], B[2], B[3]) if B[0] and B[1] and B[2] and B[3] == 1 or B[-1] - B[0] == 1: print(playerlist1, "this is a straight hand") # (and return True) else: print(playerlist1, "is not a straight hand") '''
import unittest from .models import movie Movie = movie.Movie class MovieTest(unittestst.TestCase): def setUp(self): self.new_movie = Movie(1234, "Python must be crazy","Ancient pythoneers", "https://image.tmdb.org/t/p/w500/khsjha27hbs",8.5,129993) def test_inctance(self): self.assertTrue(isinstance(self.new_movie,Movie)) if __name__ == '__main__': unittest.main()
class Retangle(): def __init__(self,length=1,width=1): self.length=length self.width=width def __setattr__(self,name,value): if name=='square': self.length=value self.width=value else: super().__setattr__(name,value) def mianji(self): return self.length*self.width
while True: num_1 = input('Digite um número: ') num_2 = input('Digite outro número: ') if not num_1.isdigit() or not num_2.isdigit(): print('Digite um número válido.') continue else: num_1 = float(num_1) num_2 = float(num_2) operador = input('Digite a operadoração (+, -, /, *): ') if operador == '+': print(num_1 + num_2) elif operador == '-': print(num_1 - num_2) elif operador == '/': print(num_1 / num_2) elif operador == '*': print(num_1 * num_2) else: print('Não é um operador válido.') sair = input('Deseja sair? [s]im ou [n]ão: ') if sair == 's': break else: continue
""" https://rszalski.github.io/magicmethods/ """ ## OLHAR O LINK ACIMA ## class A: def __init__(self): # método mágico iniciador print(f'Eu sou o INIT') a = A()
""" Combinations, Permutations e Product - Itertools Combinação - Ordem não importa Permutação - Ordem importa Ambos não repetem valores únicos. Produto - Ordem importa e repete valores únicos """ import itertools pessoa = ['Luiz', 'André', 'Eduardo', 'Letícia', 'Fabrício', 'Rose'] for grupo in itertools.combinations(pessoa, 2): # faz combinações de valores em X valor (valor, x) print(grupo) print('~'*45) for grupo in itertools.permutations(pessoa, 2): # repete os valores iguais. (André, Luiz) == (Luiz, André) print(grupo) print('~'*45) for grupo in itertools.product(pessoa, repeat=2): # repete o valor com ele mesmo. print(grupo)
print() print('TEXTO EXPLICATIVO:') perguntas = { 'Pergunta 1': { 'pergunta': 'Quanto é 2+2? ', 'respostas': {'a': '1', 'b': '4', 'c': '5'}, 'resposta_certa': 'b' }, 'Pergunta 2': { 'pergunta': 'Quanto é 2*3? ', 'respostas': {'a': '7', 'b': '9', 'c': '6'}, 'resposta_certa': 'c' }, 'Pergunta 3': { 'pergunta': 'Quanto é 7*9? ', 'respostas': {'a': '63', 'b': '52', 'c': '79'}, 'resposta_certa': 'a' }, 'Pergunta 4': { 'pergunta': 'Quanto é 14+7? ', 'respostas': {'a': '27', 'b': '21', 'c': '32'}, 'resposta_certa': 'b' }, 'Pergunta 5': { 'pergunta': 'Quanto é 8*6? ', 'respostas': {'a': '64', 'b': '40', 'c': '48'}, 'resposta_certa': 'c' }, } print() respostas_certas = 0 for pk, pv in perguntas.items(): print(f'{pk}: {pv["pergunta"]}') print('Respostas: ') for rk, rv in pv['respostas'].items(): print(f'[{rk}]: {rv}') resposta_usuario = input('Qual é sua resposta? ') if resposta_usuario == pv['resposta_certa']: print('Oba! Você acertou.') respostas_certas += 1 else: print('ERRRRROOOOOUUUUU!!!') print() quantidade_perguntas = len(perguntas) porcentagem_acerto = respostas_certas / quantidade_perguntas * 100 if respostas_certas > 1: plural = 'perguntas' else: plural = 'respostas' print(f'Você acertou {respostas_certas} {plural}.') print(f'Seu aproveitamento foi de {porcentagem_acerto}%.')
def func(arg, arg2): return f'{arg} * {arg2} =', arg * arg2 var = func(2,4) print(var) variavel = lambda x, y: x * y print(variavel(2, 8))
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] ex1 = [variavel for variavel in l1] # cria uma cópia idêntica a l1 print(ex1) ex2 = [v * 2 for v in l1] # multiplica o valor de v por 2 print(ex2) ex3 = [(v, v2) for v in l1 for v2 in range(3)] # cria uma lista de coordenadas (0, 1), (0, 2)... print(ex3) l2 = ['Luiz', 'Mauro', 'Maria'] ex4 = [v.replace('a', '@') for v in l2] # troca o a por @ dentro de toda a lista. print(ex4) tupla = ( ('chave', 'valor'), ('chave2', 'valor2'), ) ex5 = [(y, x) for x, y in tupla] # inverte as posições de X e Y print(ex5) l3 = list(range(100)) ex6 = [v for v in l3 if v % 3 == 0 if v % 8 == 0] # v recebe v dentro de l3 se for divisível por 3 e por 8 print(ex6) ex7 = [v if v % 3 == 0 else 'Não é' for v in l3] # para utilizar o else, precisa usar o if no começo print(ex7) ex8 = [v if v % 3 == 0 and v % 8 == 0 else 0 for v in l3] # o AND precisa ser incluso caso tenha mais uma condição. print(ex8)
import itertools alunos = [ {'nome': 'Derick', 'nota': 'A'}, {'nome': 'Luiz', 'nota': 'B'}, {'nome': 'Karla', 'nota': 'A'}, {'nome': 'Clara', 'nota': 'C'}, {'nome': 'Stheffany', 'nota': 'B'}, {'nome': 'Filipe', 'nota': 'D'}, {'nome': 'Pedro', 'nota': 'C'}, {'nome': 'Maria', 'nota': 'D'}, {'nome': 'José', 'nota': 'D'}, {'nome': 'Fernando', 'nota': 'A'}, ] ordena = lambda item: item['nota'] # uma "função" para ordenar alunos.sort(key=ordena) # for i in alunos: # print(i) alunos_agrupados = itertools.groupby(alunos, ordena) # agrupa itens que são iguais. Nesse caso a Key "Nota" for agrupamento, valores_agrupados in alunos_agrupados: va1, va2 = itertools.tee(valores_agrupados) # cria duas cópias do iterador (va1 e va2) print(f'Agrupamento: {agrupamento}') for aluno in va1: print(f'\t{aluno["nome"]}') quantidade = len(list(va2)) print(f'{quantidade} tiraram nota {agrupamento}') print()
class Produto: def __init__(self, nome, preco): self.nome = nome self.preco = preco def desconto(self, percentual): self.preco = self.preco - (self.preco * percentual / 100) @property def nome(self): return self._nome @nome.setter def nome(self, valor): self._nome = valor.title() # Getter recebe o valor de preço antes de atribuir no __init__ @property # decorador de propriedade def preco(self): return self._preco # por conveção é atribuido o nome do parâmetro com _ na frente # Setter Converte o valor recebido em algo para não dar erro. @preco.setter # nome da propridade acompanhado por setter. def preco(self, valor): # valor é o que será atribuido para a variável (preco da instancia __init__) if isinstance(valor, str): # se a variável é uma instância do tipo XPTO valor = float(valor.replace('R$', '')) # substitiu o R$ por nada self._preco = valor # getter recebe "valor" p1 = Produto('camiseta', 'R$53') p2 = Produto('CANECA', 14.3) print(p1.nome, p1.preco) print(p2.nome, p2.preco) p1.desconto(10) print(p1.preco)
# ESSE CÓDIGO É RESPONSAVEL APENAS PELA DESCRIPTAÇÃO DA MENSAGEM JÁ CRIPTOGRAFADA ## CRIAÇÃO DA TABELA PARA INSERÇÃO DOS VALORES tabela=[] for i in range(26): linha=[] cont=65+i for j in range(26): if cont>90: cont-=26 linha.append(chr(cont)) cont+=1 tabela.append(linha) #============================================================================== ##ENTRADA DO USUÁRIO E CRIAÇÃO DAS RESPECTIVAS TABELAS E VETORES NECESSÁRIOS f_cript=input("Digite a frase criptografada: ") f_chave=input("Digite a chave: ") cript=[] chave=[] descript=[] #============================================================================= #INSERÇÃO DOS VALORES DE CHAVE E DA MENSAGEM CRIPTOGRAFADA NOS VETORES ##RESPECTIVOS for i in f_cript: cript.append(i) for i in f_chave: chave.append(i) #============================================================================= ##FAZ A COMPARAÇÃO NA TABELA PARA GERAR A MENSAGEM DESCRIPTADA E ARMAZENA ## EM UM VETOR CHAMADO "DESCRIPT" for i in range(len(cript)): l=ord(chave[i])-65 x=tabela[l].index(cript[i]) descript.append(chr(x+65)) chave.append(chr(x+65)) #============================================================================= #CRIA UMA VARIÁVEL STR "TEXTO" PARA APRESENTAR A MENSAGEM DESCRIPTADA PARA #O USUÁRIO texto='' for i in range(len(cript)): texto+=descript[i] print(texto) #===============================================================================
def fact(n): if n == 0: return 1 p = 1 for i in range(1, n+1): p *= i return p def calc_binom(n, k): return int(fact(n)/(fact(k)*fact(n-k))) lines = 10 #lines = int(input("Number of lines: ")) pascal_triangle = [] for i in range(lines): nums = [] for j in range(i+1): nums.append(calc_binom(i, i-j)) pascal_triangle.append(nums) longest_line = sum([len(str(x))+1 for x in pascal_triangle[-1]])+1 for t in pascal_triangle: line = " ".join(str(x) for x in t) print("{0:^{width}}".format(line, width=longest_line))
import turtle from turtle import Screen import random caspar = turtle.Turtle() turtle.colormode(255) def random_color(): r = random.randint(0, 256) g = random.randint(0, 256) b = random.randint(0, 256) return r, g, b # colors = ["red", "green", "blue", "orange", "purple", "pink", "yellow"] turtle.speed("fastest") def draw_spirograph(size_gap): for _ in range(int(360 / size_gap)): caspar.color(random_color()) caspar.circle(100) caspar.setheading(caspar.heading() + size_gap) draw_spirograph(5) screen = turtle.Screen() screen.exitonclick()
import re def isValidEmail(email): regex = "^[A-Z0-9._+-]+@[A-Z0-9]+.[A-Z]{2,}$" if len(email) > 7: if re.match(regex, email, re.IGNORECASE) is not None: return True if isValidEmail("netsetos@gmail.com"): print("Valid Email Address") else: print("Invalid Email Address")
import pandas as pd from objects.subjects import Subjects from objects.students import Students from objects.teachers import Teachers #name_tch = input('Write your name: ') #name_tch = name_tch.capitalize() #print(name_tch) def populate_data(): # all the data with which we will work is entered # ------------------------ Define Teachers ------------------ # List of Teachers teachers = [] teacher_1 = Teachers( id = 1, id_2 = '0001', name = 'Carlos Ramirez', subjects = [1, 2, 8] ) teacher_2 = Teachers( id = 2, id_2 = '0002', name = 'Paola Campos', subjects = [3, 4] ) teacher_3 = Teachers( id = 3, id_2 = '0003', name = 'Andres Garcia', subjects = [1, 5, 8] ) teacher_4 = Teachers( id = 4, id_2 = '0004', name = 'Stefania Ortiz', subjects = [7, 2, 6] ) teachers.append(teacher_1) teachers.append(teacher_2) teachers.append(teacher_3) teachers.append(teacher_4) # ------------------------ Define Students ------------------ # List of Teachers students = [] student_1 = Students( id = 1, name = 'Jhonatan Ruiz', subjects = { 1 : 1, 2 : 4, 3 : 2 }, notes = { 1 : 3.4, 8 : 2.9, 6 : 2.5 } ) student_2 = Students( id = 2, name = 'Bryan Portela', subjects = { 4 : 2, 5 : 3 }, notes = { 4 : 3.4, 5 : 4.0 } ) student_3 = Students( id = 3, name = 'Irina Davila', subjects = { 1 : 3, 2 : 1, 7 : 4 }, notes = { 1 : 5, 8 : 4.5, 6 : 2.5 } ) student_4 = Students( id = 4, name = 'Jose Barrio', subjects = { 6 : 4, 8 : 3, 3 : 2 }, notes = { 1 : 3.6, 8 : 2.5, 6 : 2.5 } ) student_5 = Students( id = 5, name = 'Joaquin Valencia', subjects = { 1 : 3, 8 : 1, 6 : 4 }, notes = { 1 : 2.0, 8 : 1.8, 6 : 2.5 } ) student_6 = Students( id = 6, name = 'Alejandro Bernal', subjects = { 6 : 4, 7 : 4 }, notes = { 6 : 4.8, 7 : 3.2 } ) student_7 = Students( id = 7, name = 'Andres Saavedra', subjects = { 6 : 4, 4 : 2 }, notes = { 6 : 4.0, 4 : 3.5 } ) students.append(student_1) students.append(student_2) students.append(student_3) students.append(student_4) students.append(student_5) students.append(student_6) students.append(student_7) # ------------------------ Define Subjects ------------------ subjects = [] subject_1 = Subjects( id = 1, name = 'Math', ) subject_2 = Subjects( id = 2, name = 'Physics', ) subject_3 = Subjects( id = 3, name = 'Astronomy', ) subject_4 = Subjects( id = 4, name = 'Biology', ) subject_5 = Subjects( id = 5, name = 'English', ) subject_6 = Subjects( id = 6, name = 'Arts', ) subject_7 = Subjects( id = 7, name = 'Geography', ) subject_8 = Subjects( id = 8, name = 'Chemistry', ) subjects.append(subject_1) subjects.append(subject_2) subjects.append(subject_3) subjects.append(subject_4) subjects.append(subject_5) subjects.append(subject_6) subjects.append(subject_7) subjects.append(subject_8) # ------------------------ Define Notes ------------------ return { 'teachers': teachers, 'students': students, 'subjects': subjects } data = populate_data() #def check_subjects(): #for key, value in data.items(): #if key in['Subjects' and ['Teachers']: #if key in['Subjects']: #for val in value: #print(val.name) #return True # for key, value in data.items(): # if key in['subjects']: # for val in value: # for key_2, value_2 in data.items(): # if key_2 in['teachers']: # for val_2 in value_2: # if val_2.name == 'Carlos Ramirez': # if val.id in val_2.subjects: # print(val.name) #---------- function to check subjects assigned to teachers ---------- # for key, value in data.items(): # if key in['students']: # for val in value: # for key_2, value_2 in val.subjects.items(): # for key_3, value_3 in data.items(): # if key_3 in['teachers']: # for val_3 in value_3: # if val_3.name == 'Stefania Ortiz': # if value_2 == val_3.id: # students_list = [val.name] # no_repeat = set(students_list) # print(no_repeat) # for key, value in data.items(): # if key in['students']: # for val in value: # for key_2, value_2 in val.subjects.items(): # for key_3, value_3 in data.items(): # if key_3 in['teachers']: # for val_3 in value_3: # if val.name == 'Jhonatan Ruiz': # if val_3.id == key_2: # print(val.name + ' -- ' + val_3.name) for key, value in data.items(): if key in['students']: for val in value: if val.name == 'Jhonatan Ruiz': count_notes = 0 sum_notes = 0 for key_2, value_2 in val.notes.items(): count_notes += 1 sum_notes += value_2 print(sum_notes / count_notes) #if key in['Subjects']: #for val in value: #print(val.name) #return True
#!/bin/python3 import math import os import random import re import sys # # Complete the 'equalStacks' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER_ARRAY h1 # 2. INTEGER_ARRAY h2 # 3. INTEGER_ARRAY h3 # #計算stack的總共高度 def calculateheight(h): height = 0 for i in h: height += i return height def equalStacks(h1, h2, h3): height1 = calculateheight(h1) height2 = calculateheight(h2) height3 = calculateheight(h3) label1, label2, label3 = 0,0,0 result = 0 while True: if height1 == height2 and height2 == height3: #這個條件要先放前面 result = height1 break elif height1 >= height2 and height1 >= height3: #height1最高 height1 -= h1[label1] label1 += 1 elif height2 >= height1 and height2 >= height3: #height2最高 height2 -= h2[label2] label2 += 1 elif height3 >= height1 and height3 >= height2: height3 -= h3[label3] label3 += 1 return result ##Main first_multiple_input = input().rstrip().split() #the numbers of cylinders in stacks 1, 2, 3 n1 = int(first_multiple_input[0]) n2 = int(first_multiple_input[1]) n3 = int(first_multiple_input[2]) h1 = list(map(int, input().rstrip().split())) # h1 = [3, 2, 1, 1, 1] h2 = list(map(int, input().rstrip().split())) # h2 = [4, 3, 2] h3 = list(map(int, input().rstrip().split())) # h3 = [1, 1, 4, 1] result = equalStacks(h1, h2, h3) print(result)
nomor = int(input("Nomor Berapa: ")) def dot(): global nomor global num if len(nomor) > 3: num.insert(-3,".") if len(nomor) > 6: num.insert(-7,".") if len(nomor) > 9: num.insert(-11,".") def dot2(): global kali global kal if len(kali) > 3: kal.insert(-3,".") if len(kali) > 6: kal.insert(-7,".") if len(kali) > 9: kal.insert(-11,".") if nomor > 1: for i in range(2,nomor): if (nomor % i == 0): kali = nomor // i nomor = str(nomor) num = list(nomor) kali = str(kali) kal = list(kali) dot() dot2() n = "".join(num) k = "".join(kal) print("Bukan bilangan prima") print(i,"kali",k,"=", n) break else: nomor = str(nomor) num = list(nomor) dot() n = "".join(num) print(n," adalah bilangan prima") else: print("Bukan bilangan prima")
#!/usr/bin/env python # -*- coding: utf-8 -*- import re,sys regex_input = raw_input('Enter regex > ') regexp = re.compile(regex_input, re.IGNORECASE) test_email_addresses = ['abc@gmail.com', 'xyz123@hotmail.com', 'blahblah09@gmail.com'] matched_address = [] for email_address in test_email_addresses: if regexp.search(email_address): matched_address.append(email_address) print matched_address
#NOMBRES: #Reto 1 #Entradas: Cadena #Salidas: Cantidad de cada caracter #Restricciones: Se debe dar una cadena, la cadena no puede ser vacia def contarCaracteres(cadena): if(type(cadena)!=str): return "Debe indicar una cadena" elif(cadena==""): return "Cadena no valida" else: return eliminarElementosIguales(contarCaracteresAux(cadena,0)) def contarCaracteresAux(cadena,x): if(x==len(cadena)): return [] else: return [compararCaracteres(cadena[x],cadena,len(cadena)-1,0)] + contarCaracteresAux(cadena,x+1) def compararCaracteres(caracter,cadena,contador,cantidad): if(contador==-1): return [caracter,cantidad] elif(caracter==cadena[contador]): return compararCaracteres(caracter,cadena,contador-1,cantidad+1) else: return compararCaracteres(caracter,cadena,contador-1,cantidad) def eliminarElementosIguales(lista): if(lista==[]): return [] elif(seRepiteCaracter(lista[0],lista,1)==False): return [lista[0]] + eliminarElementosIguales(lista[1:]) else: return eliminarElementosIguales(lista[1:]) def seRepiteCaracter(caracter,lista,indice): if(indice==len(lista)): return False elif(caracter==lista[indice]): return True else: return seRepiteCaracter(caracter,lista,indice+1) #Reto 2 #Entradas: Lista #Salidas: Lista de vocales #Restricciones: Se debe dar una lista no vacia def crearListaVocales(lista): if(type(lista)!=list): return "Debe indicar una lista" elif(lista==[]): return "Lista vacia" else: return crearListaVocalesAux(lista,0) def crearListaVocalesAux(lista,indice): if(indice==len(lista)): return [] elif(esVocal(lista[indice])==True): return [lista[indice]]+crearListaVocalesAux(lista,indice+1) else: return crearListaVocalesAux(lista,indice+1) def esVocal(elemento): if(type(elemento)!=str): return False elemento=elemento.lower() if(elemento=="a" or elemento=="e" or elemento=="i" or elemento=="o" or elemento=="u"): return True else: return False #Reto 3 #Entradas: Elemento 1, Elemento2, Lista #Salidas: Lista con elementos sumados #Pre/Post Condiciones: Se deben dar 2 elementos, si el elemento 1 esta en la lista se agrega el elemento 2 justo despues #Restricciones: Se debe ingresar una lista def insertarElemento(elemento1,elemento2,lista): if(type(lista)!=list): return "Indicar una lista" elif(lista==[]): return [] else: return insertarElementoAux(elemento1,elemento2,lista) def insertarElementoAux(elemento1,elemento2,lista): if(lista==[]): return [] elif(lista[0]==elemento1): return [lista[0]]+[elemento2]+insertarElementoAux(elemento1,elemento2,lista[1:]) else: return [lista[0]]+insertarElementoAux(elemento1,elemento2,lista[1:]) #Reto 4 #Entradas: Lista #Salidas: Los primeros elementos en cada lista #Restricciones: Se debe dar una lista no vacia def obtenerPrimeros(lista): if(type(lista)!=list): return "Debe indicar una lista" elif(lista==[]): return "Lista vacia" else: return obtenerPrimerosAux(lista) def obtenerPrimerosAux(lista): if(lista==[]): return [] else: return extraerElemento(lista[0])+obtenerPrimerosAux(lista[1:]) def extraerElemento(lista): return [lista[0]] #Reto 5 #Entradas: Lista #Salidas: Profundidad de la lista #Restricciones: Se debe dar una lista no vacia def profundidadLista(lista): if(type(lista)!=list): return "Debe indicar una lista" elif(lista==[]): return "Lista vacia" else: return profundidadListaAux(lista,1) def profundidadListaAux(lista,profundidad): if(lista==[]): return profundidad elif(type(lista[0])==list): return profundidadListaAux(lista[1:],profundidadListaAux(lista[0],profundidad+1)-seRepiteLista(lista[1:])) else: return profundidadListaAux(lista[1:],profundidad) def seRepiteLista(lista): if(lista==[]): return 0 elif(type(lista[0])==list): return 1 else: return seRepiteLista(lista[1:]) #Reto 6 #Entradas: Lista A, Lista B #Salidas: Lista producto cartesiano A x B #Restricciones: Se deben de dar listas en A y en B def productoCartesiano(A,B): if(type(A)!=list or type(B)!=list): return "Debe indicar listas" elif(A==[] or B==[]): return [] else: return productoCartesianoAux(A,B,0) def productoCartesianoAux(A,B,indice): if(A==[]): return [] elif(indice==len(B)): return productoCartesianoAux(A[1:],B,0) else: return [[A[0]] + [B[indice]]] + productoCartesianoAux(A[0:],B,indice+1)
import random # imports the library named random def rps(): """ this plays a game of rock-paper-scissors (or a variant of that game) arguments: no arguments (prompted text doesn't count as an argument) results: no results (printing doesn't count as a result) """ user = input("Choose your weapon: ") comp = random.choice(['rock','paper','scissors']) print() print('The user (you) chose', user) print('The computer (I) chose', comp) print() if comp == 'rock' and user == 'scissors': print(f"Comp {comp} wins over user {user}") if comp == 'paper' and user == 'rock': print(f"Comp {comp} wins over user {user}") if comp == 'scissors' and user == 'paper': print(f"Comp {comp} wins over user {user}") if user == 'rock' and comp == 'scissors': print(f"User {user} wins over comp {comp}") if user == 'paper' and comp == 'rock': print(f"User {user} wins over comp {comp}") if user == 'paper' and comp == 'rock': print(f"User {user} wins over comp {comp}") if user == 'paper' and comp == 'paper': print(f"It's a draw") if user == 'rock' and comp == 'rock': print(f"It's a draw") if user == 'scissors' and comp == 'scissors': print(f"It's a draw") #test rps()
def factorial(n): ans=1 for i in range(1,n+1): ans = ans * i print(f"multiply {i}") return ans # test it print(factorial(9))
def isPrime(n): if n > 2 and n%2 == 0: return 0 i = 3 while i*i <= n: if n % i == 0: return 0 i += 2 return 1 if __name__ == '__main__': l = (input()[1:-1]).split(',') for n in reversed(sorted(l, key=lambda k: int(k))): if isPrime(int(n)): print(n) break
# # @lc app=leetcode id=124 lang=python3 # # [124] Binary Tree Maximum Path Sum # # https://leetcode.com/problems/binary-tree-maximum-path-sum/description/ # # algorithms # Hard (30.60%) # Likes: 1981 # Dislikes: 149 # Total Accepted: 221.9K # Total Submissions: 717.6K # Testcase Example: '[1,2,3]' # # Given a non-empty binary tree, find the maximum path sum. # # For this problem, a path is defined as any sequence of nodes from some # starting node to any node in the tree along the parent-child connections. The # path must contain at least one node and does not need to go through the # root. # # Example 1: # # # Input: [1,2,3] # # ⁠ 1 # ⁠ / \ # ⁠ 2 3 # # Output: 6 # # # Example 2: # # # Input: [-10,9,20,null,null,15,7] # # -10 # / \ # 9  20 # /  \ # 15   7 # # Output: 42 # # # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: current_max = -math.inf def maxPathSum(self, root: TreeNode) -> int: """ :type root: TreeNode :rtype: int """ self.maxPathSumHelper(root) return self.current_max def maxPathSumHelper(self, root): if root is None: return root left = self.maxPathSumHelper(root.left) right = self.maxPathSumHelper(root.right) left = 0 if left is None else (left if left > 0 else 0) right = 0 if right is None else (right if right > 0 else 0) self.current_max = max(left+right+root.val, self.current_max) return max(left, right) + root.val
# # @lc app=leetcode id=968 lang=python3 # # [968] Binary Tree Cameras # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minCameraCover(self, root: TreeNode) -> int: # Set cameras on all leaves' parents, then remove all covered nodes. # Repeat step 1 until all nodes are covered. self.res = 0 def dfs(root): if not root: return 2 l, r = dfs(root.left), dfs(root.right) if l == 0 or r == 0: self.res += 1 return 1 return 2 if l == 1 or r == 1 else 0 # if dfs(root) == 0 means that his left and right child all covered by their child, # the root is the only one w/o covered, so root need install a camera. return (dfs(root) == 0) + self.res
#!/usr/bin/python import hashlib import sys m = hashlib.md5() eHarmonyOtptFile = open("eHarmonyOutput.txt", 'w') #Open output file to store matched passwords passwordFile = open("eHarmony.txt", "r+") #Open the given list of hashed passwords passwordList = passwordFile.readlines() for i in range(0,len(passwordList)): passwordList[i] = passwordList[i].replace("\n","") for line in open("md5.txt", "r+"): #Open the list of passwords in the wordlist #line = line.strip() m = hashlib.md5() line = line.replace("\n","") m.update(line) #encrypt the plain text passwords in the wordlist predictedPassword = m.hexdigest() if predictedPassword==passwordList[i]: #Check if the newly hashed plain text password matched that in the given hashed password list eHarmonyOtptFile.write(passwordList[i] + " " + line) #if the above condition is true. The original is written in the output file eHarmonyOtptFile.write('\n') break passwordFile.close() eHarmonyOtptFile.close()
# Team Nintentoads (Stella Oh, Helena Williams, Jason Chan) # SoftDev # K06 -- Amalgate the KREWES # 2020-09-26 # A program that will print the name of a randomly-selected student # from team (orpheus, rex, or endymion) import random # Dictionary of team (str) and names in each team (list) KREWES = { 'orpheus': ['ERIC', 'SAUVE', 'JONATHAN', 'PAK', 'LIAM', 'WINNIE', 'KELLY', 'JEFFREY', 'KARL', 'ISHITA', 'VICTORIA', 'BENJAMIN', 'ARIB', 'AMELIA', 'CONSTANCE', 'IAN'], 'rex': ['ANYA', 'DUB-Y', 'JESSICA', 'ALVIN', 'HELENA', 'MICHELLE', 'SHENKER', 'ARI', 'STELLA', 'RENEE', 'MADELYN', 'MAC', 'RYAN', 'DRAGOS'], 'endymion': ['JASON', 'DEAN', 'MADDY', 'SAQIF', 'CINDY', 'YI LING', 'RUOSHUI', 'FB', 'MATTHEW', 'MAY', 'ERIN', 'MEIRU'] } # Prints the name of a randomly-selected student from team (orpheus, rex, or endymion) def pick_name(): team = input("orpheus, rex, or endymion: ") #ask for team name team = team.lower() #non-case sensitive if team != "orpheus" and team != "rex" and team != "endymion": #Not a teamname print("That's not one of the three") else: # picks random name from that chosen team print(random.choice(KREWES.get(team))) #test-run of random name pick_name()
while True: w=input("檢測的字串(end結束):") if w=="end": print("檢測結束") break else: s=input("檢測的單一字元:") t=w.count(s) print("字元%s出現次數為:%d" % (s,t))
M=int(input("請輸入階層值M:")) i=n=1 while (M>=i): ##True往下執行 i=i*n n+=1 print("超過M為"+str(M)+"的最小階層N值為:"+str(n-1))
# Математическая программа викторины. # # Напишите программу, которая запрашивает ответ для математического выражения, проверяет # , прав ли пользователь или нет, а затем отвечает соответствующим образом сообщением def numb(): num = int(input("Решите пример 35 + 24 - 18 = ")) num1 = int(input("128 - 69 + 17 = ")) num2 = int(input("109 + 16 - 53 = ")) return [num, num1, num2] res = numb() summ = [41, 76, 72] if res == summ: print ("OK") else: print("error in decision")
# BeautifulSoup is used to obtain the html document and for parsing from bs4 import BeautifulSoup # urllib.request for Python 3, urllib for Python 2 from urllib.request import urlopen # xlwt is used to port the data to an excel sheet import xlwt url = "https://www.cadth.ca/about-cadth/what-we-do/products-and-services/pcodr/transparency/find-a-review" # set url to scrape from html = urlopen(url) #soup = str(html.read(), 'utf-8') # create soup soup = BeautifulSoup(html, "html.parser") # create arrays for extracting information tdArray = [] brArray = [] # create arrays for storing information headings = ["Brand Name", "Generic Name", "Tumour Type", "Indication", "Review Status", "Last Updated"] brandName = [] genericName = [] tumourType = [] indication = [] reviewStatus = [] lastUpdated = [] #find all the br stuff in the soup brContent = soup.find("table", {"class" : "sortable_table"}).find_all("br") # store the br info into an array for child in brContent: brArray.append(child.string) # remove all the br content from the soup for e in soup.findAll('br'): e.extract() # find all the td stuff in the soup tdContent = soup.find("table", {"class" : "sortable_table"}).find_all("td") # store the td info into an array for child in tdContent: tdArray.append(child.string) indication = brArray # store information into arrays while tdArray: brandName.append(tdArray.pop(0)) genericName.append(tdArray.pop(0)) tumourType.append(tdArray.pop(0)) reviewStatus.append(tdArray.pop(0)) lastUpdated.append(tdArray.pop(0)) """ print(brandName) print(genericName) print(tumourType) print(indication) print(reviewStatus) print(lastUpdated) """ # store information into an excel sheet wb = xlwt.Workbook() ws = wb.add_sheet('Drugs') row = 1; column = 0; # titles / headings for x in range(0, 6): ws.write(0, x, headings.pop(0)) # rest of the data while brandName: ws.write(row, column + 0, brandName.pop(0)) ws.write(row, column + 1, genericName.pop(0)) ws.write(row, column + 2, tumourType.pop(0)) ws.write(row, column + 3, indication.pop(0)) ws.write(row, column + 4, reviewStatus.pop(0)) ws.write(row, column + 5, lastUpdated.pop(0)) row+=1 # save the excel file wb.save("drugs.xls")
from time import sleep # used to clear the terminal window from os import name, system # Verifies if the email has at least a basic resemblance to an email def get_email(): while True: email = input("Please enter your email for alert notifications: ") if '@' not in email or '.' not in email or len(email) < 6: print('Error: Please enter a valid email') sleep(2) else: return email # Gets the frequency for which the program should run. def get_check_freq(): return input("Enter the frequency for which you want the product data to be checked in minutes" "(Decimals allowed)\n") # Used to clear the terminal window def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear')
import string def compareItems((w1,c1), (w2,c2)): if c1 > c2: return - 1 elif c1 == c2: return cmp(w1, w2) else: return 1 def main(): print "Word Frequency Analyzer" print "This prints a report on the n most frequent words.\n" fname = raw_input("File to analyze: ") text = open(fname,'r').read() text = string.lower(text) for ch in """!"#$%&()*+,-./:;<=>?@[\\]?_'`{|}?""": text = string.replace(text, ch,' ') words = string.split(text) counts = {} for w in words: try: counts[w] = counts[w] + 1 except KeyError: counts[w] = 1 n = input("Output analysis of how many words? ") items =counts.items() items.sort(compareItems) for i in range(n): print "%-10s%5d" % items[i] if __name__ == '__main__': main()
""" https://leetcode.com/problems/find-all-anagrams-in-a-string/ https://app.glider.ai/practice/problem/algorithms/anagram-substring/problem Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". Example 2: Input: s: "abab" p: "ab" Output: [0, 1, 2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab". """ from collections import Counter def anagram(S, P): """ :param S: :param P: :return: """ d = Counter(P) result = [] for i, e in enumerate(S): x = Counter(S[i:len(P)+i]) if not (d-x): result.append(i) #print(i, x, '<==>', d-x) return result print(anagram('BACDGABCDA', 'ABCD')) class Solution(object): def findAnagrams(self, s, p): if len(p) > len(s): return first = dict() second = dict() for i in range(len(p)): if p[i] not in first: first[p[i]] = 1 else: first[p[i]] += 1 for i in range(len(p)): if s[i] not in second: second[s[i]] = 1 else: second[s[i]] += 1 l = [] if first == second: l.append(0) for i in range(len(p),len(s)): j = i - len(p) second[s[j]] -= 1 if second[s[j]] == 0: del second[s[j]] if s[i] not in second: second[s[i]] = 1 elif s[i] in second: second[s[i]] += 1 if first == second: l.append(j + 1) return l obj = Solution() print(obj.findAnagrams('BACDGABCDA', 'ABCD'))
def binay_search_itr(arr, x): """ https://www.geeksforgeeks.org/floor-in-a-sorted-array/ :param arr: :param x: :return: """ l = 0 h = len(arr) - 1 res = -1 while l <= h: m = l + (h - l // 2) if arr[m] == x: return arr[m] elif arr[m] > x: h = m - 1 else: res = arr[m] l = m + 1 return res print(binay_search_itr([1, 2, 8, 10, 10, 12, 19], 5))
def divide(arr): """ https://practice.geeksforgeeks.org/problems/inversion-of-array-1587115620/1# https://app.glider.ai/practice/problem/algorithms/inversion-of-array/problem :param arr: :return: """ n = len(arr) // 2 if len(arr) == 1: return arr, 0 left = arr[:n] right = arr[n:] left, left_count = divide(left) right, right_count = divide(right) count = left_count + right_count return merge(left, right, count) def merge(left, right, count): arr = [] i = j = 0 while i < len(left) and j < len(right): if left[i] > right[j]: arr.append(right[j]) j += 1 count += 1 elif left[i] == right[j]: arr.append(left[i]) arr.append(right[j]) i += 1 j += 1 else: arr.append(left[i]) i += 1 arr += right[j:] arr += left[i:] return arr, count #arr = list(map(int, '2 4 1 3 5'.split())) arr = [1, 20, 6, 4, 5] print(divide(arr))
res = [] def solve(open, closed, op): """ https://www.interviewbit.com/problems/generate-all-parentheses-ii/ :param open: :param closed: :param op: :return: """ if open == closed == 0: res.append(op) return if open != 0: op1 = op op1 += '(' solve(open - 1, closed, op1) if closed > open: op2 = op op2 += ')' solve(open, closed -1, op2) return solve(2, 3, '(') print(res)
from collections import defaultdict class Solution(object): def canFinish(self, numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ self.courseDict = defaultdict(list) for pair in prerequisites: nextCourse, prevCourse = pair[0], pair[1] self.courseDict[prevCourse].append(nextCourse) self.visitList = defaultdict(lambda: None) for course in range(numCourses): if not self.visitList[course]: if self.dfs(course) == 'CYCLE': return False return True def dfs(self, course): if self.visitList[course] == 'visited': return True if self.visitList[course] == 'visiting': return 'CYCLE' self.visitList[course] = 'visiting' for c in self.courseDict[course]: if self.dfs(c) == 'CYCLE': return 'CYCLE' self.visitList[course] = 'visited' return True s = Solution() print(s.canFinish(3, [[1, 0], [0, 2], [2, 1]]))
""" https://leetcode.com/problems/coin-change/ You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. Example 1: Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 """ class Solution: def coinChange(self, coins, amount: int) -> int: dp = [float('inf')] * (amount + 1) dp[0] = 0 for coin in coins: for x in range(coin, amount + 1): dp[x] = min(dp[x], dp[x - coin] + 1) return dp[amount] if dp[amount] != float('inf') else -1 s = Solution() print(s.coinChange([1,2,3], 6))
def isPalindrome(string): """ :param string: :return: """ return string == string[::-1] def solve(n, string): """ https://app.glider.ai/practice/problem/algorithms/rotation-of-a-palindrom/problem https://www.geeksforgeeks.org/check-given-string-rotation-palindrome/ You are given a string consisting of n lowercase Latin letters. Print "YES" (without quotes) if the given string is a clockwise rotation of a palindrome, print "NO" (without quotes) otherwise. :param n: :param string: :return: """ if isPalindrome(string): return 'YES' n = len(string) for i in range(n-1): str1 = string[i + 1:n] str2 = string[0:i + 1] if isPalindrome(str1 + str2): return 'YES' return 'NO' string = 'xxy' n = len(string) print(solve(n, string))
""" https://www.interviewbit.com/problems/repeat-and-missing-number-array/ You are given a read only array of n integers from 1 to n. Each integer appears exactly once except A which appears twice and B which is missing. Return A and B. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? Note that in your output A should precede B. Example: Input:[3 1 2 5 3] Output:[3, 4] A = 3, B = 4 """ class Solution: # @param A : tuple of integers # @return a list of integers def repeatedNumber(self, A): n = len(A) x = sum(A) - sum(set(A)) k = sum(A) - int(n * (n + 1) / 2) return [x, x - k] arr = [3, 1, 2, 5, 3] obj = Solution() print(obj.repeatedNumber(arr)) class Solution2: # @param A : tuple of integers # @return a list of integers def repeatedNumber(self, A): n = len(A) S = sum(A) Sn = (n * (n + 1)) // 2 S2 = 0 for num in A: S2 += num * num S2n = (n * (n + 1) * (2 * n + 1)) // 6 diff = S - Sn summation = (S2 - S2n) // diff D = (summation - diff) // 2 R = summation - D return [R, D] arr = [3, 1, 2, 5, 3] obj = Solution2() print(obj.repeatedNumber(arr)) class Solution3: # @param A : tuple of integers # @return a list of integers def repeatedNumber(self, A): size = len(A) + 1 count = [0] * size for val in A: count[val] += 1 res1 = 0 res2 = 0 for idx, val in enumerate(count): if val == 2: res1 = idx if val == 0: res2 = idx return res1, res2 arr = [3, 1, 2, 5, 3] obj = Solution3() print(obj.repeatedNumber(arr))
def fill_water(water, glasses, row, column): """ https://app.glider.ai/practice/problem/algorithms/water-fill-glasses/problem There is a stack of water glasses in a form of pascal triangle and a person wants to pour the water only at the topmost glass, but the capacity of each glass is 1 unit . Overflow takes place in such a way that after 1 unit, 1/2 of remaining unit gets into immediate below left glass and other half in immediate below right glass. 1 / \ 2 3 / \ / \ 4 5 6 Now the person pours K units of water in the topmost glass and wants to know how much water is there in the jth glass of the ith row. Assume that there are enough glasses in the triangle till no glass overflows. Input First line contain an integer K, second line contains an integer i and third line contains an integer j. Output Corresponding to each test case output the remaining amount of water in jth cup of the ith row correct to 6 decimal places. :param water: :param glasses: :param row: :param column: :return: """ if glasses[row][column] + water <= 1: # no overflow, so we terminate the loop glasses[row][column] += water return extra_water = glasses[row][column] + water - 1 glasses[row][column] = 1 # fill the glass fill_water(extra_water/2, glasses, row + 1, column) # divide the water into two glasses fill_water(extra_water/2, glasses, row + 1, column + 1) k = 4 n = 2-1 glasses = [[0] * (i + 1) for i in range(k)] print(glasses) position = 2 - 1 fill_water(k, glasses, 0, 0) print(glasses) print(glasses[n][position])
""" https://app.glider.ai/practice/problem/algorithms/paint/problem In Paint, when we take a Shape Filler and click on a pixel, the color of the region is replaced with a selected color. For a given screen as a 2D array (size of N x M) of colored pixels, S{X, Y} pixel and new color C, replace the color of the given pixel and all adjacent same-colored pixels with color C. Input The first line of input contains an integer N, representing the number of rows. The second line of input contains an integer M, representing the number of columns. The next N lines of input contain M space-separated integers, representing row elements as pixel colors. The next 3 lines of input contain integers X, Y, C, representing the pixel index points S(X, Y) and new color.​​​ Output Print the updated 2D matrix as a screen. Constraints 1 <= N, M <= 100 0 <= X,Y <= 100 0 <= C <= 1000 """ def search_by_direction(ar, row, col, direction, num, replace_num): """ :param ar: :param row: :param col: :param direction: :param num: :param replace_num :return: """ if row >= len(ar) or col >= len(ar[0]) or row <= -1 or col <= -1 or ar[row][col] != num: return ar[row][col] = replace_num for i, j in direction: search_by_direction(ar, row+i, col+j, direction, num, replace_num) def color(ar, X, Y, C): """ :param ar: :param X: :param Y: :param C: :return: """ row = len(ar) - 1 col = len(ar[0]) - 1 direction = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] search_by_direction(ar, row, col, direction, ar[X][Y], C) a = [[0, 0, 0, 0, 0],[0, 0, 0, 0, 0],[0, 0, 1, 1, 0],[0, 1, 1, 1, 1],[0, 0, 0, 1, 1]] color(a, 2, 2, 3) print(a)
""" https://www.interviewbit.com/problems/min-steps-in-infinite-grid/ You are given a few points on the coordinate plane and are asked to go through (or visit) all of the given points in the same order as they are given in the input. You can move from a point to any one of its eight adjacent points and it will be counted as a single step. For a given point ( x, y ), its eight adjacent points are as follows:- ( x+1, y ) ( x-1, y ) ( x, y+1 ) ( x, y-1 ) ( x+1, y+1 ) ( x-1, y+1 ) ( x+1, y-1 ) ( x-1, y-1 ) You have to visit all the given points in the same order taking the minimum number of steps. And to move from one point to another in the minimum number of steps you need to go through a path that is the shortest amongst all. See the example below for better understanding of the problem. Input:- [0, 1, 1, 2] [0, 0, 3, 4] Given points in input are ( 0, 0 ) ( 1, 0 ) ( 1, 3 ) ( 2, 4 ). With these points what you are required to do is first move from ( 0, 0 ) to ( 1, 0 ). It will take 1 step. Then move from ( 1, 0 ) to ( 1, 3 ). It will take 3 steps. Then from ( 1, 3 ) to ( 2, 4 ). And it will take 1 step (moving diagonally to upper right point). So the total steps taken will be 1+3+1. Output: 5 Hint: The minimum number of steps to move from one point, say (x1, y1), to another point, say (x2, y2), is maximum( abs(x2-x1), abs(y2-y1) ). """ class Solution: # @param A : list of integers # @param B : list of integers # @return an integer def coverPoints(self, A, B): path_count = 0 for i in range(1, len(A)): path_count += max(abs(A[i]-A[i-1]), abs(B[i]-B[i-1])) return path_count obj = Solution() print(obj.coverPoints(A=[0, 1, 1], B=[0, 1, 2]))
def countNonDecreasing(n): """ https://app.glider.ai/practice/problem/algorithms/nondecreasing-numbers/problem https://www.geeksforgeeks.org/total-number-of-non-decreasing-numbers-with-n-digits/ You have given with a count of digits N. Print the count of total non-decreasing numbers having N digits. A number is non-decreasing if every digit (except the first one) is greater than or equal to the previous digit. Input The input contains an integer N. Output Print the count of total non-decreasing numbers having N digits. Constraints 1 <= N <= 30 :param n: :return: """ N = 10 # Compute value of N*(N+1)/2*(N+2)/3 # * ....*(N+n-1)/n count = 1 for i in range(1, n + 1): count = int(count * (N + i - 1)) count = int(count / i) return count # Driver program n = 3 print(countNonDecreasing(n))
def solve(arr): """ https://www.geeksforgeeks.org/find-rotation-count-rotated-sorted-array/ :param arr: :return: """ l = 0 n = len(arr) h = n - 1 if arr[l] < arr[h]: return -1 while l <= h: m = (l + h) // 2 nxt = (m + 1) % n # rotate index of the array from the last pre = (m + n - 1) % n # rotate index of the array from the first if arr[nxt] > arr[m] and arr[pre] > arr[m]: return m elif arr[l] <= arr[m]: l = m + 1 elif arr[m] <= arr[h]: h = m - 1 return -1 arr = [4,5,6,7,0,1,2] print(solve(arr))
def binay_search_itr(arr, x): """ Given a sorted array, find the element in the array which has minimum difference with the given number. :param arr: :param x: :return: """ l = 0 h = len(arr) - 1 while l <= h: m = l + (h - l // 2) if arr[m] == x: return arr[m] elif arr[m] > x: m -= 1 h = m else: m += 1 l = m if abs(arr[l] - x) >= abs(arr[h] - x): return arr[h] else: return arr[l] arr = [1, 4, 8, 10, 15] x = 12 print(binay_search_itr(arr, x))
def divide(arr): n = len(arr) // 2 if len(arr) == 1: return arr left = arr[:n] right = arr[n:] return merge(divide(left), divide(right)) def merge(left, right): arr = [] i = j = 0 while i < len(left) and j < len(right): if left[i] > right[j]: arr.append(right[j]) j += 1 elif left[i] == right[j]: arr.append(left[i]) arr.append(right[j]) i += 1 j += 1 else: arr.append(left[i]) i += 1 arr += right[j:] arr += left[i:] return arr arr = list(map(int, '5 2 4 1 3 5'.split())) print(divide(arr))