text
stringlengths
37
1.41M
def main(): with open("input.txt", "r+") as file: content = file.readlines() valid_password_count = 0 for item in content: parameters = item.split(' ') range = parameters[0] index1 = int(range.split('-')[0])-1 index2 = int(range.split('-')[1])-1 letter = parameters[1][0] password = parameters[2].strip() count_on_index = 0 if password[index1] == letter: count_on_index += 1 if password[index2] == letter: count_on_index += 1 if count_on_index == 1: valid_password_count += 1 print(valid_password_count) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """ Created on Wed Apr 10 06:33:58 2019 @author: Hari Chukkala """ # Description of the Problem: #You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. #You may assume the two numbers do not contain any leading zero, except the number 0 itself. #Example: #Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) #Output: 7 -> 0 -> 8 #Explanation: 342 + 465 = 807. # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def get_digit(number, n): return number // 10**n % 10 def stringToIntegerList(input): return json.loads(input) def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: factor=1 left_num=0 right_num=0 left_node=l1 right_node=l2 while(True): if not left_node: break left_num=left_node.val*factor+left_num left_node=left_node.next factor=factor*10 factor=1 while(True): if not right_node: break right_num=right_node.val*factor+right_num right_node=right_node.next factor=factor*10 total=left_num+right_num dummyRoot=ListNode(0) if (total==0): return dummyRoot result=dummyRoot for i in str(total)[::-1]: result.next=ListNode(i) result=result.next result=dummyRoot.next return result
# -*- coding: utf-8 -*- """ Created on Tue Sep 20 19:55:52 2016 @author: Vivek """ # Some string gotchas # define the strings str1 = 'hello' str2 = ',' str3 = 'world' str4 = str1+str3 # do stuff with it # 1) repeat something 3 times str3 * 3 # worldworldworld # 2) substring only 'el' in 'hello' str1[1:3] # el # 3) get everything in a string except the last character # i.e left(str,len(str)-1) str3[:-1] # worl # 4) get only consecutive letters in a string str4[1:9:2] # elwr # 5) reverse the string str4[::-1] # dlrowolleh # 6) user input always returns string, even if the user inputs a number result = int(input("enter a number here: ")) # 7) you can use lexicographic order to compare letters! 'b'>'a' # True
# Ingresar palabras desde el teclado hasta ingresar la palabra FIN. Imprimir aquellas que empiecen y terminen con la misma letra. cadena = input('palabra: ') while cadena != 'FIN': if len(cadena) > 0 and cadena.endswith(cadena[0]): print(cadena) cadena = input('palabra: ')
tablero = [ '-*-*-', '--*--', '----*', '*----' ] # retorna un nuevo string con la casilla incrementada def renovar_string(a_modificar, pos, value): """Recibe un string y remplaza el caracter en pos por value. Parametros: a_modificar : str El string que se va a modificar. pos : int Posición del caracter a modificar. value : str El valor a colocar en a_mdificar[pos]. """ output = '' for i in range(len(a_modificar)): if i == pos: output += value else: output += a_modificar[i] return output def incrementar_casilla(tablero, linea_casilla, pos_x_casilla): """Incrementa en 1 una casilla dada del tablero. Para incrementar utiliza el método renovar_string. Este método se encarga de llamarlo con los valores necesarios. Parámetros: tablero : list, El tablero a modificar. linea_casilla : int Linea dónde se encuentra la casilla. pos_x_casilla : int Posición de la casilla en la linea. """ # obtiene el valor a darle a la casilla valor_casilla_incrementada = str( int(tablero[linea_casilla][pos_x_casilla]) + 1 ) # actualiza el string tablero[linea_casilla] = renovar_string( tablero[linea_casilla], pos_x_casilla, valor_casilla_incrementada ) def incrementar_linea(tablero, linea_mina, pivot): """Incrementa la cantidad de minas en pivot - 1, pivot, pivot + 1. Verifica que existan casillas a izquierda/derecha del pivot. Verifica que ninguna tenga una mina. Parámetros: tablero : list El tablero a modificar. linea_mina : int Línea del tablero que se va a modificar. pivot : int A partir de donde se buscan las casillas a izq/der. """ # si hay casilla a la izquierda y no es una mina if pivot - 1 >= 0 and tablero[linea_mina][pivot - 1] is not '*': incrementar_casilla(tablero, linea_mina, pivot - 1) # si hay casilla a la derecha y no es una mina if pivot + 1 < len(tablero[linea_mina]): if tablero[linea_mina][pivot + 1] is not '*': incrementar_casilla(tablero, linea_mina, pivot + 1) # si el 'pivot' no es una mina if tablero[linea_mina][pivot] is not '*': incrementar_casilla(tablero, linea_mina, pivot) def incrementar_minas(tablero, linea_mina, pos): """Incrementa en 1 las casillas alrededor de una mina. Recibe la posición de la mina en el tablero y: * Verifica los límites arriba/abajo. * Llama al método incrementar_linea como corresponda. Parámetros: tablero : list El tablero a modificar. linea_mina : int Linea donde está la mina. pos : int Casilla de la línea dónde está la mina """ # si hay linea arriba if linea_mina - 1 >= 0: incrementar_linea(tablero, linea_mina - 1, pos) # si hay linea abajo if linea_mina + 1 < len(tablero): incrementar_linea(tablero, linea_mina + 1, pos) # también incrementar en la linea actual incrementar_linea(tablero, linea_mina, pos) def preparar_tablero(tablero): """Modifica el tablero, remplazando '-' por '0'. Facilita la utilización del método 'incrementar_casilla'. Evita que las casillas sin minas alrededor queden en '-'. Parámetros: tablero : list El tablero a modificar. """ # recorre cada línea for i in range(len(tablero)): # el string de la línea es actualizado tablero[i] = tablero[i].replace('-', '0') def contar_minas(tablero): """Modifica el tablero para que cada casilla muestre el número de minas alrededor. Parámetros: tablero : list El tablero a modificar. """ preparar_tablero(tablero) # recorre cada linea for i in range(len(tablero)): # recorre cada caracter for j in range(len(tablero[i])): # si es una mina if tablero[i][j] == '*': incrementar_minas(tablero, i, j) def imprimir_tablero(tablero): """Imprime el tablero en forma de matriz. Parámetros: tablero : list El tablero a imprimir. """ # recorre cada línea for i in range(len(tablero)): # imprime cada caracter, separados por espacio for j in range(len(tablero[i])): print(tablero[i][j], end=' ') print() print('ANTES') print() imprimir_tablero(tablero) print() contar_minas(tablero) print('DESPUÉS') print() imprimir_tablero(tablero) print()
# Modificar el código previa para que se imprima la cadena “TIENE R” si la palabra contiene la letra r y sino, imprima “NO TIENE R”. for i in range(4): cadena = input('cadena: ') if 'r' in cadena: print('TIENE R') else: print('NO TIENE R')
# Escribir un programa que ingrese 4 palabras desde el teclado e imprima aquellas que contienen la letra “r” for i in range(4): cadena = input('cadena: ') if 'r' in cadena: print(f'cadena que contiene una \'r\': {cadena}')
""" 12.03.2019, Salı, Ankara, Türkiye Python Yazı & Tura Oyunu Orçun Madran - madran.net """ from random import randint yazi = 0 tura = 0 kere = int(input("Kaç kere? ")) for x in range(kere): gelen = randint(0,1) if gelen == 0: yazi += 1 else: tura +=1 print(str(x+1) + ". tur > Yazı:" +str(yazi) + " | Tura:" + str(tura))
# more strings and text # defining x as "theyre are %d types of people, which calls a number (the %d) x = "there are %d types of people." % 10 # defining binary as "binary" binary = "binary" # defining doNot as "don't" doNot = "don't" # defining y as "those who know %s and those who know %s", the %s will call something to be placed there y = "those who know %s and those who know %s" % (binary, doNot) # this is calling x print(x) # this is calling y print(y) # this is printing print("I said: %r.:" % x) print("i also said: '%s'." % y) hilarious = True jokeEvaluation = "isn't that joke so funny!? %r" print(jokeEvaluation % hilarious) w = "this is the left side of..." e = "a string with a right side." print(w+e) # more printing fun print("mary had a little lamb.") print("it's fleece was white as %s." % 'snow') print("and everywhere that mary went.") print("." * 10) end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" print(end1 + end2 + end3 + end4 + end5 + end6,) print(end7 + end8 + end9 + end10 + end11 + end12) # But wait! There's more: formatter = "%r %r %r %r" print(formatter % (1, 2, 3, 4)) print(formatter % ("the", "one", "nine", "nine")) print(formatter % (False, False, False, False)) print(formatter % (wooo, wooo, wooo, wooo)) # why do I use %r instead of %s in the above example? # which should I use on a regular basis? # why does %r sometimes give me single quotes around things? days = "monday tuesday wednesday thursday friday saturday sunday" months = "january\nfebruary\nmarch\napril\nmay\njune\njuly\naugust" print("here are the days: ", days) print("here are the months: ", months) print(""" there's something going on here. with the three double-quotes. we'll be able to type as much as we like. even 4 lines if we want, or 5, or 6. """) # this calls out the months function and lists them out in one line print("here are the months: %r" % months) # this calls the months and lists them out line by line rather than in just one line print("here are the months: %s" % months) # escape sequences redux tabbyCat = "\tI'm tabbed in." persianCat = "I'm split\non a line." backslashCat = "I'm \\ a \\ cat." topCat = """ # creates a list of things i'll do a list: \t* litter box chilling \t* eating ALL the snacks \t* sleeping\n\t* scratches """ # this calls the definitions we made earlier print(tabbyCat) print(persianCat) print(backslashCat) print(topCat) # Escape Seq What it does? # \\ # \' # \" # \a # \b # \f # \n # \N{name} # \r # \t # \uxxxx # \Uxxxxxxxx # \v # \ooo # \xhh # What does the following code do: # while True: # for i in ["/", "-", "|", "\\", "|"]: # print("%s\r" % i, end='') # Can you use ''' instead of """ ? question1 = input("how is your day going? ") question2 = input("") print("so, you are feeling %r and %r is ." % (age, height)) # jessie remember to ask 4 more questions dummy
""" algorithms.py: Contains the PathfindingAlgorithms class which contains various path finding functions. CSC111 Final Project by Tony He, Austin Blackman, Ifaz Alam """ from queue import PriorityQueue import pygame from matrix_graph import MatrixGraph from clock import Timer class PathfindingAlgorithms: """ A class used to store various path finding pathfinding algorithms Private Instance Attributes: - _iteration_text_background: A white pygame surface that acts as a background for the text of the iteration counter - _iteration_text_pos: A tuple that represents where to draw the iteration counter - _timer_text_background: A white pygame surface that acts as a background for the text of the timer - _timer_text_pos: A tuple that represents where to draw the timer - _maze_x_offset: An integer that represents how much the drawing of the maze needs to be shifted in the x direction inorder to account for the maze being centered - _maze_y_offset: An integer that represents how much the drawing of the maze needs to be shifted in the y direction inorder to account for the maze being centered Sample Usage: >>> algorithms = PathfindingAlgorithms((200, 200), 5, 5, (500, 500)) """ _iteration_text_background: pygame.Surface _iteration_text_pos: tuple[int, int] _timer_text_background: pygame.Surface _timer_text_pos: tuple[int, int] _maze_x_offset: int _maze_y_offset: int def __init__(self, iteration_counter_pos: tuple[int, int], maze_x_offset: int, maze_y_offset: int, timer_text_pos: tuple[int, int]) -> None: """ Initialize a PathfindingAlgorithms Object """ # Max variables are used to generate the largest background max_string = f'Nodes Searched + {1920 * 1080}' max_time = 'Timer: 99:99:99' # Assign instance attributes self._iteration_text_background = _get_text_surface(max_string) self._iteration_text_pos = iteration_counter_pos self._timer_text_pos = timer_text_pos self._timer_text_background = _get_text_surface(max_time) self._maze_x_offset = maze_x_offset self._maze_y_offset = maze_y_offset def breadth_first_search(self, graph: MatrixGraph, start: tuple, target: tuple, surface: pygame.Surface, display: pygame.Surface) \ -> list[tuple[int, int]]: """ Return a list of tuples representing the final path if target is found, return an empty list otherwise. This function is an implementation of the breadth_first_search pathfinding algorithm """ queue = [] visited = set() paths = {} # A dictionary that maps new nodes to the previous node queue.extend(graph.get_valid_neighbours(start[0], start[1])) visited.update(graph.get_valid_neighbours(start[0], start[1])) # Update paths with the original visited set for node in graph.get_valid_neighbours(start[0], start[1]): paths[node] = start found = False # Counter to store current iteration counter = 0 # Pygame clock clock = Timer() while queue != [] and not found: # Draw and update the loop iteration counter counter += 1 iteration_counter = f'Nodes Searched: {counter}' self._draw_loop_iterations(iteration_counter, surface) # Pop the current node curr = queue.pop(0) # Visualize step _ = pygame.event.get() # Call event.get to stop program from crashing on clicks curr_x = curr[0] + self._maze_x_offset + 1 curr_y = curr[1] + self._maze_y_offset + 1 pygame.draw.circle(surface, (255, 0, 0), (curr_x, curr_y), 3) display.blit(surface, (0, 0)) pygame.display.flip() if curr == target: found = True for node in graph.get_valid_neighbours(curr[0], curr[1]): if node not in visited: queue.append(node) visited.add(node) # Add the node as a key with the current node as the value paths[node] = curr clock.update_time() self._draw_timer(clock, surface) if found is False: return [] else: return self._find_and_draw_final_path(paths, start, target, surface, display) def depth_first_search_iterative(self, graph: MatrixGraph, start: tuple, target: tuple, surface: pygame.Surface, display: pygame.Surface) \ -> list[tuple[int, int]]: """ Return a list of tuples representing the final path if target is found, return an empty list otherwise. This is an iterative version of depth_first_search, since the recursive version exceeds the maximum recursion depth. """ discovered = set() stack = [start] # Stack is a reversed list for now. Later we can make a stack class if we # need paths = {} # A dictionary that maps new nodes to the previous node found = False # Variables and Surfaces used to display the current iterations counter = 0 # Pygame clock clock = Timer() while stack != [] and not found: # Draw and update the loop iteration counter counter += 1 iteration_counter = f'Nodes Searched: {counter}' self._draw_loop_iterations(iteration_counter, surface) vertex = stack.pop() # Visualize step _ = pygame.event.get() # Call event.get to stop program from crashing on clicks curr_x = vertex[0] + self._maze_x_offset + 1 curr_y = vertex[1] + self._maze_y_offset + 1 pygame.draw.circle(surface, (255, 0, 0), (curr_x, curr_y), 3) display.blit(surface, (0, 0)) pygame.display.flip() if vertex == target: found = True elif vertex not in discovered: discovered.add(vertex) neighbors = graph.get_valid_neighbours(vertex[0], vertex[1]) for neighbor in neighbors: if neighbor not in discovered: # Add the neighbor as a key in the path dictionary with vertex as a parent stack.append(neighbor) paths[neighbor] = vertex clock.update_time() self._draw_timer(clock, surface) if found is False: return [] else: return self._find_and_draw_final_path(paths, start, target, surface, display) def a_star(self, graph: MatrixGraph, start: tuple, target: tuple, surface: pygame.Surface, display: pygame.Surface) -> list[tuple[int, int]]: """ The heuristic used is the distance from target to the current node if f(n) = 0 we have reached our node, our promising choice is the min(f(n)) for each neighbour """ open_queue = PriorityQueue() open_queue.put((graph.euclidean_distance(start, target), (start, 0))) closed = {start} paths = {} # A dictionary that maps new nodes to the previous node found = False # Variables and Surfaces used to display the current iterations counter = 0 # Pygame clock clock = Timer() while not open_queue.empty() and not found: # Draw and update iteration counter counter += 1 iteration_counter = f'Nodes Searched: {counter}' self._draw_loop_iterations(iteration_counter, surface) curr = open_queue.get() closed.add(curr[1][0]) _ = pygame.event.get() # Call event.get to stop program from crashing on clicks curr_x = curr[1][0][0] + self._maze_x_offset + 1 curr_y = curr[1][0][1] + self._maze_y_offset + 1 pygame.draw.circle(surface, (255, 0, 0), (curr_x, curr_y), 3) display.blit(surface, (0, 0)) pygame.display.flip() if curr[1][0] == target: found = True neighbours = graph.get_valid_neighbours(curr[1][0][0], curr[1][0][1]) for coord in neighbours: if coord in closed: # If the neighbor has already been computed, do nothing continue if not any(tup[1][0] == coord for tup in open_queue.queue): # If the neighbor is not in the the open queue, add it # Compute the heuristic and add it to open neighbour_f = curr[1][1] + 1 + graph.euclidean_distance(target, coord) open_queue.put((neighbour_f, (coord, curr[1][1] + 1))) # Track the path paths[coord] = curr[1][0] # Update clock clock.update_time() self._draw_timer(clock, surface) if found is False: return [] else: return self._find_and_draw_final_path(paths, start, target, surface, display) def update_off_set_values(self, centered_w: int, centered_h: int) -> None: """ Update the off set attributes. This method is called when the program swaps mazes. """ self._maze_x_offset = centered_w self._maze_y_offset = centered_h def _find_and_draw_final_path(self, paths: dict[tuple[int, int], tuple[int, int]], start: tuple, target: tuple, surface: pygame.Surface, display: pygame.Surface) -> list[tuple[int, int]]: """ Return a list of tuples that corresponds to the path found by the algorithm that calls this function """ final_path_so_far = [] current_node = target while current_node != start: final_path_so_far.insert(0, current_node) current_node = paths[current_node] # Draw the final path curr_x = current_node[0] + self._maze_x_offset + 1 curr_y = current_node[1] + self._maze_y_offset + 1 pygame.draw.circle(surface, (0, 255, 0), (curr_x, curr_y), 3) # Insert the first node final_path_so_far.insert(0, start) # Draw the final path pygame.draw.circle(surface, (0, 255, 0), (start[0] + self._maze_x_offset + 1, start[1] + self._maze_y_offset + 1), 3) display.blit(surface, (0, 0)) pygame.display.flip() return final_path_so_far def _draw_loop_iterations(self, loop_iters: str, surface: pygame.Surface) -> None: """ Draw the current loop iterations at the specified position """ text_surface = pygame.font.SysFont('Arial', 20).render(loop_iters, True, (0, 0, 0)) surface.blit(self._iteration_text_background, self._iteration_text_pos) surface.blit(text_surface, self._iteration_text_pos) def _draw_timer(self, clock: Timer, surface: pygame.Surface) -> None: text_surface = clock.get_text_surface() surface.blit(self._timer_text_background, self._timer_text_pos) surface.blit(text_surface, self._timer_text_pos) def _get_text_surface(longest_text: str) -> pygame.Surface: """ Return a white box that is the size of the maximum possible text being rendered """ text_surface = pygame.font.SysFont('Arial', 20).render(longest_text, True, (0, 0, 0)) text_h = text_surface.get_height() text_w = text_surface.get_width() white = pygame.Surface((text_w, text_h)) white.fill((255, 255, 255)) return white if __name__ == '__main__': import python_ta import python_ta.contracts python_ta.contracts.check_all_contracts() python_ta.check_all(config={ 'extra-imports': ['pygame', 'matrix_graph', 'typing', 'clock', 'queue'], 'allowed-io': [], # the names (strs) of functions that call print/open/input 'max-line-length': 100, 'disable': ['E1136'] })
''' Problem 9: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ''' import math def solve(): answer = 1 numInput = 1000 for a in range(1,numInput+1): for b in range(1,numInput+1): prod = a**2 + b**2 c = math.sqrt(prod) if(c%1==0 and a+b+c==numInput and a<b<c): answer = a*b*c print(answer)
"""Maintaining overall state """ import sys import pygame from alphabet import Alphabet from ledboard import Ledboard #from pygame.locals import * class Timetable(): """Class to maintain the state of the timetable """ def __init__(self, rows, columns): """Timetable contains representation of the strings that are shown and manages all updates Args: rows (int): number of lines (strings) perceived by user on the led board columns (int): number of chars per line """ self.ledboard = Ledboard(columns*(5+1), rows*(7+1)) self.rows = rows self.columns = columns self.times = [[" " for col in columns] for row in rows] self.dotsize = 6 self.alphabet = Alphabet() pygame.init() while True: pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() def set_time_entry(self, position, entry): """Sets the time entry at a given position Args: position (int): 0 based entry position entry (str): string to be shown """ self.times[position] = entry def update(self): """Updates the LED board """ for r_idx, time in enumerate(self.times): print(f"{r_idx} {time}") def print(self): """Prints the current state to the console """ print(self.alphabet.A)
# Gelin Eguinosa Rosique import time class TimeKeeper: """ Class to keep track of the time the programs expends processing the information. It doesn't count the time the program expends waiting for input from the user. """ def __init__(self): """ Create the basic variables to keep track of the running time of the program. """ # Initialize variables self.start_time = time.time() self.runtime = 0 # Set the state of the recording self.current_state = 'running' def pause(self): """ Stop recording the time, until the user commands it to start recording again. """ # Check if the TimeKeeper is currently running, otherwise we don't need # to anything. if self.current_state == 'running': # Update the total runtime of the program. self.runtime += time.time() - self.start_time # Update the state of the recording self.current_state = 'pause' def restart(self): """ Resets the start time of the TimeKeeper, either if it is currently on pause or running. As a result, it continues recording if it was on pause, or resets the time if it was currently running. """ # Reset the value of the start time self.start_time = time.time() # Update the state of the recording self.current_state = 'running' def run_time(self): """ Transforms the elapsed time from the start of the program to a new format in hours, minutes and seconds. :return: A string containing the elapsed time in <hours:minutes:seconds> """ # Update the runtime value only is the TimeKeeper was running. if self.current_state == 'running': self.runtime += time.time() - self.start_time # Reset the start time, to avoid adding the same segment again self.start_time = time.time() # Calculating the hours, minutes, seconds and milliseconds hours = int(self.runtime / 3600) minutes = int((self.runtime - hours * 3600) / 60) seconds = int(self.runtime - hours * 3600 - minutes * 60) milliseconds = int((self.runtime - int(self.runtime)) * 1000) return f'{hours} h : {minutes} min : {seconds} sec : {milliseconds} mill'
from urllib2 import urlopen from BeautifulSoup import BeautifulSoup url = "https://en.wikipedia.org/wiki/Game_of_Thrones#cite_note-S1avgS2ratings-276" response = urlopen(url).read() wiki = BeautifulSoup(response) viewer_numbers_file = open("viewer_numbers.csv", "w") viewer_numbers_file.write("The number of viewers of first-airing episodes of Game of Thrones in the US is: \n\n") print "The number of viewers of first-airing episodes of Game of Thrones in the US is: \n" table = wiki.findAll("table", attrs={"class": "wikitable"}) all_views = 0 for table_row in table[1].findAll("tr"): for table_data in table_row.findAll("td"): all_table_data = table_data.string odvec = "N/A" if all_table_data is not None and all_table_data != odvec: views = float(all_table_data) all_views += views print str(all_views) + " millions." viewer_numbers_file.write(str(all_views) + " millions. \n") viewer_numbers_file.close()
"""Implements class DecisionTreeclassifier, to - hold input data (attributes, classes), - fit a binary decision tree to efficiently decide a predicted class for an input row of data - make predictions Attributes: rows colnames (not currently used) tree (added by fit() method) Methods: fit() predict() Major helper functions defined: make_tree() gini_impurity() imformation_gain() Uses recursion to build a tree from input data rows. Uses Gini Impurity and Information Gain functions to find optimal evolution of binary tree. """ class DecisionTree: def __init__(self, rows, colnames=None): self.rows = rows if colnames is None: colnames = ['column_' + str(i) for i in range(len(rows[0]))] def fit(self): self.tree = build_tree(self.rows) def predict(self, data): """Wrapper method to run 'predict_inner.'""" # TODO: unify classes 'DecisionTree' and 'DecisionNode' # They are basically the same thing. node = self.tree return predict_inner(data, node) def predict_inner(row, node): """Helper function to be called by wrapper method 'predict'.""" # Base case: Leaf node. if isinstance(node, LeafNode): return node.predictions # Recurse case. # Use this node's tester to choose a side to recurse down. if node.tester.passes(row): return predict_inner(row, node.true_side) else: return predict_inner(row, node.false_side) class DecisionNode: """Holds a test to be applied, and pointers to two child nodes. Each child node can be a further DecisionNode, or a LeafNode. """ def __init__(self, tester, true_side, false_side): self.tester = tester self.true_side = true_side self.false_side = false_side class LeafNode: """Holds info about features. A single entry dict of feature value (classification) and the count of times the feature value appears in the overall input set. """ def __init__(self, rows): self.predictions = tally(rows) def distinct(rows, col): """Return the set of values from a specific column in a matrix.""" return set([row[col] for row in rows]) def tally(rows): """Counts occurrences of specific values. Returns a dict of label: count pairs.""" tal = {} for row in rows: # label is rightmost column label = row[-1] if label not in tal: tal[label] = 0 # add an entry for a new label tal[label] += 1 return tal class Tester: """A test to choose to which of two lists a tested row should be added.""" def __init__(self, col, val): self.col = col # index of a column in a matrix. Identifies a 'variable' self.val = val # the value of a 'variable' def passes(self, test_case): # Compare the feature value to a test value. test_val = test_case[self.col] if isinstance(self.val, int) or isinstance(self.val,float): # use greater than or equal for numeric values return test_val >= self.val else: # use double equals for string values return test_val == self.val def __repr__(self): # Print the actual test being applied. if isinstance(self.val, int) or isinstance(self.val,float): test = ">=" else: test = "==" return f"Test whether {str(self.val)} matches column {self.col}, using {test}" def split(data_rows, test): """Divides a data set into two 'child' datasets, using a test. For each row, if the test returns True, that row will be added to the list 'true_rows'. If the test does not return True, the row is added to 'false rows'. """ true_rows = [] false_rows = [] for row_to_test in data_rows: if test.passes(row_to_test): true_rows.append(row_to_test) else: false_rows.append(row_to_test) return true_rows, false_rows def gini_impurity(rows): """Calculate the Gini impurity for a set of values in rows. """ label_counts = tally(rows) impurity = 1 # start with complete impurity # adjust impurity for each label for label in label_counts: label_probability = label_counts[label] / float(len(rows)) impurity -= label_probability**2 return impurity def information_gain(left_child, right_child, uncertainty): """Information Gain. Defined as the result of subtracting the WEIGHTED impurities of two CHILDREN from UNCERTAINTY of the CURRENT node. """ prob = float(len(left_child)) / (len(left_child) + len(right_child)) ig = uncertainty - prob * gini_impurity(left_child) - (1 - prob) * gini_impurity(right_child) return ig def best_split(rows): """Given a set of observations, - iterate over each pair of feature and value. - Calculate information gain. - Retain best pair each iteration. - Return final best pair.""" # Initialize variables to track best gain and # the test question used to get that gain. best_gain = 0 best_test_q = None # keep train of the feature / value that produced it uncertainty = gini_impurity(rows) col_count = len(rows[0]) - 1 for col in range(col_count): # iterate over features distinct_vals = set([row[col] for row in rows]) for val in distinct_vals: test_question = Tester(col, val) # Try to split rows into subsets true_rows, false_rows = split(rows, test_question) # If there is no split, ignore. if len(true_rows) == 0 or len(false_rows) == 0: continue # Calculate information gain gain = information_gain(true_rows, false_rows, uncertainty) if gain > best_gain: best_gain, best_test_q = gain, test_question return best_gain, best_test_q def build_tree(rows): """Recursively builds a decision tree to classify entries in the input rows. DecisionNodes hold test questions and subtrees. LeafNodes hold feature classifications and counts of those. """ # Split the data (if possible). # find information gain per possible tests. # get best test. gain, tester = best_split(rows) # Base case: stop recursing, because we cannot gain # more info by testing. # Create a LeafNode. if gain == 0: return LeafNode(rows) # Recursive case. We found a test that delivers info gain. # Extend tree. true_rows, false_rows = split(rows, tester) true_subtree = build_tree(true_rows) false_subtree = build_tree(false_rows) # Build DecisionNode using subtrees just built, and the best test found. return DecisionNode(tester, true_subtree, false_subtree) def print_tree(node, spacing=""): """Print out tree structure.""" # Base case: Leaf node if isinstance(node, LeafNode): print (spacing + "Prediction: ", node.predictions) return print (spacing + str(node.tester)) # Recurse down true branch print (spacing + '--> True:') print_tree(node.true_side, spacing + " ") # Recurse down false branch print (spacing + '--> False:') print_tree(node.false_side, spacing + " ") # training_data = [ # ['Green', 3, 'Apple'], # ['Yellow', 3, 'Apple'], # ['Red', 1, 'Grape'], # ['Red', 1, 'Grape'], # ['Yellow', 3, 'Lemon'], # ] # # In[15]: # too = DecisionTree(training_data) # too.fit() # too.predict(training_data[0])
"""This file contains the Phonebook functionality.""" import os class Phonebook(): """Phonebook Class.""" def __init__(self, cachedir): """The constructor for the Phonebook class.""" self.entries = {} self.filename = "phonebook.txt" self.file_cache = open(os.path.join(str(cachedir), self.filename), "w") def add(self, name, number): """Method that adds a name and number to the phonebook.""" self.entries[name] = number def lookup(self, name): """Method that looks up a name in the phonebook.""" return self.entries[name] def names(self): """Method that looks up names in the phonebook.""" return self.entries.keys() def numbers(self): """Method that looks up numbers in the phonebook.""" return self.entries.values() def clear(self): """Method that closes the created file and removes it.""" self.entries = {} self.file_cache.close() os.remove(self.filename)
# Simple function demo # check for prime number def is_prime(number): divider = 2 while divider < number / 2: # bis zur Hälfte if number % divider == 0: # Zahl lässt sich ohne Rest teilen return False divider = divider + 1 return True i = 2 while i < 100: if is_prime(i): print(i) i += 1 print()
import multiprocessing as mp import traceback import random import time # This routine is actually the routine that is parallelized. All parallel # processes do nothing but run this routine. Everything else is handled by # the handler and the main. def myWorker(input_queue, output_queue, start_time): # This is just a nice thing to track which process accomplished the work my_name = mp.current_process().name # loop until told to break. while True: try: # get the next element in the queue task = input_queue.get() try: # if the first element in the queue task is None, it means # we are done and the process can terminate if task[0] is None: break # the task to be accomplished is the second element in the queue # perform the work assigned to the parallel process - in this case # the task is to sleep for a specified number of seconds. time.sleep(task[1]) # output a message that the task has been completed my_message = "(%s): PROCESSED LIST ELEMENT %s BY SLEEPING FOR %s SECONDS WITH A TOTAL RUN TIME OF " % (my_name.upper(), task[0], task[1]) output_queue.put((1,my_message)) except: # there was an error performing the task. Output a message indicating # there was an error and what the error was. output_queue.put((2,traceback.format_exc())) except: # there is no task currently in the queue. Wait and check again time.sleep(1) # the tasks have all been cleared by the queue, and the processes has been # instructed to terminate. Send a message indicating it is terminating/exiting output_queue.put((0,"(%s) FINISHED PROCESSING AND IS READY TO TERMINATE WITH A TOTAL RUN TIME OF %s SECONDS" % (my_name.upper(),(time.mktime(time.localtime())-time.mktime(start_time))))) return # This routine preps, manages, and terminates the parallel processes def myHandler(sleeper_list, pool_size, start_time): # establish connections to the input and output queues input_queue = mp.Queue() output_queue = mp.Queue() # load the queue with the tasks to be accomplished for i in range(len(sleeper_list)): input_queue.put((i,sleeper_list[i])) print('(MASTER): COMPLETED LOADING QUEUE WITH TASKS WITH A TOTAL RUN TIME OF %s' % (time.mktime(time.localtime())-time.mktime(start_time))) # load the queue with sentinals/poison pills that terminate the parallel processes for i in range(pool_size*2): input_queue.put((None,None)) print('(MASTER): COMPLETED LOADING QUEUE WITH NONES WITH A TOTAL RUN TIME OF %s' % (time.mktime(time.localtime())-time.mktime(start_time))) # create the parallel processes my_processes = [mp.Process(target=myWorker,args=(input_queue,output_queue, start_time)) for _ in range(pool_size)] # start the parallel processes for p in my_processes: p.start() # manage the results provided by each of the parallel processes counter = 0 # this variable is used to count the number of solutions we # are looking for so that we know when we are done while counter < len(sleeper_list): try: result = output_queue.get() try: # if result = 1, then we know this is a "countable" output if result[0] == 1: counter += 1 running_time = time.mktime(time.localtime())-time.mktime(start_time) my_message = result[1] + str(running_time) print(my_message) # if result = 0, then we know this is information that is useful, but # not a countable output elif result[0] == 0: my_message = result[1] print(my_message) # any other type of result indicates we had an error and we want to # see what the error was so we can fix it. This is what makes # parallel processing so hard else: print(result) except: # There was an error in processing the queue result, output # the error message print(traceback.format_exc()) except: # there was nothing in the queue (yet) wait a little and check again time.sleep(.5) # stop the routine from moving forward until all processes have completed # their assigned task. Without this, you will get an error for p in my_processes: p.join() # now that all processes are completed, terminate them all - you don't want # to tie up the CPU with zombie processes for p in my_processes: p.terminate() # the way we have written the handler, it is possible there are still # messages in the output queue that need to be delivered (the parallel process # received the sentinal, terminated, send a message and all of this happened # after we processed the correct number of outputs). So lets make sure the # output queue is empty. If not, then output the messages number_tasks = output_queue.qsize() for i in range(number_tasks): print(output_queue.get_nowait()[1]) # There may be some left over "Nones" in the input queue. Let's clear # them out since we want to account for all tasks (good housekeeping) number_tasks = input_queue.qsize() for i in range(number_tasks): try: input_queue.get_nowait() except: pass # close out the handler process print('(MASTER): COMPLETED FLUSHING QUEUE WITH A TOTAL RUN TIME OF %s' % (time.mktime(time.localtime())-time.mktime(start_time))) return def main(): # set the start time start_time = time.localtime() # set the parameters that we want to be able to change list_size = 25 # the size of the list that holds the sleep time pool_size = 4 # the number of parallel processes we want to run my_seed = 11111124 # the seed number we use in all three experiments # so that we know we are processing the same tasks random.seed(my_seed) # fix the seed value for the random number generator # instantiate and populate the list of sleep times (for real problems these # would be the individual tasks we are trying to complete) sleeper_list = [] for i in range(list_size): sleeper_list.append(random.randint(1,4)) # call the routine that manages the pool of processes myHandler(sleeper_list, pool_size, start_time) # notify that the process is done print('(MASTER): ALL PROCESSES HAVE COMPLETED WITH A TOTAL RUN TIME OF %s' % (time.mktime(time.localtime())-time.mktime(start_time))) return if __name__ == "__main__": main()
#!/usr/bin/python from Employee import Employee def main(): name = raw_input("What's your name? ") age = raw_input("What's your age? ") position = raw_input("What is your position? ") e = Employee() e.create(name,age,position) if __name__ == "__main__": main()
#Creadting and writing a file fw = open('sample.txt', 'w') fw.write('This file is created using a python script, Sounds Amazing. Right?\n') fw.write('I like Bacon\n') fw.close() #Reading a file fr = open('sample.txt','r') text = fr.read() print(text) fr.close()
import random import numpy as np import matplotlib.pyplot as plt possible = 6 dice = 2 size = possible*dice mean = [] frequency = [] i = 0 while(i<size): d1 = random.randint(1,6) d2 = random.randint(1,6) avg = (d1+d2)/2 mean.append(avg) # index = ((mean[i]*2)-1) # frequency.append(index) i = i+1 # print(frequency) mean.sort() print(mean) i = 0 j = 0 # plt.bar(frequency,mean) # plt.show() print(freq)
magicNumber = 17 # Ok this program finds a magic number print(5+4) #Break here print("Kushal"+"Sharma") print("Kushal",17) for n in range(101): if n is magicNumber: print(n,"is the magic number") break else: print(n) #Continue here numbersTaken = [2,9,13,12,17] print("Here are the numbers that are still available") for n in range(1,30): if n in numbersTaken: continue print(n) else: print(n)
# i = 0 def series_sum(n): i = 0 add = 0 while(i<n): add = add + 1/n n = n+3 i = i+1 return add
""" Including some customized plot """ from .basic_import import * import matplotlib import matplotlib.pyplot as plt def bar_plot(sizes, labels, bar_ylabel, bar_title, colors=None, with_show=False): """ Draw barplot with count on top Code from https://www.kaggle.com/phunghieu/a-quick-simple-eda """ y_pos = np.arange(len(labels)) barlist = plt.bar(y_pos, sizes, align='center') plt.xticks(y_pos, labels) plt.ylabel(bar_ylabel) plt.title(bar_title) if colors is not None: for idx, item in enumerate(barlist): item.set_color(colors[idx]) def autolabel(rects): """ Attach a text label above each bar, displaying its height """ for rect in rects: height = rect.get_height() plt.text( rect.get_x() + rect.get_width() / 2., height, \ '%d' % int(height), ha='center', va='bottom', fontweight='bold' ) autolabel(barlist) if with_show: plt.show() def bar_plot_from_one_col(df, bar_ylabel='Freq', bar_title='Counting freq', colors=None, with_show=False): """ Barplot given a list of values """ if isinstance(df, pd.DataFrame): col = list(df.columns) if col.__len__() != 1: raise Exception("Input dataframe should have one column only") plot_target = deepcopy(df[col]).values else: # pd.Series, np.array, list.. plot_target = deepcopy(df) bar_plot_params = {'bar_ylabel': bar_ylabel, 'bar_title': bar_title, 'colors': colors, 'with_show': with_show} unique_val, counts = np.unique(plot_target, return_counts=True) bar_plot(counts, labels=[label for label in unique_val], **bar_plot_params)
op=float(input("Enter yesterday open price:")) hp=float(input("Enter yesterday high price:")) lp=float(input("Enter yesterday low price:")) cp=float(input("Enter yesterday close price:")) oc=float(input("Enter today open price:")) hc=float(input("Enter today high price:")) lc=float(input("Enter today low price:")) cc=float(input("Enter today close price:")) #mdlist=[[op,hp,lp,cp],[oc,hc,lc,cc]] def is_inside_bar(op,hp,lp,cp,oc,hc,lc,cc): if hc < hp and lc > lp: print("Today's candle fulfills the inside bar pattern") else: print("Today's candle doesn't fulfill the inside bar pattern") def is_bullish_engulfing(op,hp,lp,cp,oc,hc,lc,cc): if oc <= cp and cc > op: print("Today's candle fulfills the bullish engulfing pattern") else: print("Today's candle doesn't fulfill the bullish engulging pattern") def is_bearish_engulfing(op,hp,lp,cp,oc,hc,lc,cc): if oc >= cp and cc < op: print("Today's candle fulfills the bearish engulfing pattern") else: print("Today's candle doesn't fulfill the bearish engulging pattern") def is_harami(op,hp,lp,cp,oc,hc,lc,cc): if hc < hp and hc < op and lc > cp and lc > lp and oc < cc: print("Today's candle fulfills the harami pattern") elif hc < hp and hc < cp and lc > op and lc > lp and oc > cc: print("Today's candle fulfills the harami pattern") else: print("Today's candle doesn't fulfill the harami pattern") def is_rising_sun(op,hp,lp,cp,oc,hc,lc,cc): if lc < lp and lc < cp and oc < cp and hc < hp and cc < op and hc < op and oc < cc: print("Today's candle fulfills the rising sun pattern") else: print("Today's candle doesn't fulfill the rising sun pattern") def is_darkcloud_cover(op,hp,lp,cp,oc,hc,lc,cc): if lc > lp and lc > op and cc > op and hc > hp and oc > cp and hc > cp and oc > cc: print("Today's candle fulfills the dark cloud cover pattern") else: print("Today's candle doesn't fulfill the dark cloud cover pattern") is_inside_bar(op,hp,lp,cp,oc,hc,lc,cc) is_bullish_engulfing(op,hp,lp,cp,oc,hc,lc,cc) is_bearish_engulfing(op,hp,lp,cp,oc,hc,lc,cc) is_harami(op,hp,lp,cp,oc,hc,lc,cc) is_rising_sun(op,hp,lp,cp,oc,hc,lc,cc) is_darkcloud_cover(op,hp,lp,cp,oc,hc,lc,cc)
def insidebar(open,high,low,close,volume): insidebarlist=[False] for i in range(len(high)): if i==len(high)-1: break elif high[i+1]<high[i] and low[i+1]>low[i]: insidebarlist.append(True) else: insidebarlist.append(False) return insidebarlist def bullishengulfing(open,high,low,close,volume): bullishengulfinglist=[False] for i in range(len(open)): if i==len(open)-1: break elif open[i+1]<=close[i] and close[i+1]>open[i] and close[i+1]>open[i+1] and close[i]<open[i]: bullishengulfinglist.append(True) else: bullishengulfinglist.append(False) return bullishengulfinglist def bearishengulfing(open,high,low,close,volume): bearishengulfinglist=[False] for i in range(len(open)): if i==len(open)-1: break elif open[i+1]>=close[i] and close[i+1]<open[i] and close[i+1]<open[i+1] and close[i]>open[i]: bearishengulfinglist.append(True) else: bearishengulfinglist.append(False) return bearishengulfinglist def harami(open,high,low,close,volume): haramilist=[False] for i in range(len(high)): if i==len(high)-1: break elif high[i+1] < high[i] and high[i+1] < open[i] and low[i+1] > close[i] and low[i+1] > low[i] and open[i+1] < close[i+1]: haramilist.append(True) elif high[i+1] < high[i] and high[i+1] < close[i] and low[i+1] > open[i] and low[i+1] > low[i] and open[i+1] > close[i+1]: haramilist.append(True) else: haramilist.append(False) return haramilist def risingsun(open,high,low,close,volume): risingsunlist=[False] for i in range(len(low)): if i==len(low)-1: break elif low[i+1] < low[i] and low[i+1] < close[i] and open[i+1] < close[i] and high[i+1] < high[i] and close[i+1] < open[i] and high[i+1] < open[i] and open[i+1] < close[i+1]: risingsunlist.append(True) else: risingsunlist.append(False) return risingsunlist def darkcloud(open,high,low,close,volume): darkcloudlist=[False] for i in range(len(low)): if i==len(low)-1: break elif low[i+1] > low[i] and low[i+1] > open[i] and close[i+1] > open[i] and high[i+1] > high[i] and open[i+1] > close[i] and high[i+1] > close[i] and open[i+1] > close[i+1]: darkcloudlist.append(True) else: darkcloudlist.append(False) return darkcloudlist
'''This program is used to print the length of a string''' name=input("Enter your name:") print("Length of your name is:",len(name)) #Printing length of entered string '''This program is used to check if a string is palindrome or not''' enteredstring=(input("Enter your text:")).lower() reversedstring="" length=len(enteredstring) for i in reversed(enteredstring): #iterating string in reverse order reversedstring=reversedstring+i if enteredstring==reversedstring: print("Your string {} is a palindrome string".format(enteredstring)) else: print("Your string {} is not a palindrome string".format(enteredstring)) '''This program is used to check if today's closing price in nifty is higher than last 52 week high or not''' todaycp=float(input("Enter today's closing price of Nifty:")) highprice52wk=float(input("Enter last 52 week high price:")) if todaycp>highprice52wk: #Checking condition if today's close is higher than 52 week high print("Today's closing price higher than last 52 week high price") else: print("Today's closing price is lower than last 52 week high price")
cp=float(input("Enter today's closing price:")) sma20=float(input("Enter 20 ma:")) sma50=float(input("Enter 50 ma:")) if cp>sma20 and cp>sma50: if sma20>sma50: print("Go long") elif cp<sma20 and cp<sma50: if sma20<sma50: print("Go Short") else: print("Dont do anything")
name=input("Please enter your name:") print("Entered Name:",name)
pdo=float(input("Enter previous day open:")) pdl=float(input("Enter previous day low:")) pdh=float(input("Enter previous day high:")) pdc=float(input("Enter previous day close:")) P=(pdh+pdl+pdc)/3 R1=(2*P) -pdl R2=P+(pdh-pdl) R3=R1+(pdh-pdl) S1=(2*P)-pdh S2=P-(pdh-pdl) S3=S1-(pdh-pdl) print("Pivot:{} Resistance1:{} Resistance2:{} Resistance3:{} Support1:{} Support2:{} Support3:{}" .format(P,R1,R2,R3,S1,S2,S3))
from __future__ import print_function print('hello') x = '90' if x == '80' : print('test > 80') else: print('aaa') for i in range(1, 10): for j in range(1, 10): print(i*j,end = " ") print(end = "\n") #list print('==== list ====') list = [1,2,3,4,5] print(list) for i in range(0, len(list)): print(list[i]) #dict print('==== dict ====') dict = {0:'zero', 1:'one'} print(dict) for i in dict: print(dict[i])
from collections import deque def person_is_seller(name): ''' 这里判断 被 监察人 的姓名是否以"m"结尾 ''' return name[-1] == 'm' def dfs_search(name): # 创建一个队列 search_queue = deque() # 将邻居都加入到这个搜索队列中 search_queue += graph[name] searched = [] while search_queue: # 左边弹出,先进先出 person = search_queue.popleft() if person not in searched: if person_is_seller(person): print(person + ' is a mango seller!') return True else: search_queue += graph[person] searched.append(person) return False if __name__ == '__main__': # 实现图 graph = {} # 一度关系 graph['you'] = ['alice', 'bob', 'clarie'] # 二度关系 graph['bob'] = ['anuj', 'peggy'] graph['alice'] = ['peggy'] graph['clarie'] = ['jonny', 'thom'] # 三度关系 graph['anuj'] = [] graph['peggy'] = [] graph['thom'] = [] graph['jonny'] = [] dfs_search('you')
def merge_sort(array): if len(array) < 2: return array mid = int(len(array) / 2) # 左边 lo = merge_sort(array[:mid]) # 右边 hi = merge_sort(array[mid:]) merged_arr = [] while lo and hi: merged_arr.append(lo.pop(0) if lo[0] <= hi[0] else hi.pop(0)) merged_arr.extend(hi if hi else lo) return merged_arr test_arr = [1, 2, 123, 10, 0, 300, 100] print(merge_sort(test_arr))
def recursion(n): """ # fibonacci # 递归的形式: # f(n) = f(n-1) + f(n-2) """ # 1. base case/stop case if n == 1 or n == 2: return 1 # 2. recursive case return recursion(n - 1) + recursion(n - 2) """ DFS: 深度优先搜索 BFS: 广度优先搜索 """ import numpy as np dim = 4 grid = [[1, 0, 1, 0], [1, 0, 1, 0], [0, 1, 0, 1], [1, 1, 1, 0], ] print(grid) def dfs_recursion(cur_x, cur_y): print(cur_x, cur_y) grid[cur_y][cur_x] = 0 directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] valid_points = [] for dir_x, dir_y in directions: next_x, next_y = cur_x + dir_x, cur_y + dir_y if 0 <= next_x < dim and 0 <= next_y < dim and grid[next_y][next_x] == 1: valid_points.append((next_x, next_y)) # stop case / base case if len(valid_points) == 0: return # recursive case else: for next_x, next_y in valid_points: dfs_recursion(next_x, next_y) def dfs_recursion01(cur_x, cur_y): print(cur_x, cur_y) # 访问过的,不再访问, 改变原图,设置为0 grid[cur_y][cur_x] = 0 directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] valid_points = [] for dir_x, dir_y in directions: next_x, next_y = cur_x + dir_x, cur_y + dir_y if 0 <= next_x < dim and 0 <= next_y < dim and grid[next_y][next_x] == 1: dfs_recursion01(next_x, next_y) valid_points.append((next_x, next_y)) def dfs_recursion_visited(cur_x, cur_y, visited): # 访问过的,不再访问 visited.append((cur_x, cur_y)) directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] for dir_x, dir_y in directions: next_x, next_y = cur_x + dir_x, cur_y + dir_y if 0 <= next_x < dim and 0 <= next_y < dim \ and grid[next_y][next_x] == 1 \ and (next_x, next_y) not in visited: dfs_recursion_visited(next_x, next_y, visited) """ ------------------------------------------------ """ def number_of_component(cur_x, cur_y, component_id, ): # 访问过的,不再访问 grid[cur_y][cur_x] = component_id directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] for dir_x, dir_y in directions: next_x, next_y = cur_x + dir_x, cur_y + dir_y if 0 <= next_x < dim and 0 <= next_y < dim \ and grid[next_y][next_x] == 1: number_of_component(next_x, next_y, component_id) def check_components(): component_id = 2 for y in range(dim): for x in range(dim): if grid[y][x] == 1: number_of_component(x, y, component_id) component_id += 1 print(" number of components: ", component_id - 2) """ ------------------------------------------------ """ # dfs_recursion(0, 0) # dfs_recursion01(0,0) print(grid) all_visited = [] components = [] for y in range(dim): for x in range(dim): if grid[y][x] == 1 and (x, y) not in all_visited: cur_visited = [] dfs_recursion_visited(x, y, cur_visited) print('start points: ', cur_visited) all_visited.extend(cur_visited) components.append(cur_visited) print(components) print(len(components)) print("----------------------------") # check_components() def iteration(): """使用非递归的方式实现dfs""" all_visited = [] for y in range(dim): for x in range(dim): if grid[y][x] == 1 and (x, y) not in all_visited: stack = [(x, y)] while stack: cur_x, cur_y = stack.pop() all_visited.append((cur_x, cur_y)) directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] for dir_x, dir_y in directions: next_x, next_y = cur_x + dir_x, cur_y + dir_y if 0 <= next_x < dim and 0 <= next_y < dim \ and grid[next_y][next_x] == 1: stack.append((next_x, next_y)) # bfs # queue def bfs_iteration(): """ queue 实现 bfs """ visited = [] directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] for y in range(dim): for x in range(dim): if grid[y][x] == 1 and (x, y) not in visited: queue = [(x, y)] visited.append((x, y)) while queue: # queue从左边弹出 cur_x, cur_y = queue.pop(0) for dir_x, dir_y in directions: next_x, next_y = cur_x + dir_x, cur_y + dir_y if 0 <= next_x < dim and 0 <= next_y < dim \ and grid[next_y][next_x] == 1 and (next_x, next_y) not in visited: visited.append((next_x, next_y)) queue.append((next_x, next_y)) print(visited) return bfs_iteration()
#!/usr/bin/python #coding=utf-8 # a = input() l = [ [1],[1,1] ] # 定义一个列表 for i in range(2,10): # 通过for 函数在 范围(2 , a)中取值赋值给I # print l # 输出l 在这里不需要输出。 l.append([1,1]) # 在l 中添加一个 for j in range(1,i): l[i].insert(j,(l[i-1][j-1]+l[i-1][j])) for x in l: print x
def binary(decimal): if decimal==0: return binary(int(decimal/2)) print(decimal%2, end="") return def asciiBin(string): for i in string: binary(ord(i)) print(' ') asciiBin('abc')
from copy import deepcopy from color import * import numpy as np class Matrix: n, m = 0, 0 matrix = list() def __init__(self, n, m, list_of_lists=None): self.n, self.m = n, m if list_of_lists: self.matrix = deepcopy(list_of_lists) else: self.matrix = np.full((n, m), 0) def output(self): print(TURQUOISE, end='') for i in range(self.n): for j in range(self.m): print(self.matrix[i][j], end=' ') print() def fill(self, list_of_lists): self.matrix = deepcopy(list_of_lists) def size(self): return (self.n, self.m) def __getitem__(self, index): return self.matrix[index] def __setitem__(self, key, value): self.matrix[key] = value
# -*- coding: utf-8 -*- #Decorator的使用 #The usage of decorator in python import functools def log(*text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): if text: print 'begin call %s %s():' % (text[0], func.__name__) rst = func(*args, **kw) print 'end call %s %s():' % (text[0], func.__name__) return rst else: print 'begin call %s():' % (func.__name__) rst = func(*args, **kw) print 'end call %s():' % (func.__name__) return rst return wrapper return decorator @log('test') def now(): print 'You are brilliant!' now() @log() def now(): print "You are brilliant!" now() @log('execute') def now(): print 'You are brilliant!' now()
x=float(input("x:")) y=float(input("y:")) print("x+y=",x+y) print("x-y=",x-y) print("x*y=",x*y) print("x/y=",x/y) print("x//y=",x//y) print("x%y=",x%y) print("x**y=",x**y) print("-x=",-x) print("-y=",-y) print("abs(x)=",abs(x)) print("abs(y)=",abs(y)) print("abs(-x)=",abs(-x)) print("abs(-y)=",abs(-y))
#1.check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9) import re def char(string): charRe=re.compile(r'[^a-zA-Z0-9.]') string=charRe.search(string) return not bool(string) print(char("ABCabc123")) print(char("*&%@#!")) #2.matches a word containing 'ab' import re def text_match(text): if re.search('\w*ab.\w*',text): return 'matched' else: return('Not matched') str=input() print(text_match(str)) #3.check for a number at the end of a word/sentence def number_check(string): if re.search(r'\d+s',string): return 'yes' else: return 'no' str1=input() print(number_check(str1)) #4.search the number (0-9) of length between 1 to 3 in a given string import re result=re.finditer(r"([0-9]{1,3})", "Exercises number 1, 12, 13, and 345 are important") print("Number of length 1 to 3:") for n in result: print(n.group(0)) #5.match a string that contains only uppercase letters import re def text_match(text): pattern='^[A-Z]' if re.search(pattern,text): return 'matched' else: return 'Not matched' print(text_match("welcome")) print(text_match("HELLO"))
#1 num=int(input("enter n value:")) a=[] for i in range(1,num): a.append(i) print(a) a.insert(3,6) #add an item to list print(a) a.remove(4) #delete an item in the list print(a) b=max(a) #largest value print(b) c=min(a) #smallest value print(c) #2 my_tuple=(1,2,3,4,5) new_tuple=tuple(reversed(my_tuple)) #reverse of tuple print(new_tuple) #3 my_tuple=(3,4,5) my_list=list(my_tuple) #convert tuple into list print(my_list)
#Exercise 6 in hackbright GIT curriculum # week two, day one #write a program that opens a file and counts how many times each space -separated wod # occurs in that file. # dictionary with word, counter pairs # if word in dictionary -> increment counter # else add word, 1 to dictionary from sys import argv import string script, filename = argv txt = open(filename) our_dict = {} for line in txt: #creates the our_dict from the file txt #takes in string, lowercases it, then strips new lines and punctuation for word in line.lower().strip('\n').replace(".", "").replace(",", "").replace("?","").split(): #sets word that doesn't exist to zero our_dict[word]=our_dict.get(word,0) - 1 # sorts by values, starting with the largest for key, value in sorted(our_dict.iteritems(), key=lambda (k,v): (v,k)): #WORKS, except last sort ->>for key, value in sorted(our_dict.iteritems(), key=lambda (k,v): (v,k), reverse=True): print "%s: %s" % (key, -value)
# 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, # и возвращает сумму наибольших двух аргументов. def my_func(): global arg_1, arg_2, arg_3 #теперь переменные видны не только в функции arg_1 = int(input ('Введите число 1: ')) arg_2 = int(input ('Введите число 2: ')) arg_3 = int(input ('Введите число 3: ')) sum_of_two = [arg_1, arg_2, arg_3] sum_of_two.remove(min(arg_1, arg_2, arg_3)) return sum(sum_of_two) my_result = my_func() #выводим результат на экран print(my_result)
import math def poisson_distribution(mean, expected): result = pow(mean, expected) * pow(math.e, -mean) / math.factorial(expected) return result def main(): mean = float(input()) expected = int(input()) result = poisson_distribution(mean, expected) print("{0:.3f}".format(result)) if __name__ == '__main__': main()
import math import sys def nCr(n, r): f = math.factorial return f(n) // f(r) // f(n - r) def binomial_distribution(boys, girls, n, m): b_prob = boys / (boys + girls) g_prob = girls / (boys + girls) result = nCr(n, m) * pow(b_prob, m) * pow(g_prob, n - m) return result def main(): line = sys.stdin.readline() boys, girls = list(map(float, line.split(' '))) result = binomial_distribution(boys, girls, 6, 3) + \ binomial_distribution(boys, girls, 6, 4) + \ binomial_distribution(boys, girls, 6, 5) + \ binomial_distribution(boys, girls, 6, 6) # check if binomial_distribution is working right # validation should be equal to 1 validation = binomial_distribution(boys, girls, 6, 0) + \ binomial_distribution(boys, girls, 6, 1) + \ binomial_distribution(boys, girls, 6, 2) + \ binomial_distribution(boys, girls, 6, 3) + \ binomial_distribution(boys, girls, 6, 4) + \ binomial_distribution(boys, girls, 6, 5) + \ binomial_distribution(boys, girls, 6, 6) print("{0:.3f}".format(result)) if __name__ == '__main__': main()
from random import randint def numbersgame() : num = randint(1, 10) print(f'\nCheet: {num}') tries = 0 guess = int(input('\nGuess a number between 1 and 10: \nYou have 10 tries to get it right ;) ')) while guess : diff = num - guess if diff > 0 and tries < 9: tries += 1 guess = int(input(f'\nSorry, the correct answer is bigger then {guess}\nNumber of tries: {tries}\n\nGuess again ')) elif diff < 0 and tries < 9: tries += 1 guess = int(input(f'\nSorry, the correct answer is smaller then {guess}\nNumber of tries: {tries}\n\nGuess again ')) elif tries > 8: print('\n***************GAME OVER***************\nOh no, you ran out of tries!') break else: tries += 1 if(tries > 1): print(f'\nGood job, you got it right in just {tries} tries!') else: print(f'\nGood job, you got it right in just {tries} try!') save_highscore = input(f'Wanna save your score? y/n ') if save_highscore.lower() == 'y': user_name = input('Please enter your name: ') return {user_name: tries} else: return False # TODO: # Highscore # Close guessing
# 2명뽑아 짝짓기 모든 경우의 수 # 입력 : 이름이 n개 들어 있는 리스트 # 출력 : 이름 2개씩 짝지을수 있는 경우의 수 def dual_name(a): n = len(a) for i in range(0, n-1): for j in range(i+1,n): print(a[i], "-", a[j]) name=["Tom","Jerry","Mike"] dual_name(name)
class password: def __init__(self, line): self.line = line.split() self.nums = self.line[0].split('-') self.char = self.line[1][0] self.password = self.line[2] def check(self): if (self.password[int(self.nums[0]) - 1] == self.char) \ ^ (self.password[int(self.nums[1]) - 1] == self.char): return True count = 0 lines = open("passwords.txt", mode='r') for line in lines: obj = password(line) if obj.check(): count += 1 print(count) lines.close()
import pyttsx3 import datetime import speech_recognition as sr import wikipedia import webbrowser import os import time system = pyttsx3.init('sapi5') voices = system.getProperty('voices') system.setProperty('voice', voices[1].id) def speak(audio): system.say(audio) system.runAndWait() def greetings(): hour = int(datetime.datetime.now().hour) if hour>=0 and hour<12: speak("Good Morning") elif hour>=12 and hour<18: speak("Good Afternoon") else: speak("Good Evening") speak("I am Dora. what can i do for you dear") def myorder(): r = sr.Recognizer() with sr.Microphone() as source: time.sleep(2) clearscreen() print("Listening command...") speak("Listening command...") r.pause_threshold = 1 audio = r.listen(source) try: clearscreen() print("Recognizing your command, dear...") speak("Recognizing your command, dear...") query = r.recognize_google(audio, language='en-in') print(f"User said: {query}\n") except Exception as e: time.sleep(2) clearscreen() print(e) print("Say that again please...") speak("Say that again please...") return "None" return query def clearscreen(): os.system('cls') if __name__ == "__main__": greetings() while True: query = myorder().lower() if 'wikipedia' in query: speak('Searching Wikipedia...') query = query.replace("wikipedia", "") results = wikipedia.summary(query, sentences=2) speak("Wikipedia says") print(results) speak(results) elif 'exit' in query: speak("pleasure to serve you my friend") exit() elif 'open youtube' in query: webbrowser.open("youtube.com") elif 'open google' in query: webbrowser.open("google.com") elif 'open facebook' in query: webbrowser.open("facebook.com") elif 'current time' in query: strTime = datetime.datetime.now().strftime("%H:%M:%S") speak(f"Dear, the time is {strTime}") elif 'code studio' in query: try: path="C:\\Users\\my world\\AppData\\Local\\Programs\\Microsoft VS Code\\code.exe" os.startfile(path) except Exception as e: speak('no such apps found, dear') elif 'joke' in query or 'tell me a joke' in query: speak('Do u know types of java......') time.sleep(2) speak('hahahahahahaha marjava,lootjava,hai may sadkay java hahahahahaha') elif 'who are you' in query: speak('i am dora, your virtual best friend') elif 'how are you' in query: speak('I am fine, thank you and how are you, dear') elif 'am fine' in query or 'am okey' in query: speak('good to hear that, dear')
''' Print a markdown table of the top tracks by YouTube view count. ''' import json import sys import datetime def sorted_tracks(tracks): ''' Takes a track list and sorts it by number of listens. ''' for i, track in enumerate(tracks): if 'listens' not in track: tracks[i]['listens'] = 0 return sorted(tracks, key=lambda t: t['listens'], reverse = True) def iso8601toDate(st): return datetime.datetime.strptime(st[:st.find('T')], '%Y-%m-%d').date() def markdown_tracklist(top, npdata, rank_column = False): ''' Takes a (sorted and/or truncated) track list and generates a markdown table. @param top the track list @param npdata the noon pacific data, loaded with json.load @param rank_column whether or not to include a numbering column on the left ''' mixtapes = {} for mix in npdata: mixtapes[mix['id']] = mix if rank_column: markdown = ('Rank | Views | Artist | Title | Hipsterness | Playlist\n' + '---- | ----- | ------ | ----- | ----------- | --------\n') else: markdown = ('Views | Artist | Title | Hipsterness | Playlist\n' + '----- | ------ | ----- | ----------- | --------\n') for i, t in enumerate(top): date_diff = (iso8601toDate(t['np_release']) - iso8601toDate(t['video_date'])).days if date_diff < 0: date_string = "{} days before YouTube release".format(-1 * date_diff) else: date_string = "{} days after YouTube release".format(date_diff) table_row = '{}[{:,}](https://youtube.com/watch?v={}) | {} | {} | {} | [{}](http://noonpacific.com/#/weekly/{}/{})'.format( ((str(1 + i) + ' | ') if rank_column else ''), t['listens'], t['video_id'], t['artist'], t['title'], date_string, mixtapes[t['mixtape']]['title'], mixtapes[t['mixtape']]['slug'], t['slug']) markdown += table_row + '\n' return markdown def main(): if len(sys.argv) > 1: num_tracks = int(sys.argv[1]) else: num_tracks = 10 with open('np-200-tracks.json', encoding='utf8') as f: tracks = json.load(f) with open('np-200.json', encoding='utf8') as f: npdata = json.load(f) # list of dicts containing lists of dicts st = sorted_tracks(tracks)[:num_tracks] print(markdown_tracklist(st, npdata)) if __name__ == '__main__': main()
__author__ = 'Sanjay' from collections import Counter import operator def mostTrendingBrand(numOfResponse,listOfBrands): if numOfResponse>1: brandCount = Counter(listOfBrands) onlyCount = [] for ke,va in brandCount.iteritems(): onlyCount.append(va) trendingCount = max(onlyCount) trendingBrandOutput = [] for ke,va in brandCount.iteritems(): if trendingCount == va: trendingBrandOutput.append(ke) for i in trendingBrandOutput: print "Most repeated item is",i if __name__ == "__main__": x = input() userInputList = [] for i in range(0,x): temp = raw_input() userInputList.append(temp) mostTrendingBrand(x,userInputList) # Sample output # 5 # 'a' # 'b' # 'a' # 'a' # 'b' # Most repeated item is 'a'
__author__ = 'Sanjay' # # Task # # Apply your knowledge of the .add() operation to help your friend Rupal. # # Rupal has a huge collection of country stamps. She decided to count the total number of distinct country stamps in her collection. She asked for your help. You pick the stamps one by one from a stack of NN country stamps. # # Find the total number of distinct country stamps. # # Input Format # # The first line contains an integer NN, the total number of country stamps. # The next NN lines contains the countrey's name where the stamp is from. # Constraints # # 0<N<10000<N<1000 # Output Format # # Output the total number of distinct country stamps on a single line. # # Sample Input # # 7 # UK # China # USA # France # New Zealand # UK # France # Sample Output # # 5 userInput1 = int(raw_input()) listOfCountries = [] for i in range(userInput1): #raw_input() listOfCountries.append(raw_input()) finalResult = set(listOfCountries) print len(finalResult)
__author__ = 'Sanjay' # Task # You are given three integers: aa, bb, and mm, respectively. Print two lines. # The first line should print the result of pow(a,b). The second line should print the result of pow(a,b,m). # # Input Format # The first line contains aa, the second line contains bb, and the third line contains mm. # # Constraints # 1?a?101?a?10 # 1?b?101?b?10 # 2?m?10002?m?1000 # # Sample Input # # 3 # 4 # 5 # Sample Output # # 81 # 1 from __future__ import division a = int(raw_input()) b = int(raw_input()) m = int(raw_input()) t = pow(a,b) print t print t % m
__author__ = 'Sanjay' # Let's delve into one of the most basic data types in Python, the list. You are given NN numbers. Store them in a list and find the second largest number. # # Input Format # # The first line contains NN. The second line contains an array AA[] of NN integers each separated by a space. # # Output Format # # Output the value of the second largest number. # # Sample Input # # 5 # 2 3 6 6 5 # Sample Output # # 5 # Constraints # 2?N?102?N?10 # ?100?A[i]?100?100?A[i]?100 # Concept # # A list in Python is similar to an array. A list can contain any data type as well as mixed data types. A list can contain a number, a string and even another list. # Lists are mutable. They can be changed by adding or removing values from the list. input() a=list(map(int,input().split(" "))) b=max(a) while max(a)==b : a.remove(b) print (max(a))
# Given an integer, , traverse its digits (1,2,...,n) and determine how many digits evenly divide (i.e.: count the number of times divided by each digit i has a remainder of ). Print the number of evenly divisible digits. # Note: Each digit is considered to be unique, so each occurrence of the same evenly divisible digit should be counted (i.e.: for , the answer is ). # Input Format # The first line is an integer, , indicating the number of test cases. # The subsequent lines each contain an integer, . # Output Format # For every test case, count and print (on a new line) the number of digits in that are able to evenly divide . # Sample Input # Sample Output # 2 # 12 2 # 1012 3 #Explanation: # The number is broken into two digits, and . When is divided by either of those digits, the calculation's remainder is ; thus, the number of evenly-divisible digits in is . # The number is broken into four digits, , , , and . is evenly divisible by its digits , , and , but it is not divisible by as division by zero is undefined; thus, our count of evenly divisible digits is . if __name__ =='__main__': t = int(input().strip()) opToDisplay = [] for a0 in range(t): n = int(input().strip()) singleIterationResult = [] splitResult = [int(i) for i in str(n)] for i in splitResult: if i != 0: if n % i == 0: singleIterationResult.append(i) opToDisplay.append(len(singleIterationResult)) for i in opToDisplay: print (i)
__author__ = 'Sanjay' # from Queue import Deque def palin(inputString): try: rValue = inputString[::-1] if (inputString == rValue): print ("It's a palindrome") else: print ("it's not a palidrome") except IndexError as e: print (e) else: print ("all is well..") if __name__ == '__main__': palin('madam') # book method def palchecker(aString): # # chardeque = Deque() # for ch in aString: # chardeque.addRear(ch) # # stillEqual = True # # while chardeque.size() > 1 and stillEqual: # first = chardeque.removeFront() # last = chardeque.removeRear() # if first != last: # stillEqual = False return stillEqual
__author__ = 'Sanjay' # How to create a generator in Python? # It is fairly simple to create a generator in Python. It is as easy as defining a normal function with # yield statement instead of a return statement. # # If a function contains at least one yield statement (it may contain other yield or return statements), # it becomes a generator function. Both yield and return will return some value from a function. # # The difference is that, while a return statement terminates a function entirely, yield statement pauses the function # saving all its states and later continues from there on successive calls. # import random import time def lottery(): # returns 6 numbers between 1 and 40 for i in range(6): yield random.randint(1, 40) #bascially yield always returns the value. # returns a 7th number between 1 and 15 time.sleep(10) yield random.randint(100,110) #after completing the above iterations, pointer comes here, yeilds returns the value from random.randint(1,15) print (lottery()) #this really prints the generator object id # if you want to get all Lottery() values, iterate it. for random_number in lottery(): print("And the next number is... %d!" %(random_number))
def checkPalindrome(): userInput = input("Enger a string or integer") try: if type(userInput) is str: if userInput == userInput[::-1]: print ('its a palindrome') else: raise Exception else: print ("is it something else?") except Exception as e: print (e) if __name__ == '__main__': checkPalindrome()
__author__ = 'Sanjay' #calculating a sum of list of numbers. def sumOfList(inp): s = 0 for i in inp: s = s +i print (s) return s #Recurssion methodology now # three LAWS OF RECURSSION # A recursive algorithm must have a base case. # A recursive algorithm must change its state and move toward the base case. # A recursive algorithm must call itself, recursively. def sumRec(inp): if len(inp) == 1: return 1 else: return inp[0] + sumRec(inp[1:]) def listsum(numList): if len(numList) == 1: return numList[0] else: return numList[0] + listsum(numList[1:]) return numList if __name__ == '__main__': sumOfList([1,2,3,6,7,8,9,65,6]) sumRec([1,90,80,700]) # 3 RECURSSIVE CALLS WIL HAPPEN (TOTAL LENGTH - 1) listsum([1,90,80,700])
__author__ = 'Sanjay' def compareTwoStrings(s1,s2): if s1 and s2 is not '': x = list(s1) y = list(s2) x.sort() y.sort() print (x,y) if s1 == s2: print("both strings are equal") else: print("its wrong") else: raise RuntimeError("something went bad") if __name__ == '__main__': compareTwoStrings("abcde","edcba")
__author__ = 'Sanjay' # You are given a string SS. Your task is to capitalize each word of SS. # # Input Format # # A single line of input containing the string, SS. # # Constraints # # 0<len(S)<10000<len(S)<1000 # The string consists of alphanumeric characters and spaces. # # Output Format # # Print the capitalized string, SS. # # Sample Input # # hello world # Sample Output # # Hello World userInput = str(intput()) l = userInput.split(" ") for i in l: print (i.capitalize())
""" 数据库查询操作 2 """ import pymysql # 连接数据库 (连接自己计算机可以不写host port) db = pymysql.connect(host="localhost", port=3306, user='root', password='123456', database='stu', charset='utf8' ) # 创建游标 (游标对象负责调用执行sql语句,操作数据,得到结果) cur = db.cursor() # 查询数据库 name = input("Name:") # 确保sql语句正确 # sql = "select name,age,score from cls where name='%s';"%name # print(sql) # cur.execute(sql) # 执行sql # 利用execute参数列表解决 sql = "select name,age,score from cls where name=%s or score>%s;" cur.execute(sql,[name,80]) # 执行sql,列表不能传递关键字,符号,表名,字段名 # # 获取一条记录 没有结果返回None row = cur.fetchall() print(row) # 关闭游标和数据库 cur.close() db.close()
# Lost Without a Map! (name of problem) # Given an array of integers, return a new array with each value doubled. # For example: # [1, 2, 3] --> [2, 4, 6] # For the beginner, try to use the map method - it comes in very handy quite a lot so is a good one to know. def maps(a): # This was my method for this problem, see below for map() function. newlist = [] for x in a: newlist.append(x*2) # For each index of list a, times by 2 and append to newlist return newlist def maps2(b): # See this method - I tried this but failed syntax so I moved to other method. return [2*x for x in b] # Needed sq brackets around list comprehension to tell comp to print to new list. def maps3(a): return map(lambda x:2*x, a) # Using map() function
''' Sum of Pairs Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum. sum_pairs([11, 3, 7, 5], 10) # ^--^ 3 + 7 = 10 == [3, 7] sum_pairs([4, 3, 2, 3, 4], 6) # ^-----^ 4 + 2 = 6, indices: 0, 2 * # ^-----^ 3 + 3 = 6, indices: 1, 3 # ^-----^ 2 + 4 = 6, indices: 2, 4 # * entire pair is earlier, and therefore is the correct answer == [4, 2] sum_pairs([0, 0, -2, 3], 2) # there are no pairs of values that can be added to produce 2. == None/nil/undefined (Based on the language) sum_pairs([10, 5, 2, 3, 7, 5], 10) # ^-----------^ 5 + 5 = 10, indices: 1, 5 # ^--^ 3 + 7 = 10, indices: 3, 4 * # * entire pair is earlier, and therefore is the correct answer == [3, 7] Negative numbers and duplicate numbers can and will appear. NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out. ''' # O(n^2) Time complexity solution def sum_pairs(ints, s): start_pointer = 0 end_pointer = 1 min_dist = [99999,99999] while start_pointer < len(ints): while end_pointer < len(ints): if ints[start_pointer] + ints[end_pointer] == s and end_pointer < min_dist[1]: min_dist = [start_pointer, end_pointer] elif ints[start_pointer] + ints[end_pointer] == s and end_pointer == min_dist and start_pointer < min_dist[0]: min_dist = [start_pointer, end_pointer] end_pointer += 1 start_pointer += 1 end_pointer = start_pointer + 1 if min_dist == [99999,99999]: return None return [ints[min_dist[0]], ints[min_dist[1]]] # O(n) Time complexity solution - this solution uses the set ds to keep track of visited values, meaning we dont need a nested loop. def sum_pairs(ints, s): seen_nums = set() for int in ints: if s - int in seen_nums: return [s-int, int] else: seen_nums.add(int)
''' You will be given a list of strings, a transcript of an English Shiritori match. Your task is to find out if the game ended early, and return a list that contains every valid string until the mistake. If a list is empty return an empty list. If one of the elements is an empty string, that is invalid and should be handled. Examples: All elements valid: The array {"dog","goose","elephant","tiger","rhino","orc","cat"} should return {"dog","goose","elephant","tiger","rhino","orc","cat"} An invalid element at index 2: The array {"dog","goose","tiger","cat", "elephant","rhino","orc"} should return ("dog","goose") since goose ends in 'e' and tiger starts with 't' ''' def game(words): index_counter = 0 if words.count('') >= 1: return words[:words.index('')] while index_counter < len(words) - 1: if words[index_counter][-1] == words[index_counter + 1][0]: index_counter += 1 else: break return words[:index_counter + 1]
''' Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements, with the same value next to each other and preserving the original order of elements. For example: unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] unique_in_order([1,2,2,3,3]) == [1,2,3] ''' # This was my original solution, which was very similar to a solution with many upvotes for best practises! def unique_in_order(iterable): if len(iterable) == 0: return [] ret = [iterable[0]] for char in iterable: if ret[-1] != char: ret.append(char) return ret
expanded_form(12) # Should return '10 + 2' expanded_form(42) # Should return '40 + 2' expanded_form(70304) # Should return '70000 + 300 + 4' def expanded_form(num): list = [] n = (len(str(num))) # Number of digits within num while n > 0: # This loop will append each digit as a str + (n-1)*'0's UNLESS digit is '0' for i in str(num): n = n - 1 if i != '0': list.append(str(i) + (n*'0')) String = ''.join([x + ' + ' for x in list]) # ''.join() function - joins (index + ' + ') as a string ExpandedForm = String[:-3] # need to remove the final ' + ' aka final 3 characters return ExpandedForm
''' There is an array with some numbers. All numbers are equal except for one. Try to find it! find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 It’s guaranteed that array contains at least 3 numbers. The tests contain some very huge arrays, so think about performance. This is the first kata in series: ''' def find_uniq(arr): non_dupe_values = list(set(arr)) # Cannot index into a set therefore used list after set applied. if arr.count(non_dupe_values[0]) > 1: return non_dupe_values[1] else: return non_dupe_values[0] # See more condensed version: def find_uniq(arr): a, b = set(arr) # Only ever 2 values therefore a, b = set(arr) assigns variable names effectively. return a if arr.count(a) == 1 else b
''' Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example: domain_name("http://github.com/carbonfive/raygun") == "github" domain_name("http://www.zombie-bites.com") == "zombie-bites" domain_name("https://www.cnet.com") == "cnet" ''' # Test cases make this kata quite tricky. Had to use urlparse with a little addition of http:// to urls that start with something else, otherwise it has difficulty parsing. def domain_name(url): from urllib.parse import urlparse if url[:4] != 'http': edit_domain = 'http://' + url # See this if else statment. Adds the http(s):// if it isn't there which aids parsing. # Then its a case of splitting on '.' and finding the root domain. else: edit_domain = url domain = urlparse(edit_domain).netloc domain_breakdown = domain.split('.') for element in domain_breakdown: if element != 'www': return element
# Rewrite this in Unit Test from caesar_cipher import caesar_cipher import unittest class CaesarCipher(unittest.TestCase): def test_for_functionality1(self): self.assertEqual(caesar_cipher("Boy! What a string!", -5), "Wjt! Rcvo v nomdib!") def test_for_functionality2(self): self.assertEqual(caesar_cipher("Hello zach168! Yes here.", 5), "Mjqqt efhm168! Djx mjwj.") def test_for_functionality3(self): self.assertEqual(caesar_cipher("Hello Zach168! Yes here.", -5), "Czggj Uvxc168! Tzn czmz.") if __name__ == '__main__': unittest.main() # print(caesar_cipher("Boy! What a string!", -5) == "Wjt! Rcvo v nomdib!") # print(caesar_cipher("Hello zach168! Yes here.", 5) == "Mjqqt efhm168! Djx mjwj.") # print(caesar_cipher("Hello Zach168! Yes here.", -5) == "Czggj Uvxc168! Tzn czmz.")
def decorator(func): def wrapper(*args, **kwargs): print "args: ", args, " kwargs:", kwargs func(*args, **kwargs) return wrapper @decorator def f(a, b, c, platypus="Why not?", test="1"): print a, b, c, platypus, test # f = decorator(f) f("Bill", "Linus", "Stieve", platypus="Homer!", test="Hello, I'm kwargs")
from Piece import Piece from Board import Board from Player import Player import numpy as np import copy import pickle import random #Game class: #maintains 4 player objects in a structure #when initialized, creates a board, piecelist (common to all players), players, and a turn-marker class Game(): def __init__(self,piece_size,num_players,board_size): self.game_board = Board(board_size) #loads piece shapes from file --- Need to create a new pickle since class was redefined f = open('blokus_pieces_lim_5.pkl', 'rb') all_pieces = pickle.load(f) f.close() self.pieces = [] for piece in all_pieces: # TODO: Piece size other than 5 doesn't work if piece.size <= piece_size: self.pieces.append(piece.get_orientations()) self.player_list = [] for i in range (1,num_players+1): # Note from Mike: I don't think piece_size is a necessary attribute for the Player object new_player = Player(i,piece_size,self.game_board,self.pieces) self.player_list.append(new_player) self.turn = 1 def run(self): # Ends game if no player can make a move turns_since_last_move = 0 while turns_since_last_move <= len(self.player_list): print(self.turn) #self.game_board.display2() print(self.player_list[0].played) print(self.player_list[1].played) print(self.player_list[2].played) print(self.player_list[3].played) print("\n\n") # select player to play current_player = self.player_list[self.turn-1] # ask player for move, then ask player to make move move = current_player.make_move(self.game_board,self.pieces, 'random') # if no move could be made, increment counter by 1 # else reset counter to 0 if move == False: #no move available turns_since_last_move = turns_since_last_move + 1 else: turns_since_last_move = 0 # eventually, log each move # change to next player self.turn = self.turn % len(self.player_list) + 1 return self.score() #scores game based on number of squares occupied on board FIX def score(self): scores= [] for i in range(0,len(self.player_list)): scores.append(sum(sum(self.game_board.board == i+1))) return scores,self.game_board,self.player_list import random random.seed(0) import os os.chdir("C:/Users/Mike/Documents/Coding Projects/Blokus/Dereks/Blokus-Reinforcement-Learning") game = Game(5,4,20) final_score,board,player_list = game.run() board.display2()
# Type checking and casting x = '6' int_x = int(x) print(int_x) print(type(int_x)) # Variable reassignment x = "cat" y = "goat" x = "python" print(x) a = 5 b = 6 a = a + b print(a)
import sqlite3 conn=sqlite3.connect('testing.db') c=conn.cursor() def create_table(): c.execute("CREATE TABLE example (language VARCHAR, level TEXT, Version REAL)") def enter_data(): c.execute("INSERT INTO example VALUES('Python', 'Beginner', 2.7)") c.execute("INSERT INTO example VALUES('Python', 'Intermediate', 3.4)") c.execute("INSERT INTO example VALUES('Python', 'Expert', 2.6)") enter_data() conn.close()
import turtle def draw_square(some_turtle,forward1,forward2): some_turtle.begin_fill() for x in range(2): some_turtle.forward(forward1) some_turtle.right(90) some_turtle.forward(forward2) some_turtle.right(90) some_turtle.end_fill() def change_pos(some_turtle,angle,length): some_turtle.color("white") some_turtle.right(angle) some_turtle.forward(length) some_turtle.color("red") def draw_art(): window = turtle.Screen() window.bgcolor("white") brad = turtle.Turtle() brad.shape("turtle") brad.color("red") brad.speed(2) brad.right(45) draw_square(brad,50,25) change_pos(brad,135,75) brad.left(180) draw_square(brad,100,25) var = 0 while var<360/5: draw_square(brad) brad.right(5) var=var+1 angie = turtle.Turtle() angie.circle(100) angie.shape("arrow") angie.color("blue") window.exitonclick() draw_art()
def get_coordinates(val): """ This function simply returns a tuple containing the coordinates of a certain value Args: val: a number ranging from 0 to 15 Example: the value 13 would correspond to (3,1) """ row_val = val // 4 col_val = val % 4 return row_val, col_val def copy_board(source_list, target_list): """ Copies a list into another list Args: source_list: Our source list target_list: The list we want to insert data into """ for item in source_list: target_list.append(item) def process_input(source_list_one, source_list_two): """ Process the command line arguments to return two lists, one will be the root node object. The other, by the goal_node Args: source_list_one: The board of the root node source_list_two: The board of the goal_node """ strip_list(source_list_one) strip_list(source_list_two) start_node_list = [int(x) for x in source_list_one] goal_list = [int(x) for x in source_list_two] return start_node_list, goal_list def strip_list(target_list): """Removes the '[' and ']' from the list we are trying to process Args: target_list: List we need to process """ target_list[0] = target_list[0][1] # Remove the '[' target_list[-1] = target_list[-1][:-1] # Remove the ']' def get_parent_node(node, closed_list): """ Returns the parent node of the node currently being examined Args: node: Node object whose parent we are trying to find closed_list: The closed list """ parent_candidate = None for candidate_node in closed_list: if node.parent_ID == candidate_node.state_ID: return candidate_node def write_node_to_file(node): """Writes the properties of the node object to the file output.txt Args: node: the node object whose properties we are trying to print out """ with open('output.txt', 'a') as output_file: output_file.write('Node_ID: ' + str(node.state_ID) + '\n') output_file.write("Node board: " + str(node.board) + '\n'), output_file.write('g(n): ',) output_file.write(str(node.g_of_n) + '\n') output_file.write('h(n): ',) output_file.write(str(node.h_of_n) + '\n') output_file.write('f(n): ',) output_file.write(str(node.f_of_n) + '\n') def in_open_list(node, open_list): """ Checks to see if a node is in the open_list (the frontier) Args: node: The Node object we want to check open_list: The open list returns: True or False depending or whether or not the node exists in the open list """ for i in range(open_list.qsize()): if open_list.queue[i][2].board == node.board: return open_list.queue[i][2] return None def find_and_replace(pre_existing_node, child_node, open_list): """ Finds the location of the node in the open_list Args: pre_existing_node: The node already within the open_list child node: The node we want to replace the pre-existing node with open_list: The open list """ for i in range(open_list.qsize()): if open_list.queue[i][2].board == child_node.board: open_list.queue[i] = (child_node.f_of_n, child_node.state_ID, child_node) def in_closed_list(node, closed_list): """ Checks to see if a node is within the closed list Args: node: The Node object we are trying to check closed_list: the closed list returns: True or False depending on whether or not we have found a node """ for ref_node in closed_list: if node.board == ref_node.board: return True return False def calculate_h_of_n(current_state, goal_node): """ Our heuristic function that calculates the h(n) value of a child node. Args: current_state: the state in the search tree we are at goal_node: The goal node returns: The h(n) of the particular state we are in """ overall_count = 0 for num in current_state: source_x, source_y = get_coordinates(current_state.index(num)) # Where is that element currently? target_x, target_y = get_coordinates(goal_node.index(num)) # Where that element is supposed to be difference = abs(target_x - source_x) + abs(target_y - source_y); if difference > 1: overall_count += difference return overall_count
import time def metodoa(): #Aqui definimos el diccionario basicamente es como un hashmap con keys y values pertsona={'izena': 'Oskar','abizena1': 'Casquero','abizena2': 'Oyarzabal'} #De aqui lo que sacamos es el value del key 'izena' print(pertsona['izena']) #Para añadir otro valor al diccionario pertsona['herria']='Amurrio' #Mediante esto recorremos el diccionario entero sacando los keys y los values for key in pertsona.keys(): print(key + '='+pertsona[key]) #Esto sirve para meter varios valores al diccionario beste_datuak={'jaiotze_data': '1979-01-01','NAN': '12345678-A'} pertsona.update(beste_datuak) ikasgaiak = ['Web Sistemak','KonputagailuSareenOinarriak','Datu-baseenDiseinua','Datu-baseenKudeaketa','Datu-egituraketa Algoritmoak'] print("HEMENDIK AURRERA") print(ikasgaiak[0]) #Los arrays tienen una estructura circular print(ikasgaiak[-2]) #Para printear solo los primeros dos print(ikasgaiak[:2]) #Para printear todos menos los primeros dos print(ikasgaiak[2:]) #Te recorre el array for ikasgaia in ikasgaiak: print(ikasgaia) #Pones la i al principio para definirla como en la estructura clasica del for en java #Find lo que hace es te busca ese palabra en la cadena y si existe te devuelve el indice #de la primera aparicion de ese elemento y sino existe te devuelve -1 zerrenda_berria = [i for i in ikasgaiak if i.find('Datu') != -1] print("hemen") print(zerrenda_berria) #Append es el add de java zerrenda_berria.append('Proiektuen Kudeaketa') print(zerrenda_berria) #Te devuelve el indice de un elemento que sabes que esta en la lista print(zerrenda_berria.index('Proiektuen Kudeaketa')) #Es el remove de java zerrenda_berria.remove('Proiektuen Kudeaketa') if 'Proiektuen kudeaketa' in zerrenda_berria: print("dago") else: print("ez dago") pertsona = {'id': 'cvzcaoio', 'desc': {'firstName': 'Oskar', 'lastName': ['Casquero', 'Oyarzabal']}, 'contact': {'email': '[email protected]', 'phone': '946014459'}, 'courses': [{'code': 27699, 'desc': 'Introduction to Computer Networks'}, {'code': 27702, 'desc': 'Web Systems'}]} print(pertsona['id']) print(pertsona['desc']['lastName']) print(pertsona['contact']['email']) print(pertsona['courses'][0]['code']) if __name__ == '__main__': metodoa()
##This script takes the directory containing wav files as input, convert each of the files into text ##and save the corresponding text file in the output directory. ##python SpeechToText.py --input <input_dir_name> --output <output_dir_name> import io import os import shutil import sys import argparse # Imports the Google Cloud client library from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types OUTPUT_DIR = 'output' INPUT_DIR = 'input' parser = argparse.ArgumentParser() parser.add_argument("--input","-i",help="input file directory") parser.add_argument("--output","-o",help="output file directory") args = parser.parse_args() if args.input: INPUT_DIR=args.input if args.output: OUTPUT_DIR=args.output #delete older dir, create new directory to store generated text files shutil.rmtree(OUTPUT_DIR,ignore_errors=True) os.makedirs(OUTPUT_DIR) ##iterate over all the input wav files file_counter=1 # Instantiates a client client = speech.SpeechClient() for wav_file in os.listdir(INPUT_DIR): print("**********************Generating text from audio files in folder :" + INPUT_DIR+" *****************************") if wav_file.endswith('.wav'): with io.open(INPUT_DIR+"/"+wav_file, 'rb') as audio_file: print("********* Now converting audio file : "+wav_file+" ************") # Loads the audio into memory content = audio_file.read() audio = types.RecognitionAudio(content=content) config =types.RecognitionConfig(encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16, sample_rate_hertz=16000, language_code='en-US', enable_automatic_punctuation=True, max_alternatives=1) response = client.recognize(config, audio) output_text = open(OUTPUT_DIR + '/generated_speech'+str(file_counter)+'.txt', 'w') file_counter+=1 for i in range(len(response.results)): for j in range(len(response.results[i].alternatives)): transcript = response.results[i].alternatives[j].transcript print('Transcript: {}'.format(transcript)) output_text.write('Alternative num. ' + str(j + 1) + ': ' + transcript + '\n')
from math import ceil def par_ou_impar(x): if x % 2 == 0: return "par" else: return "ímpar" def positivo_ou_negativo(y): if y > 0: return "positivo" else: return "negativo" def int_ou_dec(z): if ceil(z) == z: return "inteiro" else: return "decimal" print("1. adição") print("2. subtração") print("3. multiplicação") print("4. divisão") print("5. exponenciação") print("") n1 = float(input("1° número: ")) n2 = float(input("2° número: ")) op = int(input("Digite qual operação deseja fazer: ")) if op == 1: resultado = n1 + n2 print("Resultado:", resultado) print("Informações sobre o resultado:") print(resultado, "é", par_ou_impar(resultado)) print(resultado, "é", positivo_ou_negativo(resultado)) print(resultado, "é", int_ou_dec(resultado)) elif op == 2: resultado = n1 - n2 print("Resultado:", resultado) print("Informações sobre o resultado:") print(resultado, "é", par_ou_impar(resultado)) print(resultado, "é", positivo_ou_negativo(resultado)) print(resultado, "é", int_ou_dec(resultado)) elif op == 3: resultado = n1 * n2 print("Resultado:", resultado) print("Informações sobre o resultado:") print(resultado, "é", par_ou_impar(resultado)) print(resultado, "é", positivo_ou_negativo(resultado)) print(resultado, "é", int_ou_dec(resultado)) elif op == 4: resultado = n1 / n2 print("Resultado:", resultado) print("Informações sobre o resultado:") print(resultado, "é", par_ou_impar(resultado)) print(resultado, "é", positivo_ou_negativo(resultado)) print(resultado, "é", int_ou_dec(resultado)) else: resultado = n1 ** n2 print("Resultado:", resultado) print("Informações sobre o resultado:") print(resultado, "é", par_ou_impar(resultado)) print(resultado, "é", positivo_ou_negativo(resultado)) print(resultado, "é", int_ou_dec(resultado))
class Point: def __init__(self): self.x = 0 self.y = 0 p = Point() q = Point() print(p) print(q) print() print(p is q)
# Nesse programa retorna-se o número de notas que cada aluno possui arquivo = open("notas_estudantes.dat", "r") for x in arquivo: lista = x.split(" ") cont = 0 for y in range(len(lista)): try: int(lista[y]) cont += 1 except: cont += 0 if cont > 6: print(lista[0])
numero = int(input("Digite o número principal de sua tabuada: ")) for i in range(11): print(str(numero) + " X " + str(i) + " = ", numero * i)
def aprox_de_raiz(n): aprox = 0.5 * n betteraprox = 0.5 * (aprox + n / aprox) while aprox != betteraprox: aprox = betteraprox betteraprox = 0.5 * (aprox + n / aprox) return betteraprox numero = int(input("Digite um número natural para aproximação de raiz: ")) print("Raiz quadrada de", numero,"=", aprox_de_raiz(numero))
def count_impar(lista): resultado = 0 for i in lista: if i % 2 == 0: resultado += 1 return resultado num_elementos = int(input("Número de elemetos: ")) print() lista = [] for i in range(num_elementos): valor = int(input("Elementos " + str(i + 1) + ": ")) lista.append(valor) print() print("Números ímpares da lista:", count_impar(lista))
dic = {"hotel":"fleabag inn", "sir":"matey", "student":"swabbie", "boy":"matey", "madam":"proud beauty", "professor":"foul blaggart", "restaurnat":"galley", "your":"yer", "excuse":"arr", "students":"swabbies", "are":"be", "lawyer":"foul blaggart", "the":"th`", "restroom":"head", "my":"me", "hello":"avast", "is":"be", "man":"matey"} frase = input("Frase: ") palavras = frase.split() trad = "" for i in palavras: trad += dic[i.lower()] + " " print(trad.capitalize())
f = float(input("Graus fahrenheit: ")) print(f, "°F =", 5*(f - 32)/9, "°C")
periodo = input("Digite o periodo em que você estuda (M, V, N): ") if periodo == "M" or periodo == "m": print("Bom dia!") elif periodo == "V" or periodo == "v": print("Boa tarde!") elif periodo == "N" or periodo == "n": print("Boa noite!") else: print("Valor inválido!")
numero_clientes = int(input("Número de clientes: ")) lista_codigo = [] lista_altura = [] lista_massa = [] maior_altura = 0 menor_altura = 0 maior_massa = 0 menor_massa = 0 MaiorAlturaCode = "" MenorAlturaCode = "" MaiorMassaCode = "" MenorMassaCode = "" index = -1 for i in range(numero_clientes): print(str((i + 1)) + "° cliente:" ) print() codigo = int(input("Código: ")) altura = float(input("Altura (metros): ")) massa = float(input("Massa (quilogramas): ")) lista_codigo = lista_codigo.append(codigo) lista_altura = lista_altura.append(altura) lista_massa = lista_massa.append(massa) maior_altura = max(lista_altura) menor_altura = min(lista_altura) maior_massa = max(lista_massa) menor_massa = min(lista_massa) for y in lista_altura: # os codigos da maior e menor altura são obtidos nesse laço index += 1 if y == maior_altura: if MaiorAlturaCode == "": MaiorAlturaCode += str(lista_codigo[index]) else: MaiorAlturaCode += ", " + str(lista_codigo[index]) if y == menor_altura: if MenorAlturaCode == "": MenorAlturaCode += str(lista_codigo[index]) else: MenorAlturaCode += ", " + str(lista_codigo[index]) index = -1 for z in lista_massa: # os códigos da maior e menor massa são obtidos nesse laço index += 1 if z == maior_massa: if MaiorMassaCode == "": MaiorMassaCode += str(lista_codigo[index]) else: MaiorMassaCode += ", " + str(lista_codigo[index]) if z == menor_massa: if MenorMassaCode == "": MenorMassaCode += str(lista_codigo[index]) else: MenorMassaCode += ", " + str(lista_codigo[index]) print("Cliente(s) com maior altura:") print(" Código(s):", MaiorAlturaCode) print(" Altura:", maior_altura) print() print("Cliente(s) com menor altura:") print(" Código(s):", MenorAlturaCode) print(" Altura:", menor_altura) print() print("Cliente(s) com maior massa:") print(" Código(s):", MaiorMassaCode) print(" Massa:", maior_massa) print() print("Cliente(s) com menor massa:") print(" Código(s):", MenorMassaCode) print(" Massa:", menor_massa)
import turtle pen = turtle.Pen() wn = turtle.Screen() tam = 20 for i in range(5): for v in range(4): pen.forward(tam) pen.left(90) tam += 20 pen.right(90) pen.forward(10) pen.left(90) wn.exitonclick()
n1 = float(input("Digite um número: ")) n2 = float(input("Digite outro número: ")) print("Adição:", n1 + n2) print("Subtração:", n1 - n2) print("Multiplicação:", n1 * n2) print("Divisão:", n1 / n2) print("Divisão inteira:", n1 // n2) print("Módulo:", n1 % n2) print("Exponenciação:", n1 ** n2)
nota1 = float(input("1° nota: ")) nota2 = float(input("2° nota: ")) media = (nota1 + nota2) / 2 print("Nota 1:", nota1) print("Nota 2:", nota2) print("Média:", media) if media > 9 and media <= 10: print("Grau: A") print("APROVADO!") elif media > 7.5 and media <= 9: print("Grau: B") print ("APROVADO!") elif media > 6 and media <= 7.5: print("Grau: C") print("APROVADO!") elif media > 4 and media <= 6: print("Grau: D") print("REPROVADO!") else: print("Grau: E") print("REPROVADO!")
import random import math numero_da_sorte = int(input("Aposte um número que se encaixe no intervalo [0; 10): ")) numero_sorteado = random.random() * 10 print("AGORA CUIDADO! ESCOLHA 1 OU 2! ISSO PODE DETERMINAR SE VC SERÁ UM VENCEDOR OU PERDEDOR!") um_ou_dois = int(input("Digite aqui a sua escolha: ")) if um_ou_dois == 1: numero_sorteado = math.floor(numero_sorteado) elif um_ou_dois == 2: numero_sorteado = math.ceil(numero_sorteado) else: print("O valor que vc digitou não é nem 1 nem 2. Rode o programa novamente e faça de maneira correta o processo.") print("") if numero_sorteado == numero_da_sorte: print("PARABÉNS VC ACERTOU! VOCÊ É UM VENCEDOR!") else: print("VISH! PARECE QUE VC PERDEU! VOCÊ É UM PERDEDOR!") print("Número correto:", numero_sorteado)
import turtle def desenhabarra(t, h): t.left(90) t.forward(h) t.right(90) t.forward(20) t.write(str(h)) t.forward(20) t.right(90) t.forward(h) t.left(90) pen = turtle.Pen() pen.color("red") wn = turtle.Screen() wn.bgcolor("black") for i in [-10, 117, 200, 240, 160, 260, 220]: if i >= 200: pen.fillcolor("red") elif i >= 100 and i < 200: pen.fillcolor("yellow") else: pen.fillcolor("lightgreen") pen.begin_fill() desenhabarra(pen, i) pen.end_fill() wn.exitonclick()
"""Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metrosquadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00.Informe ao usuário a quantidades de latas de tinta a serem compradas e o preço total.""" area = float(input("Área da parede (m²): ")) litros = area // 3 if area % 3 > 0: litros += 1 latas = litros // 18 if litros % 18 > 0: latas += 1 print("Quantidade de latas:", latas) print("Preço:", 80 * latas)
import turtle def desenhaquadradocolorido(t, tam): for i in ["pink", "red", "blue", "yellow"]: t.color(i) t.forward(tam) t.left(90) pen = turtle.Pen() pen.pensize(3) wn = turtle.Screen() wn.bgcolor("black") pen.speed(0) tamanho = 20 for i in range(40): desenhaquadradocolorido(pen, tamanho) tamanho += 10 pen.right(18) wn.exitonclick()
def count(s, c): counter = 0 for i in s: if i == c: counter += 1 return counter string = input("String: ") char = input("char: ") print() print("Ocorrências:", count(string, char))
import random, sys, os options = ['rock','paper','scissors'] print("Let's Play Rock-Paper-Scissors") player1 = input("Player: Enter your name: ") player2 = "Computer" def game(): p1_option = input("%s enter your choice: " %player1).lower() p2_option = ''.join(random.choices(options)) print("%s entered his choice as: %s"%(player2,p2_option)) if p1_option == p2_option: print("It's a tie between %s and %s" %(player1, player2)) replay = input("Would you like to continue (Y/N): ").lower() if replay == 'n': sys.exit() else: pass return game() elif p1_option == 'rock': if p2_option == 'scissors': print("%s, wins!" %player1) else: print("%s, wins!" %player2) elif p1_option == 'scissors': if p2_option == 'paper': print("%s, wins!" %player1) else: print("%s, wins!" %player2) elif p1_option == 'paper': if p2_option == 'rock': print("%s, wins!" %player1) else: print("%s, wins!" %player2) else: print("Invalid Entry by %s, Try Again" %player1) replay = input("Would you like to continue (Y/N): ").lower() if replay == 'n': sys.exit() else: pass return game() game() os.system("PAUSE")
import numpy as np import math def index(human_unit): if human_unit < 2 * 10**int(math.log10(human_unit)) : MF = 0 elif human_unit >= 2 * 10**int(math.log10(human_unit)) and human_unit < 3 * 10**int(math.log10(human_unit)): MF = 1 raw_data = open("kekka_9.csv", 'r') data = np.loadtxt(raw_data, delimiter=",") dd = data[np.where(data[:,MF] == human_unit)] raw_data.close() dd_sort = dd[np.argsort(dd[:, 2])] return dd_sort if __name__ == "__main__": human_unit = int(input()) if human_unit <= 1 * 10**math.log10(human_unit): FM = 1 elif human_unit >= 2 * 10**int(math.log10(human_unit)) and human_unit < 3 * 10**int(math.log10(human_unit)): FM = 0 #print(2 * 10**int(math.log10(human_unit))) dd = index(int(human_unit)) words="" for i in dd: words += str(str(int(i[FM]))+"→"+str(int(i[2]))+"\n") words = words.rstrip() print(words)
#!/usr/bin/python3 import sys file = open("Test.txt","w") file_text = "" file_finish = "1" while file_text != file_finish: file_text = input("Enter text: ") if file_text == file_finish: break file.write(file_text) file.write("\n") file.close() file = open("Test.txt","r") file_text = file.read() file.close print (file_text)
""" Solution for Algorithms #344 (Reverse String) - Space Complexity: O(1) - Time Complexity: O(N) Runtime: 176 ms, faster than 45.30% of Python3 online submissions for Reverse String. Memory Usage: 17.7 MB, less than 36.68% of Python3 online submissions for Reverse String. """ class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ for i in range(len(s) // 2): s[i], s[len(s) - i - 1] = s[len(s) - i - 1], s[i]