text
stringlengths
37
1.41M
class DynamicArray: def __init__(self): self._storage = [None] * 4 self._number_of_items = 0 def __len__(self): return self._number_of_items def __getitem__(self, index): self._is_index_valid(index) return self._storage[index] #??? #def __setitem__(self, key, value): def _is_index_valid(self, index): if not 0 <= index < self._number_of_items: raise IndexError() def insert(self, index, item): self._is_index_valid(index) self._check_capacity() for new_index in range(self._number_of_items, index, -1): self._storage[new_index] = self._storage[new_index-1] self._insert_item(index, item) def _insert_item(self, index, item): self._storage[index] = item self._number_of_items += 1 def _resize(self): new_storage = [None] * ( 2 * len(self._storage) ) for index in range(len(self._storage)): new_storage[index] = self._storage[index] self._storage = new_storage def remove(self, item): for index in range(self._number_of_items): if self._storage[index] == item: for new_index in range(index, self._number_of_items-1): self._storage[new_index] = self._storage[new_index+1] self._number_of_items -= 1 self._storage[self._number_of_items] = None return raise ValueError("value not found") def append(self, item): self._check_capacity() self._insert_item(self._number_of_items, item) def _check_capacity(self): if self._number_of_items >= len(self._storage): self._resize() def selection_sort(some_array): for insert_into_index in range(len(some_array)-1): smallest_index = insert_into_index for comparison_index in range(insert_into_index + 1, (len(some_array))): if some_array[comparison_index] < some_array[smallest_index]: smallest_index = comparison_index temp = some_array[insert_into_index] some_array[insert_into_index] = some_array[smallest_index] some_array[smallest_index] = temp def insertion_sort(some_array): for index in range(1, len(some_array)): current = some_array[index] previous = current while previous > 0 and some_array[previous - 1] > current: some_array[previous] = some_array[previous - 1] previous -= 1 some_array[previous] = current dynamic_array = [] dynamic_array.append(7) dynamic_array.append(28) dynamic_array.append(2) dynamic_array.append(42) insertion_sort(dynamic_array) for item in dynamic_array: print(item)
# 10 # / \ # 8 15 # / \ / \ # 4 9 12 20 class Item: def __init__(self, key, value=None): self._key = key self._value = value def __eq__(self, other): return self._key == other._key def __ne__(self, other): return not (self == other) def __lt__(self, other): return self._key < other._key class BinarySearchTreeMap: class BinaryTreeNode: def __init__(self, data, parent=None, left=None, right=None): self._data = data self._parent = parent self._left = left self._right = right class BinaryTreePosition: def __init__(self, container, node): self._node = node self._container = container def element(self): return self._node._data def __eq__(self, other): return type(other) is type(self) and other._node is self._node def _make_position(self, node): if node is None: return None return self.BinaryTreePosition(self, node) def _validate(self, position): if not isinstance(position, self.BinaryTreePosition): raise TypeError if position._container is not self: raise ValueError if position._node._parent is position._node: raise ValueError return position._node def __init__(self): self._root = None self._size = 0 def __len__(self): return self._size def is_empty(self): return self._size == 0 def _add_root(self, item): self._root = self.BinaryTreeNode(item) def _parent(self, position): node = self._validate(position) return self._make_position(node._parent) def _left(self, position): node = self._validate(position) return self._make_position(node._left) def _right(self, position): node = self._validate(position) return self._make_position(node._right) def _add_right(self, position, item): if self._right(position) is not None: if item < self._right(position).element(): return self._add_left(self._right(position), item) else: return self._add_right(self._right(position), item) else: node = self._validate(position) node._right = self.BinaryTreeNode(item, parent=node) self._size += 1 return self._make_position(node._right) def _add_left(self, position, item): if self._left(position) is not None: if item < self._left(position).element(): return self._add_left(self._left(position), item) else: return self._add_right(self._left(position), item) else: node = self._validate(position) node._left = self.BinaryTreeNode(item, parent=node) self._size += 1 return self._make_position(node._left) def _subtree_search(self, position, key): if key == position.element()._key: return position elif key < position.element()._key: if self._left(position) is not None: return self._subtree_search(self._left(position), key) else: if self._right(position) is not None: return self._subtree_search(self._right(position), key) def __setitem__(self, key, value): if self.is_empty(): self._add_root(Item(key, value)) self._size += 1 return self._make_position(self._root) else: position = self._subtree_search(self._make_position(self._root), key) if position is not None: previous_value = position.element()._value position.element()._value = value return previous_value else: root = self._make_position(self._root) if key < root.element()._key: return self._add_left(root, Item(key, value)) else: return self._add_right(root, Item(key, value)) def __getitem__(self, key): if self.is_empty(): raise KeyError position = self._subtree_search(self._make_position(self._root), key) if position is None: raise KeyError return position.element()._value def first(self): if self.is_empty(): return None return self._subtree_first_position(self._make_position(self._root)) def _subtree_first_position(self, postition): current_position = postition while self._left(current_position): current_position = self._left(current_position) return current_position def _subtree_last_position(self, position): current_position = position while self._right(current_position): current_position = self._right(current_position) return current_position def last(self): if self.is_empty(): return None return self._subtree_last_position(self._make_position(self._root)) def before(self, position): if self._left(position): return self._subtree_last_position(self._left(position)) current_position = position parent = self._parent(position) # find parent that is a right child while parent is not None and current_position == self._left(parent): current_position = parent parent = self._parent(parent) return parent def after(self, position): if self._right(position): return self._subtree_first_position(self._right(position)) current_position = position parent = self._parent(position) # find parent that is a left child while parent is not None and current_position == self._right(parent): current_position = parent parent = self._parent(parent) return parent def __iter__(self): position = self.first() while position is not None: yield position.element()._key position = self.after(position) def delete(self, position): if self._left(position) is not None and self._right(position) is not None: replacement = self._subtree_last_position(self._left(position)) replacement_parent = self._parent(replacement) replacement_left_child = self._left(replacement) if replacement_left_child is not None: replacement_parent._node._right = replacement_left_child._node replacement_left_child._node._parent = replacement_parent._node else: replacement_parent._node._right = None position._node._data = replacement._node._data else: if self._left(position) is not None: child = self._left(position) else: child = self._right(position) parent = self._parent(position) if child is not None: if parent is None: self._root = child._node child._node._parent = None else: child._node._parent = parent._node if self._left(parent) == position: parent._node._left = child._node else: parent._node._right = child._node else: if parent is None: self._root = None elif self._left(parent) == position: parent._node._left = None else: parent._node._right = None self._size -= 1 def __delitem__(self, key): if self.is_empty(): raise KeyError position = self._subtree_search(self._make_position(self._root), key) if position is None: raise KeyError self.delete(position) my_binary_search_tree = BinarySearchTreeMap() my_binary_search_tree[10] = 10 my_binary_search_tree[5] = 5 my_binary_search_tree[3] = 3 my_binary_search_tree[9] = 9 my_binary_search_tree[15] = 15 my_binary_search_tree[12] = 12 my_binary_search_tree[20] = 20 print("Forwards") for key in my_binary_search_tree: print(key) print() print("Backwards") current = my_binary_search_tree.last() while current is not None: print(current.element()._key) current = my_binary_search_tree.before(current) del my_binary_search_tree[10] while not my_binary_search_tree.is_empty(): print("Forwards") for key in my_binary_search_tree: print(key) my_binary_search_tree.delete(my_binary_search_tree.last())
#1. Eric Charnesky says do not cheat! #2. Because the position has the Node behind the scenes ( is a wrapper class around Node), you can add/remove around a node in a linked list in O(1) #3. Class Course: class Course: def __init__(self): self.Name = “” self.Number = “” self.Credits = 0 self.Cost_per_credit = 0 def get_total_cost(self): return self.Credits * self._cost_pre_credit #4 – # AAA #Arrange Expected_credits = 4 Cost_per_credit =500 Expected_cost_for_course = 2000 #act Cis2001 = Course() Cis2001.Credits = expected_credits Cis2001.cost_per_credit = cost_per_credit Actual_cost = cis2001.get_total_cost() #assert Self.assertEqual(expected_cost_for_course, actual_cost) #5. Exhaustive enough to ensure every line of code is run when the tests are run. #Because we don’t trust the code we right to be accurate #6. O(N) – because you have to fill the blank space by shifting everything after the index back #7 def sum_of_even_columns(some_list): sum = 0 for column_index in range(len(some_list[0])): column_sum = 0 for row in some_list: column_sum += row[column_index] if column_sum % 2 == 0: sum += column_sum return sum #8 - encapsulation - interact with public methods, # hide private details # work with the abstract public interface #9 def _recursive_product(some_list, current_index, current_product): if current_index == 0: return some_list[0] * current_product return _recursive_product(some_list, current_index-1, current_product*some_list[current_index]) def recursive_product(some_list): return _recursive_product(some_list, len(some_list)-2, some_list[-1]) def better_recursive_product(some_list): if len(some_list) > 1: return some_list[0] * better_recursive_product(some_list[1:]) return some_list[0] print(recursive_product([1,2,3,4,5])) print(better_recursive_product([1,2,3,4,5])) # 10 - how to design a solution # classes are objects - nouns in the problem definition # class attributes are properties of the noun # class methods are verbs of the noun # 11 non recursive product def iterative_product_of_list(some_list): product = some_list[0] for index in range(1, len(some_list)): product *= some_list[index] return product #12 - three reasons inheritance is useful # don't have to repeat work - rewrite functions # cleaner solutions # override parent class behavior or specialize child class behavior # combine class behaviors in python #13 - shallow copies are bad # two variables pointed to the same list in memory #14 - false- many base cases are allowed #15 - O(1) - constant lookup time by index because we can read the memory address
print ("Vowel Counter") word = 0 vowel_count = 0 while 2 > 0: vowel_count = 0 word = input("Input Word: ") vowel_count = vowel_count+word.count("a") vowel_count = vowel_count+word.count("e") vowel_count = vowel_count+word.count("i") vowel_count = vowel_count+word.count("o") vowel_count = vowel_count+word.count("u") vowel_count = vowel_count+word.count("A") vowel_count = vowel_count+word.count("E") vowel_count = vowel_count+word.count("I") vowel_count = vowel_count+word.count("O") vowel_count = vowel_count+word.count("U") print ("Number Of Vowels: "+str(vowel_count))
# Use the file name mbox-short.txt as the file name fname = input("Enter file name: ") num_line = 0 s =0.0 fh = open(fname) for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue else : ipos = line.find(" ") b= line[ipos+1:] s = s + float(b) num_line = num_line+1 print("Average spam confidence:", s/num_line)
import csv import os.path def cargar_empleado(campos): pregunta = "si" lista_Empleados = [] while pregunta == "si": empleado = {} for campo in campos: ok = True while ok: print(f"Ingrese {campo} del empleado: ") dato = input("") if campo == 'Legajo' or campo == 'Total Vacaciones': # validacion de numero para legajo y vacaciones try: dato = int(dato) ok = False except ValueError: ok = True print(f'El campo {campo} debe ser un numero') else: ok = False empleado[campo] = dato lista_Empleados.append(empleado) pregunta = input("Desea seguir agregando empleados? Si/No ") return lista_Empleados def modificar(archivo, campos): lista_Empleados = cargar_empleado(campos) try: with open(archivo, 'a', newline='') as file: file_guarda = csv.DictWriter(file, fieldnames=campos) file_guarda.writerows(lista_Empleados) print(f"se guardo correctamente {archivo}") return except IOError: print("Ocurrio un error con el archivo") def crear_sobreescribir(archivo, campos): lista_Empleados = cargar_empleado(campos) try: with open(archivo, 'w', newline='') as file: file_guarda = csv.DictWriter(file, fieldnames=campos) file_guarda.writeheader() file_guarda.writerows(lista_Empleados) print(f"se guardo correctamente {archivo}") return except IOError: print("Ocurrio un error con el archivo") def ingresar_archivo(archivo,campos): archivo_existe = os.path.isfile(archivo) if archivo_existe: ok = True while ok: print(f"El archivo ya existe, ¿desea Modificarlo o Sobreescribirlo? M/S: ") accion = input("").upper() if accion == "M": modificar(archivo, campos) ok = False if accion == "S": crear_sobreescribir(archivo, campos) ok = False else: print('ingrese una opcion valida') else: crear_sobreescribir(archivo, campos) return def cargar_archivos(archivo,dias): empeados = open(archivo) dias = open(dias) archivo_empleados = csv.reader(empeados) archivo_dias = csv.reader(dias) next(archivo_empleados) next(archivo_dias) empleados = next(archivo_empleados, None) dias_tomados = next(archivo_dias, None) validar = True while validar: valor = input(f"Ingrese el numero de legajo: ") try: valor = int(valor) validar = False except ValueError: validar = True print(f'El legajo debe ser un numero') contador_dias = 0 while dias_tomados: if int(dias_tomados[0]) == valor: contador_dias += 1 dias_tomados = next(archivo_dias, None) while empleados: if int(empleados[0]) == valor: total_dias_tomados = int(empleados[3]) dias_restantes = total_dias_tomados - contador_dias print(f'Legajo {valor}: {empleados[1]} {empleados[2]}, le restan {dias_restantes} dias de vacaciones') empleados = next(archivo_empleados, None) def menu(): CAMPOS = ['Legajo', 'Apellido', 'Nombre', 'Total Vacaciones'] ARCHIVO_DIAS = "dias.csv" archivo_datos = "" while True: print("Elija una opcion: \n 1.Guardar datos \n 2.Cargar datos \n 3.Salir") op = input("") if op == "1": print("Ingrese nombre del archivo") archivo_datos = input("") ingresar_archivo(archivo_datos,CAMPOS) elif op == "2": cargar_archivos(archivo_datos,ARCHIVO_DIAS) elif op == "3": exit() else: print("Elija una opcion valida") menu()
r = int(input('Informe raio do circulo ' )) a = 3.14 * r * r print(f'A area do circulo é {a}')
b = int(input('informe a base do quadrado ')) h = int(input('informe a altura do quadrado ')) a = b * h d = a**2 print(f'O dobro da area informada é {d}')
import heapq, random, time class ElevatorControlSystem(): def __init__(self, number_of_floors, number_of_elevators): if number_of_elevators <= 0: raise AssertionError("Your building must have at least one elevator.") if number_of_floors <= 0: raise AssertionError("Your building must have at least one floor.") self.elevators = [Elevator(i) for i in range(number_of_elevators)] self.number_of_floors = number_of_floors self.pending_requests = [] def status(self): # returns the status of all elevators in the system (id, floor #, goal floor #) return [(e.id, e.current_floor, e.up_queue, e.down_queue, e.direction) for e in self.elevators] def describe(self): for e in self.elevators: print(e) def update(self, elevator_id, floor_number): # updates the state of an elevator in the system, adding a floor to its queue e = self.elevators[elevator_id] e.add_to_queue(floor_number) def pickup(self, floor_number, direction): # submits a pickup request to the system best_elevator = self.elevators[0] best_distance = self.number_of_floors * 2 for e in self.elevators: distance = abs(e.current_floor - floor_number) # penalize elevator scores based on direction if (e.direction > 0 and floor_number < e.current_floor) or (e.direction > 0 and direction < 0): highest_stop = heapq.nlargest(1, e.up_queue)[0] distance += 2 * highest_stop elif (e.direction < 0 and floor_number > e.current_floor) or (e.direction < 0 and direction > 0): lowest_stop = heapq.nsmallest(1, e.down_queue)[0] distance += 2 * lowest_stop if distance < best_distance: best_elevator = e best_distance = distance best_elevator.add_to_queue(floor_number) def step(self): # moves through one interval in the simulation for e in self.elevators: e.step() class Elevator(): def __init__(self, elevator_id): self.id = elevator_id self.current_floor = 0 self.direction = 0 # 1 for moving up, -1 for moving down, 0 for stationary self.up_queue = [] # heap self.down_queue = [] # heap def step(self): self.current_floor += self.direction self.drop_off() self.update_direction() def drop_off(self): if self.up_queue and self.current_floor == self.up_queue[0]: heapq.heappop(self.up_queue) print("Elevator " + str(self.id) + " stopping on floor " + str(self.current_floor)) elif self.down_queue and self.current_floor == abs(self.down_queue[0]): heapq.heappop(self.down_queue) print("Elevator " + str(self.id) + " stopping on floor " + str(self.current_floor)) def update_direction(self): if self.direction > 0 and not self.up_queue: self.direction = -1 if self.down_queue else 0 if self.direction < 0 and not self.down_queue: self.direction = 1 if self.up_queue else 0 def add_to_queue(self, floor_number, direction=0): if floor_number == self.current_floor: print("Elevator " + str(self.id) + " stopping on floor " + str(floor_number)) elif floor_number > self.current_floor: if floor_number not in self.up_queue: heapq.heappush(self.up_queue, floor_number) if not self.direction: self.direction = 1 else: if floor_number not in self.down_queue: heapq.heappush(self.down_queue, -floor_number) if not self.direction: self.direction = -1 def __str__(self): return "Elevator " + str(self.id) \ + " is on floor " \ + str(self.current_floor) \ + " going in direction " \ + str(self.direction) \ + " with up_queue " \ + str(self.up_queue) \ + " and down_queue " \ + str(self.down_queue) \ + "." if __name__ == '__main__': print("----------------------------------") print("---BEGINNING RANDOM SIMULATIONS---") print("-------PRESS CTRL+C TO STOP-------") print("----------------------------------") time.sleep(2) ecs = ElevatorControlSystem(16,16) while(True): for i in range(16): a = random.randint(0,15) b = random.randint(0,15) ecs.update(i, a) print('Requesting elevator ' + str(i) + ' to stop on floor ' + str(a) + '.') direction = random.choice([-1,1]) ecs.pickup(b, direction) print('Requesting pickup on floor ' + str(b) + ' in direction ' + str(direction) + '.') for i in range(16): ecs.step() print(ecs.status()) time.sleep(1)
import binascii def padding(txt, block_size): padding_to_add = block_size - len(txt)%block_size for i in range(0, padding_to_add): txt+=bytes([padding_to_add]) return txt def main(): txt = b"YELLOW SUBMARINE" txt = padding(txt, 20) print(txt) if __name__ == '__main__': main()
import re pattern = "[a-zA-Z]red" regexp = re.compile(pattern, re.IGNORECASE) file = open("names.txt") print("Open the file " + file.name + " ...\n") print("Match(es) is/are:\n") count = 0 for line in file: match = regexp.search(line) if match: count += 1 print(line, end ="") print("\n\nTotal matched lines = ",count) print("All substrings that match are:") file.seek(0,0) # reposition to the beginning of the file for line in file: x = regexp.findall(line) print(x) file.close()
from datetime import datetime from covid import Covid covid = Covid() for line in covid.list_countries(): line = line['name'] print(line) while True: country = input('Enter Country: ') try: DataJson = covid.get_status_by_country_name(country) country = DataJson["country"] confirmed = DataJson["confirmed"] active = DataJson["active"] deaths = DataJson["deaths"] recovered = DataJson["recovered"] last_update = DataJson["last_update"] print(f'country: {country}') print(f'active: {active}') print(f'deaths: {deaths}') print(f'country: {confirmed}') print(f'recovered: {recovered}') print(f'last_update: {last_update}') except ValueError: print('country Not Found Try Agin . . .') continue
import numpy as np board = [[3,0,0,8,0,1,0,0,2], [2,0,1,0,3,0,6,0,4], [0,0,0,2,0,4,0,0,0], [8,0,9,0,0,0,1,0,6], [0,6,0,0,0,0,0,5,0], [7,0,2,0,0,0,4,0,9], [0,0,0,5,0,9,0,0,0], [9,0,4,0,8,0,7,0,5], [6,0,0,1,0,7,0,0,3]] def possible(row, column, number): global board for i in range(9): if board[row][i] == number: return False for i in range(9): if board[i][column] == number: return False block_c= (column//3)*3 block_r=(row//3)*3 for i in range(3): for j in range(3): if board[block_r+i][block_c+j] == number: return False return True def solution(): global board for row in range(0,9): for column in range(0,9): if board[row][column]==0: for number in range(1,10): if possible(row,column,number): board[row][column]=number solution() board[row][column]=0 return print(np.matrix(board)) solution()
import pygame as pg #class for text that will displyed in game class GameText: def __init__(self, text, size, fontName, position, color): self.text = text self.size = size self.name = fontName self.position = position self.color = color self.bold = False self.italic = False self.font = None self.textChanged = True self.surface = None pg.font.init() self.genFont() #Generate font self.genSurface() #Draw the surface #accessors def getText(self): return self.text def getSize(self): return self.size def getSurface(self): return self.surface def getFont(self): return self.font def getPosition(self): return self.position def textChanged(self): return self.textChanged #mutators def genFont(self): #Generates font self.font = pg.font.SysFont(self.name, self.size, self.bold, self.italic) def genSurface(self): #renders text on to surface and stores the surface #This way, the main loop wont have to render the text every frame self.surface = self.font.render(self.text, False, self.color) def setText(self, text): self.text = text self.genSurface() #Redraw the surface def setBold(self, bold): self.bold = setting self.genFont() #Regenerate font self.genSurface() #Redraw the surface def setItalic(self, italic): self.italic = italic self.genFont() #Regenerate font self.genSurface() #Redraw the surface def setSize(self, size): self.size = size self.genFont() #Regenerate font self.genSurface() #Redraw the surface def setColor(self, color): self.color = color self.genFont() #Regenerate font self.genSurface() #Redraw the surface def setColorRGB(self, r, g, b): self.setColor((r,g,b)) def setSurface(self, s): self.surface = s
"""String algorithms. Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems. Jamie Zawinski """ from typing import Dict def edit_distance(s1: str, s2: str) -> int: """The minimum number of edits required to make s1 equal to s2. This is also known as the Levenshtein distance. An edit is the addition, deletion, or replacement of a character. """ if not s1: return len(s2) if not s2: return len(s1) M = [[0 for _ in range(len(s2) + 1)] for _ in range(len(s1) + 1)] # M[i1][i2] is the edit distance between s1[:i1] and s2[:i2]. for i1 in range(len(s1) + 1): M[i1][0] = i1 for i2 in range(len(s2) + 1): M[0][i2] = i2 for i1 in range(1, len(s1) + 1): for i2 in range(1, len(s2) + 1): cost = 0 if s1[i1 - 1] == s2[i2 - 1] else 1 M[i1][i2] = min( [ 1 + M[i1 - 1][i2], 1 + M[i1][i2 - 1], cost + M[i1 - 1][i2 - 1], ]) return M[len(s1)][len(s2)] def relative_edit_distance(s1: str, s2: str) -> float: """Measures how similar two strings are. Returns: A number between 0 and 1. Returns 0 if the strings are identical, 1 if the strings have nothing in common. """ if not s1 and not s2: return 0.0 return edit_distance(s1, s2) / max(len(s1), len(s2)) def substring_edit_distance(s: str, t: str) -> int: """The minimum number of edits required to make t a substring of s. An edit is the addition, deletion, or replacement of a character. """ if not s: return len(t) if not t: return 0 M = [[0 for _ in range(len(t) + 1)] for _ in range(len(s) + 1)] # M[i][j] is the minimum number of t-edits required to make t[:j] a suffix of s[:i]. for i in range(len(s) + 1): M[i][0] = 0 for j in range(len(t) + 1): M[0][j] = j for i in range(1, len(s) + 1): for j in range(1, len(t) + 1): cost = 0 if s[i - 1] == t[j - 1] else 1 M[i][j] = min( [ 1 + M[i - 1][j], 1 + M[i][j - 1], cost + M[i - 1][j - 1], ]) return min(M[i][len(t)] for i in range(len(s) + 1)) def pattern_edit_distance( s: str, pattern: str, stands_for: Dict[str, str]) -> int: """The minimum number of edits required to make s match the pattern. An edit is the addition, deletion, or replacement of a character. Characters in the pattern are treated as literals, unless they appear in as keys in the the stands_for dictionary, in which case they "stand for" any one of the values in stands_for[char]. If stands_for is empty, then this is the Levenshtein distance between s and the pattern. Args: stands_for: A dictinary from character to collection of characters (a string). When comparing the entity's text to the given pattern, anytime a key in this dictionary appears in the pattern, any of the characters in the corresponding dictionary value will be considered a pattern match. Example: pattern_edit_distance("abc123", "aaazzz", {"z": "23"}) is 3. The "b" and "c" need to be changed to "a", and the "1" needs to be changed to a "2" or a "3". """ if not s: return len(pattern) if not pattern: return len(s) M = [[0 for _ in range(len(pattern) + 1)] for _ in range(len(s) + 1)] # M[i][j] is the pattern edit distance between s[:i] and pattern[:j]. for i in range(len(s) + 1): M[i][0] = i for j in range(len(pattern) + 1): M[0][j] = j for i in range(1, len(s) + 1): for j in range(1, len(pattern) + 1): if pattern[j - 1] in stands_for: cost = 0 if s[i - 1] in stands_for[pattern[j - 1]] else 1 else: cost = 0 if s[i - 1] == pattern[j - 1] else 1 M[i][j] = min( [ 1 + M[i - 1][j], 1 + M[i][j - 1], cost + M[i - 1][j - 1], ]) return M[len(s)][len(pattern)]
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def which_day(date_time): ''' To find out which weekday according to given timestamp input: datetime string with the format of 'yyyy-mm-dd hh:mm:ss' return: nth day of the week ''' assert isinstance(date_time, str) assert len(date_time) > 0 from datetime import datetime import calendar import pandas as pd try: if type(date_time) is str: my_string=date_time.split(' ')[0] my_date = datetime.strptime(my_string, "%Y-%m-%d") return my_date.weekday() else: raise Exception("'date_time' has unexpected data type, it is expected to be a sting") except Exception as e: print(e) #read the .csv file to get the data data = pd.read_csv('./US_Accidents_Dec19.csv') # use the which_day function to find the corresponding weekday nth_day=[] date_time=[dt for dt in data['Start_Time']] for i in range(len(date_time)): nth_day.append(which_day(date_time[i])) # add four new columns 'year', 'month', 'hour', 'weekday' data['year'] = pd.DatetimeIndex(data['Start_Time']).year data['month'] = pd.DatetimeIndex(data['Start_Time']).month data['hour'] = pd.DatetimeIndex(data['Start_Time']).hour data['weekday']=nth_day #split data into weekdays and weekends wday_filt = (data['weekday'].isin([0, 1, 2, 3, 4])) weekend_filt = (data['weekday'].isin([5, 6])) data_workday = (data.loc[wday_filt])[['hour']] data_weekend = (data.loc[weekend_filt])[['hour']] #plot out accidant data with respect to the weekday distribution dt_weekday=data.groupby(['weekday'], as_index=False).count().iloc[:,:2] ax=dt_weekday.plot(kind='bar',rot=0,width=1.0,figsize=(10, 6),fontsize=16,legend=None) xtick_labels=['Mon.', 'Tue.', 'Wed.', 'Thu.', 'Fri', 'Sat.', 'Sun.'] ax.set_xticks(list(dt_weekday.index)) ax.set_xticklabels(xtick_labels) ax.set_xlabel('Weekdays',rotation=0, fontsize=16) ax.set_ylabel('Number of Accidents',rotation=0, fontsize=16) ax.set_title(' Number of accidents by days of week', fontsize=20) ax.xaxis.set_label_coords(1.08,0.00) ax.yaxis.set_label_coords(0.02,1.01) plt.savefig('#Accidents_days_of_week.png',transparent=False) plt.show() #plot out distributon divided into weekdays and weekends fig,axes=plt.subplots(nrows=2,ncols=1,figsize=(6, 12),sharex=True) ax0,ax1=axes.flatten() kwargs = dict(bins=24,density=False,histtype='stepfilled',linewidth=3) ax0.hist(list(data_workday['hour']),**kwargs,label='Only Work days') ax0.set_ylabel('Number of accidents',fontsize=16,rotation=0) ax0.yaxis.set_label_coords(0.09,1.02) ax1.hist(list(data_weekend['hour']),**kwargs,label='Only weekend') ax1.set_ylabel('Number of accidents',fontsize=16,rotation=0) ax1.set_xlabel('Hour',fontsize=16) ax1.yaxis.set_label_coords(0.09,1.02) ax0.legend(); ax1.legend() plt.savefig('hourly_distribution_US.png',transparent=False) plt.show()
#!/usr/bin/env python # coding: utf-8 # In[30]: import csv # In[31]: text = open("username.csv", "r") # In[32]: with open('username.csv','r') as csv_file: csv_reader=csv.reader(csv_file) for line in csv_reader: print(line) # In[33]: #join() method combines all contents of # csvfile.csv and formed as a string text = ''.join([i for i in text]) # In[52]: # search and replace the contents origin_word=input('Enter the origin word :') replaced_word=input('Enter the replaced word :') text = text.replace('{}'.format(origin_word),'{}'.format(replaced_word)) #text = text.replace("grey07", "grey") #text = text.replace("Grey", "White") # In[53]: x = open("output.csv","w") x.writelines(text) x.close() # In[54]: with open('output.csv','r') as csv_file: csv_reader=csv.reader(csv_file) for line in csv_reader: print(line) # In[136]: search_word =input('Enter the word you want to search : ') flag=0 ls=[] with open('username.csv','r') as csv_file: csv_reader1=csv.reader(csv_file) for line in csv_reader1: for word in line: a=word.split(';') #a=str(a) ls=ls+a for item in ls: if item in search_word: print ('Found') break else: print('Not Found') # In[ ]:
num=int(input('enter numerator: ')) den=int(input('enter denominator: ')) quo= (num/den) print (quo)
""" This module exports the 'Hand' class, 'PlayerHand' and 'DealerHand' subclasses, and related methods. """ import time draw_delay = 1 # The pause in seconds between drawn card actions twenty_one = 21 # Ideal score value for both players class Hand: """ A class defining the properties and methods of a hand object. A hand object is a collection of cards associated with either the dealer or a player (each having their own respective subclasses with specialised methods and attributes). Within a round of blackjack, cards are added to a hand when the associated player chooses to 'hit'. The outcome of each round is determined by the relative values of the player's and dealer's hands. """ def __init__(self, holder_name="Player"): """ Initialises an empty hand object for a given participant. Parameters ---------- holder_name : str Defines the owner, or 'holder', of the hand object bseing created: either 'Player' or 'Dealer'. Defaults to 'Player' for this base hand class. """ self._live_hand = ( [] ) # A list of card objects making up the hand; initialised as an empty list self._active = True # The active status communicates whether the hand is still active in the current round self._bust = False # The bust status communicates whether the hand is bust (value > 21) in the current round self._natural = False # The natural status communicates whether the hand is a natural (value = 21 with 2 cards) self._holder_name = holder_name def __iter__(self): """ Allows hand objects to be iterated over, yielding constituent card objects in the order they were added. Yields ------ card : blackjack.card.Card The next card in the hand (within the hand object's '_live_hand' attribute). """ for card in self._live_hand: yield card def __repr__(self): """ Entering the reference for a hand object in the terminal triggers this method, printing all hand details. Returns ------- Output of 'print_hand' method : str Prints the hand's owner followed by shorthand details of all cards currently within the hand. """ return self.print_hand() def __len__(self): """Allows len() to be used on hand objects, returning the number of cards in the hand as the object 'length'.""" return len(self._live_hand) def hand_value(self, bypass_face_down=False): """ Returns the total value(s) of the target hand by summing the values of all constituent card objects. Parameters ---------- bypass_face_down : bool Tells method whether to include face-down cards in calculating the value(s) of the hand. Defaults to False. Returns ------- hand_value_list : list of int / str A list containing all possible values the hand's combination of cards can take with no duplicates. For a hand with all cards face-up: returns a list of integers. For hands with any cards face-down: returns a list of strings. """ ace_count = 0 ace_values = None face_down_count = 0 non_ace_sum = 0 # Loop: counts number of face-down cards in the hand; counts face-up aces; sums face-up cards that aren't an ace for card in self: # Try statement catches AssertionErrors thrown when 'is_ace' method encounters a face-down card try: if card.is_ace(bypass_face_down): ace_count += 1 ace_values = card.card_value(bypass_face_down) else: non_ace_sum += card.card_value(bypass_face_down) except AssertionError: face_down_count += 1 # This if-else block defines a list of possible values associated with all face-up cards in the hand if ace_count > 0: ace_sum_possibilities = self._calculate_ace_values(ace_count, ace_values) ace_sum = [ possibility + non_ace_sum for possibility in ace_sum_possibilities ] hand_value_list = ace_sum else: hand_value_list = [non_ace_sum] # Where the hand contains face-down cards, this block adds the consistent face-down string to the face-up values if face_down_count > 0: hand_value_list = [ str(value) + " + *-*" * face_down_count for value in hand_value_list ] return hand_value_list def best_hand_value(self): """ Returns the best possible value of the hand as an integer. If hand value is bust (> 21), returns None. Returns ------- best_value : int or None The best possible total value of the hand's constituent cards. If no hand value <= 21, 'best_value' = None. """ max_best_value = 21 all_hand_values = self.hand_value(bypass_face_down=True) try: best_value = max([val for val in all_hand_values if val <= max_best_value]) except ValueError: best_value = None return best_value def is_active(self): """ As a boolean, returns the active status of the hand in the current round (bust/stand = False; otherwise = True). A hand is regarded as active in a round while cards can still be added to the hand. Once a player decides to 'stand' at their hand's current value, or if they go bust (> 21), the hands '_active' attribute is set to False signalling that no further actions are required by the player holding the hand in the current round. Returns ------- bool True when hand can still receive cards in the current round; otherwise False. """ return self._active def is_bust(self): """ As a boolean, returns 'bust' status of hand in the current round (value > 21: returns True; otherwise False). Returns ------- bool True when lowest possible hand value exceeds 21; otherwise False. """ return self._bust def is_natural(self): """ As a boolean, returns 'natural' status of hand (2 cards in hand and value = 21: returns True; otherwise False). Returns ------- bool True when card contains two cards with combined value of 21; otherwise False. """ return self._natural def stand(self): """Updates hand status to inactive: triggered when player chooses to draw no more cards in the current round.""" self._active = False def draw_card(self, deck_obj, face_dir="up"): """ Removes one card from the input deck and adds this card to the hand with orientation defined by 'face_dir'. Calls the 'deal_card' method of an input deck object, the deck returns a single card object and deletes this card from the deck. If the 'face_dir' input argument requires the hand to be dealt face-down, the freshly drawn card (face-up by default) calls its 'flip_card' method to ensure the card is correctly face-down before it it is appended to the hand array. Finally, the method calls '_validate_hand_status' that checks whether the hand is now bust and updates all hand statuses accordingly. Parameters ---------- deck_obj : blackjack.deck.Deck The game's 'live' deck object - a card will be removed from this deck and added to the current hand object. face_dir : str Defines whether card is added to the hand face-up or face-down. By default, the card will be added face-up with face_dir = 'up'. Any value of face_dir not spelling 'up' (case-insensitive) will add the card face-down. Raises ------ AssertionError Raised when the hand is inactive (can't accept further cards). """ assert ( self.is_active() ), "Cannot draw a card to this hand: it is marked as inactive in the current round." drawn_card = deck_obj.deal_card() if face_dir.lower() != "up": drawn_card.flip_card() self._live_hand.append(drawn_card) self._verify_hand_status() def print_hand(self, alt_text=None): """ Prints the hand's owner followed by shorthand details of all cards currently within the hand. Parameters ---------- alt_text : str This optional argument will be printed instead of the hand owner's name if provided. Returns ------- empty_string : str An empty string, returned so that the 'print_hand' method can be called by the Hand class' __repr__ method which must return a string-like object. """ empty_string = "" ends_with_s = self._holder_name[-1].lower() == "s" if alt_text is not None: print(alt_text) elif ends_with_s: print(f"\n{self._holder_name}' hand") else: print(f"\n{self._holder_name}'s hand") for idx, single_card in enumerate(self): print(f"Card {idx}: {single_card.short_card_details()}") if ( self.is_active() or self.is_bust() or (self.best_hand_value() == twenty_one and alt_text is not None) ): print(f"Value: {self.hand_value()}") return empty_string def _verify_hand_status(self): """Checks whether the hand is bust, has value equal to 21 or is a natural. Updates hand status accordingly.""" natural_length = 2 if self.best_hand_value() is None: self._bust = True self.stand() elif self.best_hand_value() == twenty_one: self.stand() if len(self) == natural_length: self._natural = True @staticmethod def _calculate_ace_values(ace_count, ace_values): """ Returns the possible values of a collection of ace cards as a sorted list. Parameters ---------- ace_count : int The number of ace cards to calculate possible summed values for. ace_values : tuple A two-element tuple containing the possible card values an ace can take e.g. (1, 11). Returns ------- ace_sum_possibilities : list of int A list containing each value 'ace_count' number of aces can combine to make. TODO: Refactor to allow any number of possible ace values (additional loop over keys of dict?) """ ace_sum_possibilities = [0] for ace_idx in range(ace_count): first_set = [ ace_values[0] + ace_sum_element for ace_sum_element in ace_sum_possibilities ] second_set = [ ace_values[1] + ace_sum_element for ace_sum_element in ace_sum_possibilities ] ace_sum_possibilities = list(set(first_set + second_set)) ace_sum_possibilities.sort() return ace_sum_possibilities class DealerHand(Hand): """ A subclass defining the properties and methods specific to a hand object held by the dealer. The dealer's hand is unique because: the first card dealt to the dealer will always be dealt face-down; the dealer's turn in a single round must be resolved automatically. """ def __init__(self): """Calls the __init__ method of the base Hand class, initialising an empty hand object for the dealer.""" super().__init__("Dealer") def draw_card(self, deck_obj, face_dir=None): """ Removes one card from the input deck and adds this card to the hand with orientation defined by 'face_dir'. Parameters ---------- deck_obj : blackjack.deck.Deck The game's 'live' deck object - a card will be removed from this deck and added to the dealer's hand object. face_dir : None / str Defines whether card is added to the hand face-up or face-down. By default, 'face_dir' is None when method is called against a dealer's hand object. Where None, the orientation of the card is determined by the number of cards currently in the dealer's hand. If the dealer currently has a single card in their hand, the card is dealt face-down; otherwise face-up. If the method is called with face_dir specified, it behaves identically to the equivalent method on the base Hand class. """ if face_dir: super().draw_card(deck_obj, face_dir) elif len(self) == 1: face_dir = "down" super().draw_card(deck_obj, face_dir) else: face_dir = "up" super().draw_card(deck_obj, face_dir) def resolve_hand(self, deck_obj, player_hand, player_score_message): """ This method automatically resolves the dealer's hand: drawing cards until the hand value exceeds seventeen. Method initially checks the dealer's hand value: if its best value > 17, the dealer stands. If < 17, the hand draws cards until its value exceeds 17 or goes bust. The dealer's final hand score is printed to the screen or the player is informed that the dealer has gone bust. Parameters ---------- deck_obj : blackjack.deck.Deck The game's 'live' deck object - cards may be removed from this deck and added to the dealer's hand object. player_hand : blackjack.hand.PlayerHand A player's 'live' hand object. Allows the player's hand to be printed for comparison as the dealer's hand is resolved. player_score_message : str A string that communicates the players score. As the dealer's hand is resolved, the players score is printed each time the dealer's hand is printed so the user can easily compare the relative scores. """ dealer_target = 17 print(player_score_message) if player_hand.best_hand_value() == twenty_one: print("You've got 21!") time.sleep(draw_delay) self._reveal_hand() while self.is_active(): if self.best_hand_value() < dealer_target: self.draw_card(deck_obj) self.print_hand(alt_text="\nDealer hits:") player_hand.print_hand() print(player_score_message) print("\n---") time.sleep(draw_delay) else: self.stand() self.print_hand(alt_text="\nDealer stands:") print(f"Dealer's score = {self.best_hand_value()}") player_hand.print_hand() print(player_score_message) break if self.is_bust(): self.print_hand(alt_text="\nDealer has gone bust!") player_hand.print_hand() print(player_score_message) print("\n---") def _reveal_hand(self): """Turns all cards in the hand face-up and prints hand details to the screen.""" print("\n---------------") for card in self: if not card.is_face_up(): card.flip_card() self.print_hand(alt_text="Dealer reveals hand:") print("---------------") time.sleep(draw_delay) def settle_naturals(self, player_hand, player_obj): """ Method detects naturals and settles any bets as necessary; returns True if round is concluded, otherwise False. A hand is a 'natural' if it contains two cards with a total value of 21. Players and dealers can get naturals upon drawing their first two cards at the start of a round. If the dealer gets a natural, the round is over and they collect the bet of any player who did not also get a natural. If a player gets a natural and the dealer did not, they are immediately paid 1.5x the value of their bet. Parameters ---------- player_hand : blackjack.hand.PlayerHand A player's 'live' hand object. The 'natural' status of this hand is read and compared to the status of the dealer's hand. Where a payout is required, the amount bet against the hand is also read into 'bet_amount'. player_obj : blackjack.player.Player The player object that owns the input 'player_hand'. Where a payout is required, this player's balance will be updated accordingly. Returns ------- round_complete : bool Returns True if no further actions are possible in the current round, following the settling of naturals; otherwise False (and the round continues). """ if not any((self.is_natural(), player_hand.is_natural())): round_complete = False return round_complete else: round_complete = True bet_amount = player_hand.get_bet() if self.is_natural() and not player_hand.is_natural(): # No action, round ends and bet is collected (discarded) automatically with player's hand self._reveal_hand() print("Dealer has a natural!") elif not self.is_natural() and player_hand.is_natural(): # Player wins 1.5x their original bet; multiplier is 2.5x so bet amount is also deposited back into balance print(f"\n{player_obj.get_name()} has a natural (dealer does not)!") payout_multiplier = 2.5 player_obj.update_balance(bet_amount * payout_multiplier) elif all((self.is_natural(), player_hand.is_natural())): # Stand-off between player and dealer: player's bet is deposited back into balance print(f"\n{player_obj.get_name()} has a natural!") self._reveal_hand() print("\nSo does the dealer! It's a stand-off!") payout_multiplier = 1 player_obj.update_balance(bet_amount * payout_multiplier) return round_complete def settle_bet(self, player_hand, player_obj): """ Method settles any bets at the end of the round; where the player loses, the method exits and their bet is lost. The value of the dealer's and player's hands are compared. If the player wins, their player object is payed the value of their bet plus the original bet amount is returned. If it's a draw, the bet is returned to the player's balance but they receive no winnings. If the player loses, the method exits and their balance is uneffected. The bet placed against their hand is lost when a new round starts and new hands are initialised. Parameters ---------- player_hand : blackjack.hand.PlayerHand A player's 'live' hand object. The value of this hand is read and compared to the value of the dealer's hand. Where a payout is required, the amount bet against the hand is also read into 'bet_amount'. player_obj : blackjack.player.Player The player object that owns the input 'player_hand'. Where a payout is required, this player's balance will be updated accordingly. """ assert not any( (self.is_active(), player_hand.is_active()) ), "Bets cannot be settled between the dealer and a player unless both participants have 'stood' or gone bust." if player_hand.is_bust(): return if self.is_bust(): dealer_score = 0 else: dealer_score = self.best_hand_value() if dealer_score > player_hand.best_hand_value(): return else: bet_amount = player_hand.get_bet() if player_hand.best_hand_value() > dealer_score: payout_multiplier = 2 player_obj.update_balance(bet_amount * payout_multiplier) elif player_hand.best_hand_value() == dealer_score: payout_multiplier = 1 player_obj.update_balance(bet_amount * payout_multiplier) class PlayerHand(Hand): """ A subclass defining the properties and methods specific to a hand object held by a player. Players' hands are special because bets can be made against these hands. """ def __init__(self, player_obj): """ Calls the __init__ method of the base Hand class, initialising an empty hand object for the player. Parameters ---------- player_obj : blackjack.player.Player The player object that owns the hand being initialised. The name of this player is queried and set used to define the '_holder_name' attribute on the base class. This name is then displayed when printing hand details to screen. """ self._bet = float( 0 ) # An attribute holding the amount bet by a player against this hand: initially zero player_name = player_obj.get_name() super().__init__(player_name) def add_bet(self, amount): """ Adds a bet made by a player to the current hand object: at the end of a round, the dealer resolves this bet. Parameters ---------- amount : float The amount bet against the hand object. In typical game flow, this bet amount has already been verified as positive and has already been removed from the player's balance. """ self._bet += amount def get_bet(self): """Returns the amount bet against this player's hand as a float.""" return self._bet
# authors: # filename: # date: # # description: <insert description here> ### imports ### # insert imports here # ensure there are no overlaps import random ############### ##### GLOBALS ##### # insert global variables here, explain what they are with comments # and include what type they are, and/or expected to be. include who made them prompt = open("prompt.txt","w") promptOpen = open("prompt.txt","r+") uInput = input("") ################### #################### FUNCTIONS #################### # !author: ALL # name: main() # parameters # none # list each parameter by name, and explain what it is expected to hold # return values # none # list what value(s) a function returns, and why # # desc: <insert description of the function here. describe the function before # creating.> # # A note about main(). main() is typically a common function that is always called # at the beginning of a program and is considered the function where the # algorithm is created at the high-level (main points/beats) def main(): pass ################################################### # Program Start if __name__ == '__main__': # a global variable, __name__, is set to the string '__main__' at the start of the program. main()
print("MathGEN 1.0") print("Разработчики: StupidKuklovod, kukold-code, Evgenia003. Дрим тим так сказать.\n") print("В следующем окне введите число от 1 до 3 - тип уравнения.") import math a = int(input("Введите номер, соответствующий виду уравнения, которое вы хотите решить: ")) if a == 1: x = int(input('введите число x ')) y = (math.pow(x, 3)-64*x*(math.pow(x, 3)/math.pow(x, 2))) print(y) elif a == 2: x1 = int(input("Please, введите x1: ")) x2 = int(input("Please, введите x2: ")) x3 = int(input("Please, введите x3: ")) y = (math.pow(x1, 2)+math.pow(x2, 2)+math.pow(x3, 2)) - 100 print(y) elif a == 3: y = math.sqrt((math.pow(x1,x2)) * (math.pow(x2,x1))) print(y)
def show_instructions(): # print a main menu and commands print('Pirate Text Adventure Game') print('Collect 6 items to win the game, or fail your mission.') print('Move commands: go South, go North, go East, go West') print("Add to Inventory: get 'item name'") def show_status(): print("You are currently in {}".format(current_island)) current_dict = islands[current_island] item = 'None' if 'item' in current_dict: item = current_dict['item'] print('Item in this room:', item) print("Inventory:", inventory) # define inventory which begins empty islands = { 'Isla Blanquilla': {'South': 'Cumana', 'East': 'Grenada', 'West': 'Curacao', 'North': 'St. Kitts'}, 'Curacao': {'East': 'Isla Blanquilla', 'item': 'Cutlass'}, 'Grenada': {'West': 'Isla Blanquilla', 'North': 'Barbados', 'item': 'Cannons'}, 'Barbados': {'South': 'Grenada', 'item': 'Treasure Ship'}, 'St. Kitts': {'South': 'Isla Blanquilla', 'East': 'Antigua', 'item': 'Crew'}, 'Antigua': {'West': 'St. Kitts', 'item': 'Frigate'}, 'Cumana': {'North': 'Isla Blanquilla', 'East': 'Trinidad', 'item': 'Gold Doubloons'}, 'Trinidad': {'West': 'Cumana', 'item': 'Rum'} } inventory = [] starting_island = 'Isla Blanquilla' current_island = starting_island show_instructions() while True: show_status() if current_island == 'Barbados': # check number of items print('You reach the final room') if len(inventory) == 6: print('You win!') else: print('You lose!') break # end game # prompt user to input compass heading word_list = input("Enter 'Go North, South, East, West' to sail or 'Exit' to exit game: ").split() word_list = [x.capitalize() for x in word_list] if len(word_list) == 1: if word_list[0] == "Exit": current_island = 'exit' break else: print('Invalid input') continue elif len(word_list) >= 2: action = word_list[0] if action == "Go": # ensure we have only two words if len(word_list) > 2: print('Invalid input.') continue direction = word_list[1] possible_islands = islands[current_island] if direction in possible_islands: current_island = possible_islands[direction] else: print(f'Could not go to {direction} from {current_island}.') elif action == "Get": if 'item' in islands[current_island]: # item name combines all the words after the first word item_name = '' i = 1 for val in word_list[1:]: if i != 1: item_name += f' {val}' else: item_name += val i += 1 if islands[current_island]["item"] == item_name: inventory.append(item_name) islands[current_island].pop("item") # check for end game if len(inventory) == 6: print('You collected all the items. You won') break else: print("This item is not in this room") else: print("There is no item here") else: print('Invalid action.') else: print('Invalid input')
#for loops items=[] prices=[] item_name="none" price=0 for i in range(3): item_name=input("Enter item name:") price=input("Enter price:") items.append(item_name) prices.append(int(price)) total_price=0 for i in range(3): print("Item is "+items[i]) print("Item price is "+ str(prices[i])) total_price = total_price + prices[i] print("Your total bill is: "+str(total_price)) '''choice='y' ''' #choice='y' #for i in range(10): # print(i)
DIGITS = "0123456789ABCDEF" def hexify(i: int) -> str: #return "00" # FIXME string = "" if i == 0: return "0" while i > 0: x_low = i & 15 string = DIGITS[x_low] + string # x_high = (i >> 4) & 15 i = i >> 4 return string print(hexify(0x0)) # Expected Out: 0 print(hexify(0xf3e45a)) # Expected Out: F3E45A
""" Driver (main program) for symbolic calculator. """ from rpn_parse import parse, InputError from lexer import LexicalError import expr help = """Type 'quit' to quit. Assignment: 'var expression =' Form expressions with +, -, *, /, ~ (negation) Use a space between each element, e.g., for y_not gets z + 3: yes: y_not z 3 + = no: y_not z3+= Identifiers can be any_valid_P7thon_identifier """ def main(): """Evaluate expressions typed at the command line""" while True: try: inp = input("expression/'help'/'quit': ") if inp == "quit": break elif inp == "dump": expr.env.dump() elif inp in ["help", "?", "Help"]: print(help) else: exp = parse(inp) print("{} -> ".format(exp), end="") print(exp.eval()) except InputError as e: print(e) print(help) except LexicalError as e: print(e) print(help) except NotImplementedError as e: print(e) if __name__ == "__main__": main()
""" In class: Postfix, S-expressions""" ops = {"+": lambda x, y: x + y, # lambda is a compact way of defining a function "*": lambda x, y: x * y, "-": lambda x, y: x - y, "/": lambda x, y: x // y} def eval_postfix(s: str) -> int: """ if "5 3 + 4 *": eval_postfix("5 3 + 4 *") -> 32 if eval_postfix("5 3 + 4 - 12 *") -> 48 """ stack = [] tokens = s.split() for i in tokens: if i.isnumeric(): # if its a number stack.append(int(i)) # adds numbers to the stack elif i in ops: # or if its in the operator dict right = stack.pop() left = stack.pop() result = ops[i](left, right) # call the correct function in ops, pass it the top 2 of the stack stack.append(result) # push the new sum/product/difference/quotient to the stack return(stack[0]) """ elif i == "+": left = stack.pop() # pops the last item off the stack right = stack.pop() x = right + left stack.append(x) # add the sum back to the stack elif i == "-": left = stack.pop() right = stack.pop() x = right - left stack.append(x) """ print(eval_postfix("5 3 + 4 - 12 *")) # 5 is an s-expression # ["+" 5 4] is an s-expression # ["+" ["-" 5 4] ["+" 3 7]] def parse_postfix(s: str) -> list: """ parses the input and builds the s-expression (a tree) """ stack = [] tokens = s.split() for i in tokens: if i.isnumeric(): # if its a number stack.append(int(i)) # adds numbers to the stack elif i in ops: # or if its in the operator dict right = stack.pop() left = stack.pop() result = [i, left, right] stack.append(result) # push the new sum/product/difference/quotient to the stack return(stack[0]) def eval_sexp(sexp: list) -> int: if isinstance(sexp, int): return sexp else: right = eval_sexp(sexp.pop()) left = eval_sexp(sexp.pop()) op = sexp.pop() return ops[op](left, right) print(parse_postfix("5 3 - 4 *")) print(eval_sexp(parse_postfix("5 3 - 4 *")))
""" alphacode.py: Convert PIN code to mnemonic alphabetic code Authors: Noah Tigner CIS 210 assignment 1, Fall 2016. """ import argparse # Used in main program to get PIN code from command line from test_harness import testEQ # Used in CIS 210 for test cases ## Constants used by this program CONSONANTS = "bcdfghjklmnpqrstvwyz" VOWELS = "aeiou" def alphacode(pin): """ Convert numeric pin code to an easily pronounced mnemonic. args: pin: code as positive integer returns: mnemonic as string """ mnemonic = "" while pin >= 1: pair = pin % 100 first_digit = pair % 5 first_digit = VOWELS[first_digit] mnemonic = (first_digit) + mnemonic second_digit = pair // 5 second_digit = CONSONANTS[second_digit] mnemonic = (second_digit) + mnemonic pin = pin // 100 # print(mnemonic) return mnemonic def run_tests(): """ This function runs a set of tests to help you debug your program as you develop it. """ print("**** TESTING --- examples from course assignment page") testEQ("4327 => lohi", alphacode(4327), "lohi") testEQ("1298 => dizo", alphacode(1298), "dizo") print("***** Longer PIN codes ****") testEQ("1234567 => begomari?", alphacode(1234567), "begomari") testEQ("42424242 => lililili ?", alphacode(42424242), "lililili") testEQ("98765 => cuwira?", alphacode(98765), "cuwira") testEQ("987654 => zotenu?", alphacode(987654), "zotenu") testEQ("(same digit pairs, reverse order) 547698 => nutezo ?", alphacode(547698), "nutezo") print("**** Edge cases (robustness testing) ****") testEQ("0 => empty mnemonic ?", alphacode(0), "") testEQ("-42 and all negative numbers => empty mnemonic? ", alphacode(-42), "") print("*** End of provided test cases. Add some of your own? ****") def main(): """ Interaction if run from the command line. Magic for now; we'll look at what's going on here in the next week or two. """ parser = argparse.ArgumentParser(description="Create mnemonic for PIN code") parser.add_argument("PIN", type=int, help="personal identifier number (an integer)") args = parser.parse_args() # gets arguments from command line pin = args.PIN mnemonic = alphacode(pin) print("Encoding of", pin, "is", mnemonic) if __name__ == "__main__": ## run_tests() main()
""" Reading and writing Sudoku boards. We use the minimal subset of the SadMan Sudoku ".sdk" format, see http://www.sadmansoftware.com/sudoku/faq19.php Author: M Young, January 2018 """ import sdk_board import typing from typing import List, Union import sys from io import IOBase class InputError(Exception): pass def read(f: Union[IOBase, str], board: sdk_board.Board=None) -> sdk_board.Board: """Read a Sudoku board from a file. Pass in a path or an already opened file. Optionally pass in a board to be filled. """ if isinstance(f, str): f = open(f, "r") if board is None: board = sdk_board.Board() values = [] for row in f: row = row.strip() values.append(row) if len(row) != 9: raise InputError("Puzzle row wrong length: {}" .format(row)) if len(values) != 9: raise InputError("Wrong number of rows in {}" .format(values)) board.set_tiles(values) return board def write(board: sdk_board.Board, f: IOBase=sys.stdout): """Print the board"""
""" Solve a jumble (anagram) by checking against each word in a dictionary Authors: Noah Tigner Usage: python3 jumbler.py jumbleword wordlist.txt """ import argparse def jumbler(jumble, dict_file_name): """ compare a jumbled anagram to a dictionary to find matches. inputs: jumble: the given jumbled anagram dict_file_name: the file containing the dictionary of words output: prints the match(es) for the jumble as well as the amount of words in the dictionary """ matches = 0 # initializing a variable to count the matches count = 0 # initializing a variable to count the number of words in the file for word in dict_file_name: # read each word in the file word = word.strip() count += 1 if sorted(word) == sorted(jumble): # compare each word to 'jumble' matches += 1 # increment matches print(word) if matches == 1: # print the matches fmt = "1 match in {} words" print(fmt.format(count)) elif matches > 1: fmt = "{} matches in {} words" print(fmt.format(matches, count)) else: print("No matches") def main(): """ collect command arguments and invoke jumbler() inputs: none, fetches arguments using argparse effects: calls jumbler() """ parser = argparse.ArgumentParser(description="Solve a jumble (anagram)") parser.add_argument("jumble", type=str, help="Jumbled word (anagram)") parser.add_argument('wordlist', type=str, help="A text file containing dictionary words, one word per line.") args = parser.parse_args() # gets arguments from command line jumble = args.jumble wordlist = args.wordlist dict_file_name = open(wordlist, "r") # open the file jumbler(jumble, dict_file_name) # call jumbler dict_file_name.close # close the file if __name__ == "__main__": main()
""" drawflower.py: Draw flower from multiple squares using Turtle graphics Authors: Noah Tigner Credits: draw_square funtion based off on Miller & Ranum, "Python Programming In Context", pp34. CIS 210 assignment 1, Fall 2016. """ import argparse # Used in main program to get num_squares and side_length # from command line import time # Used in main program to pause program before exit import turtle # using turtle graphics ## Constants used by this program #draw_square function from drawSquare function on page 34 of Miller and Ranum def draw_square(my_turtle, side_length): for i in range(4): my_turtle.forward(side_length) my_turtle.right(90) def draw_flower(my_turtle, num_squares, side_length): """ Draw flower shape using squares args: my_turtle: Turtle object to draw with num_squares: number of squares to use for flower side_length: length of a side for each square returns: nothing, draws flower in the Turtle graphics window """ turnAngle = 360 / num_squares for i in range(num_squares): draw_square(my_turtle, side_length) my_turtle.right(turnAngle) #draw_flower(my_turtle, num_squares, side_length) def main(): """ Interaction if run from the command line. Magic for now; we'll look at what's going on here in the next week or two. """ parser = argparse.ArgumentParser(description="Draw flower using squares") parser.add_argument("num_squares", type=int, help="number of squares to use (an integer)") parser.add_argument("side_length", type=int, help="length of side for each square (an integer)") args = parser.parse_args() # gets arguments from command line num_squares = args.num_squares side_length = args.side_length my_turtle = turtle.Turtle() my_turtle.speed(20) #increase the speed of the turtle to 20 draw_flower(my_turtle, num_squares, side_length) time.sleep(10) # delay for 10 seconds if __name__ == "__main__": main()
#Rock, Paper, Scissors!!! #Random answer from the computer (Rock, paper, or scissors) #Best 2/3? import random numoflives = 3 numofpoints = 0 weapons = ["Rock", "Paper", "Scissors"] print("I challenge you, to the death!") print("\n") print("Choose your weapon, type 'weapons' to see what you can use") while numoflives <= 3: choice = input(str()) if choice == ("weapons"): print(weapons) print("\n") continue if choice == random.choice(weapons): numofpoints = numofpoints + 1 print("Ah! That's a point for you!") elif choice != random.choice(weapons): numoflives = numoflives - 1 print("Ba hah! That's a point for me!") if numoflives == 0: break if numofpoints == 3: break if numofpoints == 3: print("Bah! You have bested me!") elif numoflives == 0: print("You lose! I am the better man!") input("Press enter to exit")
# Author Vladimir SR def lists_methods(): male_names = ["Alvaro", "Jacinto", "Miguel", "Edgardo", "David"] male_names.append("Jose") print(male_names) male_names.extend(["Jose", "Gerardo"]) print(male_names) male_names.insert(0, "Ricky") print(male_names) male_names.pop() print(male_names) male_names.pop(3) print(male_names) male_names.remove("Jose") print(male_names) male_names.reverse() print(male_names) male_names.sort() print(male_names) male_names.sort(reverse=True) print(male_names) male_names = ["Alvaro", "Miguel", "Edgardo", "David", "Miguel"] male_names.count("Miguel") male_names = ("Alvaro", "Miguel", "Edgardo", "David", "Miguel") male_names.count("Miguel") male_names.index("Miguel") male_names.index("Miguel", 2, 5) tupla = (1, 2, 3, 4) tupla list(tupla) lista = [1, 2, 3, 4] lista tuple(lista) list1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6, 7, 8] list3 = list1 + list2 list3 tuple1 = (1, 2, 3, 4, 5) tuple2 = (4, 6, 8, 10) tuple3 = (3, 5, 7, 9) tuple4 = tuple1 + tuple2 + tuple3 tuple4 max(tuple4) max(tuple1) min(tuple1) max(list3) min(list1) len(list3) len(list1) len(tuple2)
# Author Vladimir SR import random """ Ejercicio 1 Escriba una función que tome una lista de números y devuelva la suma acumulada, es decir, una nueva lista donde el primer elemento es el mismo, el segundo elemento es la suma del primero con el segundo, el tercer elemento es la suma del resultado anterior con el siguiente elemento y así sucesivamente. Por ejemplo, la suma acumulada de [1,2,3] es [1, 3, 6]. """ def con1(): max = random.randint(2, 7) lista = [] for cont in range(1, max): lista.append(random.randint(2, 9)) resultado = [] for cont in range(0, max -1): if cont == 0: resultado.append(lista[cont]) else: resultado.append(lista[cont] + lista[cont - 1]) return lista, resultado """ Ejercicio 2 Escribe una función llamada "elimina" que tome una lista y elimine el primer y último elemento de la lista y cree una nueva lista con los elementos que no fueron eliminados. Luego escribe una función que se llame "media" que tome una lista y devuelva una nueva lista que contenga todos los elementos de la lista anterior menos el primero y el último. """ """ Ejercicio 3 Escribe una función "ordenada" que tome una lista como parámetro y devuelva True si la lista está ordenada en orden ascendente y devuelva False en caso contrario. Por ejemplo, ordenada([1, 2, 3]) retorna True y ordenada([b, a]) retorna False. """
def knapsack_without_repeats(capacity, weight_list): cost = 1 previous = [0] * (capacity + 1) for i in range(1, len(weight_list) + 1): current = [0] for w in range(1, capacity + 1): current.append(previous[w]) if weight_list[i - 1] <= w: current[w] = max(current[w], previous[w - weight_list[i - 1]] + cost * weight_list[i - 1]) previous = current return previous[capacity] // cost def main(): capacity, n_ = (int(i) for i in input().split()) weight_list = [int(i) for i in input().split()] print(knapsack_without_repeats(capacity, weight_list)) if __name__ == '__main__': main()
#ask for primes p = int(input("How many primes? ")) #counts for primes counts = 2 #counts for iterations nums=2 while(counts<=p+1): #count for the numbers count = 0 #i is first prime number i=2 #check for non-primes while(i<= nums//2): if (nums % i == 0): #skip to the next number count += 1 #break out of the loop break #i will always increase for checking the condition i+=1 #confirm if number is prime if (count == 0 and nums != 1 ): print(" %d" %nums, end = ' ') #only goes up when we meet the condition counts += 1 #will always go up nums += 1 print("")
# This function is used to convert colorful images into grayscale. import cv2 def color2gray(input_path, output_path): name = input_path.split('/')[-1] output_path = output_path + 'gray_' + name img_array = cv2.imread(input_path, cv2.IMREAD_GRAYSCALE) img_array = cv2.resize() _ = cv2.imwrite(output_path, img_array) input_path = 'C:/Users/rolco/Desktop/old_3.jpg' output_path = 'C:/Users/rolco/Desktop/' color2gray(input_path, output_path)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 20 14:18:07 2021 @author: kamzon """ class Node: def __init__(self,val): self.l_child = None self.r_child = None self.data = val """ insert node into BST""" def insert(root, node): if (root is None): root= node if(root.data > node.data): if(root.l_child is None): root.l_child = node else: insert(root.l_child,node) else: if(root.r_child == None): root.r_child = node else: insert(root.r_child,node) """ in order print""" def in_order_print(root): if not root: return in_order_print(root.l_child) print(root.data) in_order_print(root.r_child) """ pre-order print""" def pre_order_print(root): if not root: return print(root.data) pre_order_print(root.l_child) pre_order_print(root.r_child) """ Delete node from tree""" def delete_node(root, data): if (root is None): return root elif(root.data>data): root.l_child = delete_node(root.l_child, data) elif(root.data<data): root.r_child = delete_node(root.r_child, data) else: # case 1 : leaf node if(root.l_child is None and root.r_child is None): root=None # case 2: node has one child elif(root.r_child is None): root.data = root.l_child.data root.l_child = None elif(root.l_child is None): root.data = root.r_child.data root.r_child = None # case 3: node has both children else: temp = root.r_child while(temp.l_child != None): temp = temp.l_child root.data=temp.data root.r_child = delete_node(root.r_child, temp.data) return root def Low_common_ancestor(root,node1,node2): if(root == None): return None else: if(root.data == node1.data and root.data == node2.data): return root elif((root.data > node1.data and root.data < node2.data) or (root.data < node1.data and root.data > node2.data)): return root elif(root.data > node1.data and root.data > node2.data): return Low_common_ancestor(root.l_child, node1, node2) elif(root.data < node1.data and root.data < node2.data): return Low_common_ancestor(root.r_child, node1, node2) """ example""" tree = Node(10) #in_order_print(tree) insert(tree, Node(5)) insert(tree, Node(1)) #in_order_print(tree) #pre_order_print(tree) insert(tree, Node(15)) insert(tree, Node(12)) insert(tree, Node(13)) insert(tree, Node(14)) insert(tree, Node(11)) insert(tree, Node(12.5)) in_order_print(tree) #pre_order_print(tree) print("delete 12") delete_node(tree, 12) in_order_print(tree)
# Joke Setup types_of_people = 10 x = f"There are {types_of_people} types of people." # Joke Punchline binary = "binary" do_not = "don't" y = f"Those who know {binary} and those who {do_not}." # Print out the joke. print(x) print(y) # Restate the joke, nesting the string as a variable inside an f-string print(f"I said: {x}") print(f"I also said: '{y}'") # The joke isn't funny, so use boolean. hilarious = False joke_evaluation = "Isn't that joke so funny?! {}" # False is printed along with joke evaluation print(joke_evaluation.format(hilarious))
#!/usr/bin/python # -*- coding: utf-8 -*- from collections import defaultdict import xml.etree.cElementTree as ET import re import tool """ The tool module that there are some functions being used in the fileis created by myself! Firstly, parsing the xml, so that we can know the tags and the subtags with some infomation basically """ # choose the file to analysis file_name_choose = input( "Please choose the file: \n 1: sample file 2: full file:\t") if file_name_choose == "1": file_name = "data/shanghai_china.osm" elif file_name_choose == "2": file_name = "originaldata/shanghai_china.osm" # create a dict about the information of the all tags all_tags_dict = tool.get_all_tags(file_name) print("In the file all tags and the quantity are:") print(all_tags_dict) # create a dict about the information of the elementary tag after the root tags_dict = tool.get_tags(file_name) print("\nThe information about the elementary tags after the root:") print(tags_dict) sub_tags_dict = defaultdict(int) for i in all_tags_dict.keys(): if i in ["osm", "bounds"] or i in tags_dict.keys(): continue else: sub_tags_dict[i] = all_tags_dict[i] print("\nThe information about the sub tags behind the elementary tags:") print(sub_tags_dict) """ Now, I will get the information of the tags' attributes.Next, I want to analysis the keys about the tags, which I use two different tags.They are elementary tags, and the other one is secondary tags. """ with open(file_name, "r") as file: elements = ET.iterparse(file, events=("start", "end")) parent_attribute = tool.get_attr_dict(elements, tags=tags_dict) with open(file_name, "r") as file: elements = ET.iterparse(file, events=("start", "end")) all_subattr_dict = tool.get_attr_dict(elements, tags=sub_tags_dict) print("\nThe structure of the parent attribute is:") print(parent_attribute) print("\nThe structure of all children attribute is:") print(all_subattr_dict) """ Now, I know the parent tags and their attribute.So I want to get its children's tags and their attribute.The parent tags' structure is parent_attr = {'relation': {'timestamp', 'uid', 'changeset', 'version', 'id', 'user'}, 'node': {'lat', 'timestamp', 'lon', 'uid', 'changeset', 'version', 'id', 'user'}, 'way': {'timestamp', 'uid', 'changeset', 'version', 'id', 'user'}} """ with open(file_name, "r") as file: trees = ET.parse(file) root = trees.getroot() child_attr = dict() for element in root: if element.tag in parent_attribute: for child in element.getchildren(): child_key = element.tag + "_child_" + child.tag for key in child.attrib.keys(): if child_key not in child_attr: child_attr[child_key] = set() child_attr[child_key].add(key) # push the parent attr to the all structure, then adding the children's attribute all_attr_struc = parent_attribute for child_key in child_attr: all_attr_struc[child_key] = child_attr[child_key] print("\nThe attribute of the all element and their children is:") print(all_attr_struc) # it takes long time to run the code, so pause to run if False: """ I will parse the elements attribute and the unique value. So, this progress is audit the value. """ # inital the variable contain the all tags, that is a dict all_value = dict() for key in all_attr_struc.keys(): all_value[key] = dict() for attr_key in all_attr_struc[key]: all_value[key][attr_key] = set() with open(file_name, "r") as file: trees = ET.parse(file) root = trees.getroot() for element in root: if element.tag in parent_attribute.keys(): parent_attr_value, child_attr_value = tool.get_attr_allvalues( element, element.tag) # union the parent attribute and its value into the variable all_value for key in parent_attr_value.keys(): all_value[element.tag][key] = all_value[element.tag][key].\ union(parent_attr_value[key]) # union the child attribute and its value into the variable all_value for child_tag in child_attr_value: for child_attr, attr_value in child_attr_value[child_tag].items(): all_value[child_tag][child_attr] = all_value[child_tag][child_attr].union( attr_value) """ Next, I pick up some tag to audit the value whether it's vilidate """ # create a set to store the value, which keeps unique with open(file_name, "r") as file: street_name = defaultdict(set) postal_code = defaultdict(set) wikipedia = defaultdict(set) name_en = defaultdict(set) for _, element in ET.iterparse(file, events=("start",)): if element.tag == "tag": if tool.audit_attribute(element, "addr:street"): street_name["addr:street"].add(element.attrib["v"]) if tool.audit_attribute(element, "addr:postcode"): postal_code["addr:postcode"].add(element.attrib["v"]) if tool.audit_attribute(element, "wikipedia"): wikipedia["wikipedia"].add(element.attrib["v"]) if element.tag in ["way", "node"]: for child in element.iter("tag"): if tool.audit_attribute(child, "name:en"): name_en["name:en"].add(child.attrib["v"]) print("The head 20 street name is:\n") pprint.pprint(list(street_name["addr:street"])[0:20]) print("The postal code is:\n") pprint.pprint(postal_code) print("The wikipedia is:\n") pprint.pprint(wikipedia) print("The head 20 english name is:\n") pprint.pprint(list(name_en["name:en"])[0:20]) # just check the attribute k check_out = {"lower": 0, "lower_colon": 0, "problemchars": 0, "other": 0} with open(file_name, "r") as file: for _, element in ET.iterparse(file): if element.tag == "tag": tool.count_attr_type(element, "k", check_out) print("The total of the attribute k in different type:\n") pprint.pprint(check_out) pattern = re.compile( r"(\S*\s+\([N|S|E|W]\)|Lib.|Rd|Lu|Rd.|Hwy.)$", re.IGNORECASE) # r"(Lib.|Rd|Lu|Rd.|\S[A-Z][a-z]*)$", re.IGNORECASE) problem_name = [] done_name = [] for name in name_en["name:en"]: m = pattern.search(name) if m: problem_name.append(m.group()) done_name.append(tool.update_vaue(name, pattern)) print("Before fixing the name:\n") pprint.pprint(problem_name) print("After fixing the name:\n") pprint.pprint(done_name) NODES_PATH = "result/nodes.csv" NODE_TAGS_PATH = "result/nodes_tags.csv" WAYS_PATH = "result/ways.csv" WAY_NODES_PATH = "result/ways_nodes.csv" WAY_TAGS_PATH = "result/ways_tags.csv" NODE_FIELDS = ['id', 'lat', 'lon', 'user', 'uid', 'version', 'changeset', 'timestamp'] NODE_TAGS_FIELDS = ['id', 'key', 'value', 'type'] WAY_FIELDS = ['id', 'user', 'uid', 'version', 'changeset', 'timestamp'] WAY_TAGS_FIELDS = ['id', 'key', 'value', 'type'] WAY_NODES_FIELDS = ['id', 'node_id', 'position'] class UnicodeDictWriter(csv.DictWriter, object): """Extend csv.DictWriter to handle Unicode input""" def writerow(self, row): super(UnicodeDictWriter, self).writerow({ k: (v.encode('utf-8') if isinstance(v, str) else v) for k, v in row.items() }) def writerows(self, rows): for row in rows: self.writerow(row) def get_element(file_name, tags=('node', 'way', 'relation')): """Yield element if it is the right type of tag""" context = ET.iterparse(file_name, events=('start', 'end')) _, root = next(context) for event, elem in context: if event == 'end' and elem.tag in tags: yield elem root.clear() with codecs.open(NODES_PATH, 'w') as nodes_file, \ codecs.open(NODE_TAGS_PATH, 'w') as nodes_tags_file, \ codecs.open(WAYS_PATH, 'w') as ways_file, \ codecs.open(WAY_NODES_PATH, 'w') as way_nodes_file, \ codecs.open(WAY_TAGS_PATH, 'w') as way_tags_file: nodes_writer = UnicodeDictWriter(nodes_file, NODE_FIELDS) node_tags_writer = UnicodeDictWriter(nodes_tags_file, NODE_TAGS_FIELDS) ways_writer = UnicodeDictWriter(ways_file, WAY_FIELDS) way_nodes_writer = UnicodeDictWriter(way_nodes_file, WAY_NODES_FIELDS) way_tags_writer = UnicodeDictWriter(way_tags_file, WAY_TAGS_FIELDS) nodes_writer.writeheader() # writeheader() node_tags_writer.writeheader() ways_writer.writeheader() way_nodes_writer.writeheader() way_tags_writer.writeheader() validator = cerberus.Validator() for element in get_element(file_name, tags=("node", "way")): el = tool.inital_csvs(element) print(el) if el: tool.validate_element(el, validator) if element.tag == "node": nodes_writer.writerow(el['node']) node_tags_writer.writerows(el['node_tags']) elif element.tag == 'way': ways_writer.writerow(el['way']) way_nodes_writer.writerows(el['way_nodes']) way_tags_writer.writerows(el['way_tags'])
""" Problem: Design a data structure for a pet shelter. The pet shelter must be able to add a dog or add a cat and associate a timestamp with each new pet (you can use an auto-increment id). The data structure must also support removeDog and removeCat, which remove the dog which has been here the longest (i.e. dequeue). The third operation to support is removeAny, which removes either the oldest dog or oldest cat. Throw an IndexError on any attempt to remove a pet from an empty shelter. Throw a ValeError if inserting a dog in addCat or a cat in addDog. Lastly, support numDogs(), numPets() and numCats(), which return the count for dogs, pets or cats stored within the shelter. Hints: You can use isinstance to determine if an object is an instance of some base class. """ from collections import deque class Animal: def __init__(self, name): self.name = name class Dog(Animal): def __init__(self, name): super().__init__(name) def __str__(self): return "<Dog: {}>".format(name) class Cat(Animal): def __init__(self, name): super().__init__(name) def __str__(self): return "<Cat: {}>".format(name) class PetShelter: def __init__(self): self._cats = deque() self._dogs = deque() self._id = 0 def addDog(self, dog): if isinstance(dog, Dog): self._dogs.append((dog, self._id)) self._id += 1 else: raise ValueError('Require instance of Dog') def addCat(self, cat): if isinstance(cat, Cat): self._cats.append((cat, self._id)) self._id += 1 else: raise ValueError('Require instance of Cat') def removeDog(self): if not self._dogs: raise IndexError('No dog in the shelter') return self._dogs.popleft() def removeCat(self): if not self._cats: raise IndexError('No cats in the shelter') return self._cats.popleft() def removeAny(self): if not (self._cats or self._dogs): raise IndexError('No pets in the shelter') if self._dogs and (not self._cats): return self._dogs.popleft() if self._cats and (not self._dogs): return self._cats.popleft() cat1 = self._cats[0] dog1 = self._dogs[0] if cat1[1] < dog1[1]: return self._cats.popleft() else: return self._dogs.popleft() def numCats(self): return len(self._cats) def numDogs(self): return len(self._dogs) def numPets(self): return len(self._cats) + len(self._dogs) if __name__ == "__main__": shelter = PetShelter() d1 = Dog("udon") c1 = Cat("meow") d2 = Dog("woof") d3 = Dog("pudding") c2 = Cat("cookie") c3 = Cat("binggan") shelter.addDog(d1) shelter.addCat(c1) shelter.addDog(d2) shelter.addDog(d3) shelter.addCat(c2) shelter.addCat(c3) print(shelter.numCats()) print(shelter.numDogs()) print(shelter.numPets()) print(shelter.removeCat()) print(shelter.removeDog()) print(shelter.removeAny())
class Node: def __init__(self, data=None): self.data = data self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, data): if self.root == None: self.root = Node(data) else: self.rec_insert(data, self.root) def rec_insert(self, data, curr): if data > curr.data: if curr.right == None: curr.right = Node(data) else: self.rec_insert(data, curr.right) elif data < curr.data: if curr.left == None: curr.left = Node(data) else: self.rec_insert(data, curr.left) else: print(f"{data} already exists in tree.") def display_tree(self): if self.root != None: self.rec_display(self.root) else: print("Tree is empty.") def rec_display(self, curr): if curr !=None: self.rec_display(curr.left) print(curr.data) self.rec_display(curr.right) bst = BinarySearchTree() from random import randint for _ in range(49): data = randint(0,500) bst.insert(data) bst.display_tree()
def list_mean(x): if x==[]: return "Must key in the numbers" i=0 for h in x: i=i+h i=i/float(len(x)) return i print list_mean([1,2,3,4]) print list_mean([1,3,4,5,2]) print list_mean([]) print list_mean([2])
status=True while(status): pl1=str(input("Enter player1 turn")) pl2=str(input("Enter player2 turn")) if pl1=="Rock" and pl2=="Scissors" or pl1=="Scissors" and pl2=="Rock": print("Rock beats Scissors") status=False elif pl1=="Scissors" and pl2=="Paper" or pl1=="Paper" and pl2=="Scissors": print("Scissors beats paper") status=False elif pl1=="Paper" and pl2=="Rock" or pl1=="Rock" and pl2=="Paper": print("Paper beats Rock") status=False elif pl1=="Rock" and pl2=="Rock" or pl1=="Paper" and pl2=="Paper" or pl1=="Scissors" and pl2=="Scissors" : print("No one wins")
# **************************************************************** # AULA: Visão Computacional # Prof: Adriano A. Santos, DSc. # **************************************************************** # Importando a biblioteca OpenCV import cv2 # Imagem aquivo = "./imagens/raposa.jpg" # Carregando a imagem image = cv2.imread(aquivo) # Obtem valores para calcular o valor do ponto central da imagem (h, w) = image.shape[:2] centro = (w // 2, h // 2) # Rotacionando a imagem em 90 graus matriz = cv2.getRotationMatrix2D(centro, 90, 1.0) nova_imagem = cv2.warpAffine(image, matriz, (w, h)) cv2.imshow("Imagem rotacionada", nova_imagem) cv2.waitKey(0)
from abc import ABC, abstractmethod import pandas as pd class Abstrata(ABC): def __init__(self, path_from, path_to): self.path_from = path_from self.path_to = path_to @abstractmethod def processa(self): # Essa função irá herdar os comandas assim que for chamada pass
# Python program to display calendar of given month of the year # import module import calendar # To ask month and year from the user year= input("Enter year: ") month = input("Enter month: ") # display the calendar print(calendar.month(year, month))
import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns # Importing the dataset dataset = pd.read_csv('D:/Udemy ML/ML_Complete/Part 3 - Classification/Dataset2/Classified Data.csv') print(dataset.shape) count=pd.value_counts(dataset['TARGET CLASS']) print(count) x=dataset.iloc[:,0:11] y=dataset.iloc[:,11] ''' k=sns.pairplot(dataset) plt.show(k) ''' from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 0) from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() x_train = sc_X.fit_transform(x_train) x_test = sc_X.transform(x_test) print(x_train) # Fitting the knn Regression Model to the dataset from sklearn.neighbors import KNeighborsClassifier classifier=KNeighborsClassifier(n_neighbors=23,metric='minkowski',p=2) classifier.fit(x_train,y_train) y_pred=classifier.predict(x_test) print(y_pred) #Making confution matrix from sklearn.metrics import confusion_matrix,classification_report cm=confusion_matrix(y_test,y_pred) print(cm) print(classification_report(y_test,y_pred)) #choosing k value error_rate=[] for i in range(1,40): classifier=KNeighborsClassifier(n_neighbors=i) classifier.fit(x_train,y_train) y_pred=classifier.predict(x_test) error_rate.append(np.mean(y_pred!=y_test)) plt.figure(figsize=(10,6)) plt.plot(range(1,40),error_rate,color='blue',linestyle='dashed',marker='o',markerfacecolor='red',markersize=10) plt.title('Error Rate vs K value') plt.xlabel('K') plt.ylabel('Error Rate') plt.show()
import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (20.0,10.0) #reading data data=pd.read_csv('C:/Users/kiit1/Documents/headbrain.csv') #collecting X and Y X=data['Head Size(cm^3)'].values Y=data['Brain weight(grams)'].values #Finding Mean value mean_X=np.mean(X) mean_Y=np.mean(Y) #total no of values k=len(X) #calculate m and c numerator=0 denomirator=0 for i in range(k): numerator=numerator+(X-mean_X)*(Y-mean_Y) denomirator=denomirator+(X-mean_X)**2 m=numerator/denomirator c=mean_Y-(m*mean_X) print(m,c)
import natch @natch.lt(0) def factorial(x): x = abs(x) x = factorial(x) x = -1 * x return x @natch.eq(0) def factorial(x): return 1 @natch.eq(1) def factorial(x): return 1 @natch.gt(1) def factorial(x): x = x * factorial(x - 1) return x for i in range(-5, 6): result = factorial(i) print(i, result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # anuther :zhanglei def read_file(): #afile = file('data.txt', 'r') afile = open('data_write.txt','r') for i in afile.readlines(): print i.strip().decode('utf-8') afile.close() def write_file(): name_list=[u'张三',u'李四',u'王五'] afile=open('data_write.txt','w') for i in name_list: afile.write(i.encode('utf-8')+'\n') afile.close() import os if __name__=='__main__': read_file() #write_file()
def red_color(): return 'red' def blue_color(): return 'blue' def white_color(): return 'white' def is_white(button): if button == white_color(): return True return False def is_red(button): if button == red_color(): return True return False def is_blue(button): if button == blue_color(): return True return False class Game: def __init__(self): self.reset_game() def reset_game(self): self.my_color = None self.positions = [red_color(), red_color(), white_color(), blue_color(), blue_color()] def move_button(self, position_one, position_two): if position_one == 0 and position_two == 1: print "Invalid Line" return False if position_one == 1 and position_two == 0: print "Invalid Line" return False if is_white(self.positions[position_one]): print "First White" return False if not is_white(self.positions[position_two]): print "Second Not White" return False if not self.is_move_valid(position_one): return False if self.my_color == None: self.my_color = self.positions[position_one] print "My Color" print self.my_color if is_blue(self.my_color): if is_blue(self.positions[position_one]): self.switch_positions(position_one, position_two) return True if is_red(self.my_color): if is_red(self.positions[position_one]): self.switch_positions(position_one, position_two) return True return False def is_move_valid(self, switch_position): white_position = self.find_white() if white_position == 0: if switch_position == 2 or switch_position == 3: return True else: return False elif white_position == 1: if switch_position == 2 or switch_position == 4: return True else: return False elif white_position == 2: return True elif white_position == 3: if switch_position != 1: return True else: return False elif white_position == 4: if switch_position != 0: return True else: return False else: return False def find_white(self): for position, color in enumerate(self.positions): if is_white(color): return position return -1 def switch_positions(self, position_one, position_two, color=None): if color != None and self.my_color == None: if is_blue(color): self.my_color = red_color() elif is_red(color): self.my_color = blue_color() old_position = self.positions[position_one] self.positions[position_one] = self.positions[position_two] self.positions[position_two] = old_position def is_game_over(self): if is_white(self.positions[0]): if is_red(self.positions[2]) and is_red(self.positions[3]): return True if is_blue(self.positions[2]) and is_blue(self.positions[3]): return True if is_white(self.positions[1]): if is_red(self.positions[2]) and is_red(self.positions[4]): return True if is_blue(self.positions[2]) and is_blue(self.positions[4]): return True return False
# Abrir arquivo em diretório arquivo = open("c:/Users/Minecraft/Desktop/arquivo.txt") # Ler linhas de texto do arquivo """ Linhas = arquivo.readlines() #Mostrar linhas como elementos for linha in Linhas: print(linha) """ # Ler texto completo texto = arquivo.read() print(texto)
import re import nltk nltk.download('punkt') nltk.download('stopwords') nltk.download('wordnet') import string from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() def lemmatize_words(text): return " ".join([lemmatizer.lemmatize(word) for word in text.split()]) from nltk.stem.porter import PorterStemmer stemmer = PorterStemmer() def stem_words(text): return " ".join([stemmer.stem(word) for word in text.split()]) from nltk.corpus import stopwords STOPWORDS = set(stopwords.words('english')) def remove_stopwords(text): return " ".join([word for word in str(text).split() if word not in STOPWORDS]) PUNCT_TO_REMOVE = string.punctuation def remove_punctuation(text): return text.translate(str.maketrans('', '', PUNCT_TO_REMOVE)) def remove_numbers(text): return " ".join([word for word in text.split() if word.isalpha()]) def full(text, lemmatize=False): text = text.translate(str.maketrans('', '', PUNCT_TO_REMOVE)).lower() text = [word for word in text.split() if word.isalpha()] text = [word for word in text if word not in STOPWORDS] if lemmatize: text = [lemmatizer.lemmatize(word) for word in text] else: text = [stemmer.stem(word) for word in text] return " ".join(text) if __name__ == '__main__': text = 'Just sim8le text, for test!' text = remove_punctuation(text.lower()) text = remove_numbers(text) text = remove_stopwords(text) text = stem_words(text) print(text) text = 'Just sim8le text, for test!' print(full(text))
s = input().split(" ") if int(s[0])!=0 and int(s[1])!=0 and int(s[2])!=0 and int(s[0]) + int(s[1]) + int(s[2]) == 180: print("Yes") else: print("No")
n = int(input()) m = int(input()) sum = 0 for i in range(-10, m+1): for j in range(1, n+1): sum += int(((i + j)**3) / (j**2)) print(sum)
n = input() #b = sum of digits of input b = 0 for i in n: b+= int(i) #checkprime function def checkprime(num): t=1 for i in range(2,num): if (num % i) == 0: t=0 break return t i = 0 n = int(n) while i < b: n += 1 if checkprime(n)== 1: i += 1 print(n)
''' Este website é igual uma loja de livros 'http://books.toscrape.com/' Eu passo por todas as páginas do site, pego as urls da cada livros e pego as informações da cada livro: Título, categoria, preço e quantidade no estoque Depois eu salvo no MySQL. Coloquei um intervalo de 1 segundo para a url de cada livro, se você quiser removê-lo fique a vontade. Aviso: coloque a sua senha para fazer a conexão com o banco de dados e mude o nome do database. ''' import requests import time from bs4 import BeautifulSoup from mysql.connector import connect, Error import re connection = connect(host= '127.0.0.1', port= 3306, user= 'root', password= 'COLOQUE SUA SENHA', database= 'web_scraping', charset='utf8') cursor = connection.cursor(buffered=True) cursor.execute(''' CREATE TABLE IF NOT EXISTS livraria( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(1000) NULL, category VARCHAR(100) NULL, price DECIMAL(6,2) NULL, inStock INT NULL) ''') connection.commit() def insertBookIfNotExists(bookTitle, bookCategory, bookCost, booksInStock): ''' Confiro se o livro já existe no banco de dados, se não, eu o adiciono. ''' cursor.execute('''SELECT * FROM livraria WHERE title = %(bookTitle)s AND category = %(bookCategory)s''', {'bookTitle': bookTitle, 'bookCategory': bookCategory}) if cursor.rowcount == 0: cursor.execute(''' INSERT INTO livraria (title, category, price, inStock) VALUES (%s, %s, %s, %s)''', (bookTitle, bookCategory, bookCost, booksInStock)) connection.commit() def getBeautifulSoupFromHTML(url): try: page = requests.get(url,headers={'User-Agent': 'Mozilla/5'}) except requests.exceptions.RequestException as e: print(e.message) raise SystemExit(e) return BeautifulSoup(page.text, 'html.parser') # coleto as informações do Livro e mando salvar no banco de dados def getBookInfo(bookUrl): print(bookUrl) print('-'*40) bs = getBeautifulSoupFromHTML(bookUrl) book = bs.find('article', {'class': 'product_page'}) # Título do Livro bookTitle = book.h1.get_text() # Categoria do Livro bookCategory = bs.find('ul', {'class': 'breadcrumb'}).find_all('li')[2].get_text().strip() # Preço do Livro costRegex = re.compile(r'(\d+)\.(\d{2})') bookPrice = costRegex.search(book.find('p', {'class': 'price_color'}).get_text()).group() # Quantos desse Livro tem no estoque findNumberRegex = re.compile(r'\d+') numberOfbooks = findNumberRegex.search(book.find('p', {'class': 'instock availability'}).get_text()).group() insertBookIfNotExists(bookTitle, bookCategory, bookPrice, numberOfbooks) # Pego o endereço de cada Livro na página def getAllBookFromPage(url): bs = getBeautifulSoupFromHTML(url) for link in bs.find_all('div', {'class': 'image_container'}): #Aqui eu reconstruo o url, porque nesse website os urls não estão uniformemente formatados bookUrlRegex = re.compile(r'[^/]+/index\.html$') bookUrl = 'http://books.toscrape.com/catalogue/{}'.format(bookUrlRegex.search(link.a['href']).group()) getBookInfo(bookUrl) time.sleep(1) def getPages(pageUrl): ''' Depois de coletar as informações de cada livro nesta página, movo para próxima página, até que não existam mais páginas. ''' getAllBookFromPage(pageUrl) bs = getBeautifulSoupFromHTML(pageUrl) nextPageLink = bs.find('li', {'class': 'next'}) if nextPageLink != None: nextPageUrl = bs.find('li', {'class': 'next'}).a['href'] #Aqui eu reconstruo o url, porque nesse website os urls não estão uniformemente formatados findPageRegex = re.compile(r'page.+(html$)') nextPage = 'http://books.toscrape.com/catalogue/{}'.format(findPageRegex.search(nextPageUrl).group()) print('NEW PAGE') print(nextPage) print('-'*40) getPages(nextPage) getPages('http://books.toscrape.com/') ''' São dados simples, escrevi simples análises. ''' cursor.execute('SELECT * FROM livraria LIMIT 10') for row in cursor.fetchall(): print(row) cursor.execute('SELECT COUNT(id) FROM livraria') print(cursor.fetchone()) cursor.execute( '''SELECT category, COUNT(id) AS books_per_category FROM livraria GROUP BY category ORDER BY COUNT(id) DESC''' ) for row in cursor.fetchall(): print(row) cursor.close() connection.close()
import math import pygame class Paddle(): """ The paddle at the bottom that the player controls. """ def __init__(self): super().__init__() self.width = 100 self.height = 20 self.image = pygame.Surface([self.width, self.height]) self.rectangle = self.image.get_rect() self.screenheight = pygame.display.get_surface().get_height() self.screenwidth = pygame.display.get_surface().get_width() self.rectangle.x = 0 self.rectangle.y = self.screenheight-self.height self.touched_by_ball = True def check_collision(self): pass def draw(self, screen, pygame): color = (0, 0, 0) pygame.draw.rect(screen, color, self.rectangle) def update(self, **kwargs): """ Update the player position. """ pos = pygame.mouse.get_pos() self.rectangle.x = pos[0] if self.rectangle.x > self.screenwidth - self.width: self.rectangle.x = self.screenwidth - self.width self.touched_by_ball = True class KineticPaddle(Paddle): pass
"""Implemention of the Maze ADT using a 2-D array.""" from arrays import Array2D from lliststack import Stack class Maze: """Define constants to represent contents of the maze cells.""" MAZE_WALL = "*" PATH_TOKEN = "x" TRIED_TOKEN = "o" def __init__(self, num_rows, num_cols): """Creates a maze object with all cells marked as open.""" self._maze_cells = Array2D(num_rows, num_cols) self._start_cell = None self._exit_cell = None def num_rows(self): """Returns the number of rows in the maze.""" return self._maze_cells.num_rows() def num_cols(self): """Returns the number of columns in the maze.""" return self._maze_cells.num_cols() def set_wall(self, row, col): """Fills the indicated cell with a "wall" marker.""" assert row >= 0 and row < self.num_rows() and \ col >= 0 and col < self.num_cols(), "Cell index out of range." self._maze_cells[row, col] = self.MAZE_WALL def set_start(self, row, col): """Sets the starting cell position.""" assert row >= 0 and row < self.num_rows() and \ col >= 0 and col < self.num_cols(), "Cell index out of range." self._start_cell = _CellPosition(row, col) def set_exit(self, row, col): """Sets the exit cell position.""" assert row >= 0 and row < self.num_rows() and \ col >= 0 and col < self.num_cols(), "Cell index out of range." self._exit_cell = _CellPosition(row, col) def find_path(self): """ Attempts to solve the maze by finding a path from the starting cell to the exit. Returns True if a path is found and False otherwise. """ # current = (self._start_cell.row, self._start_cell.column) # current[0] -= 1 # if self._valid_move(*current): # self._mark_path(*current) # current[0] -= 1 # if self._valid_move(*current): # self._mark_path(*current) # else: # current[0] += 1 # if self._valid_move(*current): # self._mark_path(*current) current = (self._start_cell.row, self._start_cell.col) self._mark_path(*current) stack = Stack() stack.push(current) while not stack.is_empty() and not self._exit_found(*stack.peek()): current = stack.peek() # print(current) found = False for row, col in [(-1, 0), (0, 1), (1, 0), (0, -1)]: next_cell = (current[0] + row, current[1] + col) if self._valid_move(*next_cell): stack.push(next_cell) self._mark_path(*next_cell) found = True break # for row in [-1, 1]: # next = (current[0] + row, current[1]) # if self._valid_move(*next): # stack.push(next) # self._mark_path(*next) # found = True # break # if found: # continue # # for col in [-1, 1]: # next = (current[0], current[1] + col) # if self._valid_move(*next): # stack.push(next) # self._mark_path(*next) # found = True # break if not found: self._mark_tried(*current) stack.pop() if stack.is_empty(): return False elif self._exit_found(*stack.peek()): return True def reset(self): """Resets the maze by removing all "path" and "tried" tokens.""" for row in range(self.num_rows()): for col in range(self.num_cols()): if self._maze_cells[row, col] in [Maze.PATH_TOKEN, Maze.TRIED_TOKEN]: self._maze_cells[row, col] = None def __str__(self): """Returns a text-based representation of the maze.""" maze = "" for row in range(self.num_rows()): for col in range(self.num_cols()): maze += (self._maze_cells[row, col] if self._maze_cells[row, col] is not None else "_") + " " maze += "\n" return maze def _valid_move(self, row, col): """Returns True if the given cell position is a valid move.""" return row >= 0 and row < self.num_rows() \ and col >= 0 and col < self.num_cols() \ and self._maze_cells[row, col] is None def _exit_found(self, row, col): """Helper method to determine if the exit was found.""" return row == self._exit_cell.row and col == self._exit_cell.col def _mark_tried(self, row, col): """Drops a "tried" token at the given cell.""" self._maze_cells[row, col] = self.TRIED_TOKEN def _mark_path(self, row, col): """Drops a "path" token at the given cell.""" self._maze_cells[row, col] = self.PATH_TOKEN class _CellPosition(object): """Private storage class for holding a cell position.""" def __init__(self, row, col): self.row = row self.col = col # if __name__ == "__main__": # maze = Maze(4, 4)
string = "achal chanish mridul puneet" names = string.split(" ") print names pop_name = names.pop(0) print names pop_name = names.pop(-1) print names
#!/usr/bin/env python3 import skilstak.colors as c print(c.clear) def ask(question): print(c.red + question + c.reset) answer = input("> " + c.base3).lower().strip() print(c.reset) return answer name = ask(c.b + "What is your name?") def diecrew(): print(c.red + """You have lost members of your crew, your PTSD just got worse. The problem was only barely fixed. You just generally suck at being a captain.""") def livecrew(): print(c.g + """You have saved all of your crew, gathered provisions and generally ensured the safety of your, and advanced on your travels.""") def livecrew2(): print(c.y + """You barely made it through and with some casulties. Some of your crew is dead and the moral has gotten much lower. Even the problem was only solved halfway.""") q1 = ask(c.cyan + name + """ is on a spaceship, about to take off. They are planning to take a trip to space. They are currently on a naval base in the Gulf of Guinea in the Atlantic Ocean(Point 0,0). It is a mission to Mars. (They are prepared to never return to Earth.) The mission seems like a success, but when they are about to leave the atmosphere, their ship has a malfunction. The ship is now headed in a curved shape, like f(x) = the square root of x. The crew is desperately trying to fix the issue, but for now they have to keep the ship stable so they do not blow up. The captain wants to keep as many people alive as possible, there are 29 current crew members. Their current situation demands them to solve this problem so that they can fix th orbital manuevering engines. (Sheet problem number one) """) if q1 in ['a', 'A', '1st choice', '1st answer']: diecrew() if q1 in ['b', 'B',]: diecrew() if q1 in ['c', 'C',]: livecrew() q2 = ask(c.base3 + """After taking a quick snapchat of Mars, the crew recieved a message that if they could they were to travel to the next planet in the alignment. The crew responded that they could continue. But after they were flung out orbit, there was still thruster problems on the ship. As well as an incoming asteroid that was on a collison course for the ship. They needed to fix the thruster issue in order to avoid the incoming threat. The goal is still to save as many crew members as possible. To fix the thrusters complete problem so the crew could travel to Jupiter. (See problem sheet number two)""") if q2 in ['a', 'A',]: livecrew2() q3 = ask(c.base3 + """The crew arrived at Jupiter. While facetiming your dog becuase you think the problems have settled down since the last time an issue happened: the ship has a huge tremor but there are no earthquakes in space. You look outside the port window and you see a strange vessel firing projectiles at you. You want to send a message for a cease fire. But surprise, surprise the communications ray is broken and guess who has to fix it. You need to send a message quickly so your ship does not get destroyed. (See problem sheet number three)""") if q2 in ['b', 'B']: diecrew() q3 = ask(c.base3 + """The crew arrived at Jupiter. While facetiming your dog becuase you think the problems have settled down since the last time an issue happened: the ship has a huge tremor but there are no earthquakes in space. You look outside the port window and you see a strange vessel firing projectiles at you. You want to send a message for a cease fire. But surprise, surprise the communications ray is broken and guess who has to fix it. You need to send a message quickly so your ship does not get destroyed. (See problem sheet number three)""") if q2 in ['c', 'C']: livecrew() q3 = ask(c.base3 + """The crew arrived at Jupiter. While facetiming your dog becuase you think the problems have settled down since the last time an issue happened: the ship has a huge tremor but there are no earthquakes in space. You look outside the port window and you see a strange vessel firing projectiles at you. You want to send a message for a cease fire. But surprise, surprise the communications ray is broken and guess who has to fix it. You need to send a message quickly so your ship does not get destroyed. (See problem sheet number three)""") if q3 in ['a', 'A']: diecrew() q4 = ask(c.base3 + """The next planet is fast approaching, you make contact with the vessel that was opening fire on you earlier and cleared up the mist understanding. They thought that you were an enemy ship for the current war that they have that is the cause of them being in our solarsystem. Then, to apologize, the creatures offer to help to make repairs on your ship.(The communication is being performed through hand gestures and motions. But while the supplies were being moved over from the other ship to fix the damaged one, on of your crew bumps into one of the species crew hard. The species crew got very angry and started to raise its voice very loudly. Your next problem is to find the answer to calming the crew member down and not make a scene so that your crew members can be safe. (The species crew looked very on edge already. (See problem sheet number four)""") if q3 in ['b', 'B',]: livecrew() q4 = ask(c.base3 + """The next planet is fast approaching, you make contact with the vessel that was opening fire on you earlier and cleared up the mist understanding. They thought that you were an enemy ship for the current war that they have that is the cause of them being in our solarsystem. Then, to apologize, the creatures offer to help to make repairs on your ship.(The communication is being performed through hand gestures and motions. But while the supplies were being moved over from the other ship to fix the damaged one, on of your crew bumps into one of the species crew hard. The species crew got very angry and started to raise its voice very loudly. Your next problem is to find the answer to calming the crew member down and not make a scene so that your crew members can be safe. (The species crew looked very on edge already. (See problem sheet number four)""") if q4 in ['a', 'A']: diecrew() q5 = ask(c.base3 + """The crew and yourself are both very tired from the journey and the main control gave you the okay to go home. There is but one last problem that you need to sovle. The fuel is not being able to turn and get into the engine. You need to fix the converter so that you can use the fuel. The problem most likely occured when you were being chased and shot at by the creatures. Another peice that you must report back. But for now all you need to do to get home is solve this problem: (See problem sheet number five)""") if q4 in ['b', 'B']: livecrew() q5 = ask(c.base3 + """The crew and yourself are both very tired from the journey and the main control gave you the okay to go home. There is but one last problem that you need to sovle. The fuel is not being able to turn and get into the engine. You need to fix the converter so that you can use the fuel. The problem most likely occured when you were being chased and shot at by the creatures. Another peice that you must report back. But for now all you need to do to get home is solve this problem: (See problem sheet number five)""") if q5 in ['a', 'A']: print(c.r + """You could not return to Earth and the ship wandered forever in space with no one coming to rescue you.""") if q5 in ['b', 'B']: print(c.g + """Congragulations, you have won the game and all of your crew members made it home safely. You were awarded a medal for your efforts.""")
import random # Welcome to the game text: def welcome(): print('Answer "yes" if given number is prime. Otherwise answer "no".\n') # Function returns tuple with question and right answer: def question_and_answer(): num = random.randint(1, 101) step = 2 question = 'Question: {}'.format(num) while step <= num: if step == num: answer = 'yes' break elif num == 1 or num == 2: answer = 'yes' break elif num % step != 0: step += 1 else: answer = 'no' break return question, answer
from numpy import * arr=array([ [1,2,3,5,4,2], [4,5,6,8,9,3] ]) print(arr.ndim)# attribute ndim num of dimension print(arr.shape)#num of rows & colums print(arr.size) arr1=arr.flatten()#convert 2D to 1D print(arr1) arr2=arr1.reshape(2,2,3)# 3D array print(arr2) m=matrix(arr) print(m) m=matrix('1,2,3,4 ; 5,6,7,8')# dont need to array print(m) m=matrix('1,2,3;4,5,6;7,8,9') print(diagonal(m)) print(m.min()) print(m.max()) m1=matrix('1,2,3;4,5,6;7,8,9') m2=matrix('1,5,3;4,3,6;1,8,5') m3=m1+m2; print(m3) m3=m1*m2; print(m3)
class computer: pass c1=computer() c2=computer() print(id(c1)) print(id(c2)) class comput: wheels=4 # class variable def __init__(self): self.name="navin" #instance variable because values are change self.age=20 #instance variable inside of init def update(self): self.age=28 c1=comput() c2=comput() if c1==c2: print("same age") else: print("different") c1.update() c1.name="green" c1.age=12 print(c1.name) print(c2.name)
pos = -1 def search(list,n): l=0 u=len(list)-1 while l <= u: mid=(l+u)//2 # integer division if list[mid]==n: globals() ['pos'] = mid return True else: if list[mid]<n: l= mid+1 else: u=mid-1 return False list = [3,4,5,6,7,8] n = 5 if search (list,n): print("Found",pos+1) else: print("Not Found")
#!/bin/env python3 # -*- coding: utf-8 -*- # version: Python3.X """ 无边界地图 参考讨论区给出的算法进行实现 题目链接: http://www.qlcoder.com/task/75d8 """ __author__ = '__L1n__w@tch' class Point: def __init__(self, x=None, y=None, is_alive=False): # is_alive 为 True 表示是生命体 self.x, self.y, self.is_alive = x, y, is_alive def __eq__(self, other): return self.x == other.x and self.y == other.y def __hash__(self): return hash((self.x, self.y)) def __repr__(self): return "({}, {}) - {}".format(self.x, self.y, "生命体" if self.is_alive else "空地") def update_count_dict(alive_list): """ 遍历列表,对所有生命体,将其周围8个格子的"生命体计数"加一。 :param alive_list: 生命体列表 :return: None, 将结果直接更新到 count_dict 中 """ count_dict = dict() for each_point in alive_list: # 依次更新 <左上, 上, 右上, 左, 右, 左下, 下, 右下> 共 8 个各自的数据 point_west_north = Point(each_point.x - 1, each_point.y + 1) point_west_north.is_alive = True if point_west_north in alive_list else False count_dict[point_west_north] = count_dict.get(point_west_north, 0) + 1 point_north = Point(each_point.x, each_point.y + 1) point_north.is_alive = True if point_north in alive_list else False count_dict[point_north] = count_dict.get(point_north, 0) + 1 point_north_east = Point(each_point.x + 1, each_point.y + 1) point_north_east.is_alive = True if point_north_east in alive_list else False count_dict[point_north_east] = count_dict.get(point_north_east, 0) + 1 point_west = Point(each_point.x - 1, each_point.y) point_west.is_alive = True if point_west in alive_list else False count_dict[point_west] = count_dict.get(point_west, 0) + 1 point_east = Point(each_point.x + 1, each_point.y) point_east.is_alive = True if point_east in alive_list else False count_dict[point_east] = count_dict.get(point_east, 0) + 1 point_west_south = Point(each_point.x - 1, each_point.y - 1) point_west_south.is_alive = True if point_west_south in alive_list else False count_dict[point_west_south] = count_dict.get(point_west_south, 0) + 1 point_south = Point(each_point.x, each_point.y - 1) point_south.is_alive = True if point_south in alive_list else False count_dict[point_south] = count_dict.get(point_south, 0) + 1 point_west = Point(each_point.x + 1, each_point.y - 1) point_west.is_alive = True if point_west in alive_list else False count_dict[point_west] = count_dict.get(point_west, 0) + 1 return count_dict def update_alive_list(count_dict, alive_list): """ 遍历字典,对周围有生命体的格子,检查它是否能继续生存/繁殖出新的生命体。将结果存储到新列表中 :param count_dict: 计数器字典 :param alive_list: 生命体列表 :return: list(), 更新后的结果 """ result_list = list() for each_point, count in count_dict.items(): # 空地周围有 3 个生命体 if not each_point.is_alive and count == 3: each_point.is_alive = True result_list.append(each_point) # 生命体周围有 2 或 3 个生命体 elif each_point.is_alive and 2 <= count <= 3: each_point.is_alive = True result_list.append(each_point) else: each_point.is_alive = False return result_list def init(): """ 初始化游戏开始的情况, 即有 5 个生命体的情况 :return: tuple(), (list, dict), 分别表示含有生命体的列表, 以及一个计数器字典 """ alive_list = list() count_dict = dict() # 默认最中间那个作为 0,0 alive_list.append(Point(0, 0, True)) alive_list.append(Point(0, 1, True)) alive_list.append(Point(0, -1, True)) alive_list.append(Point(-1, 0, True)) alive_list.append(Point(1, 1, True)) return alive_list, count_dict def solve(): # 初始化游戏开始的情况, 即有 5 个生命体的情况 alive_list, count_dict = init() result_dict = dict() times = 0 while times < 2000: # 遍历列表,对所有生命体,将其周围8个格子的"生命体计数"加一。 count_dict = update_count_dict(alive_list) # 遍历字典,对周围有生命体的格子,检查它是否能继续生存/繁殖出新的生命体。将结果存储到新列表中 alive_list = update_alive_list(count_dict, alive_list) # 打印列表长度 times += 1 # print("[*] 第 {times} 轮迭代后: {0}".format(alive_list, times=times)) # print("[*] 第 {times} 轮迭代后: {times}-{0}".format(len(alive_list), times=times)) result_dict[times] = len(alive_list) max_result = max(result_dict.items(), key=lambda item: item[1]) print("[*] 第 {times} 迭代得到的值最大, 为: {count}, 即 {times}-{count}".format(times=max_result[0], count=max_result[1])) if __name__ == "__main__": solve()
''' EXTRACTING FEATURES Jeff Thompson | 2018 | jeffreythompson.org A simple example that recreates the one we built in Processing: load an image, resize it and convert to grayscale, and create an array from the pixels. In the 'Better' version next, we'll improve on this and feed it into some machine learning algorithms to extract the most important features. ''' from glob import glob # for getting a list of image files from PIL import Image # load and process image files import numpy as np # numpy for all our vector needs # size to make our vectors width = height = 16 # get a list of jpg files in the 'images' folder using the glob library print 'gathering image files...' filenames = glob('input/*.jpg') print '- found ' + str(len(filenames)) # we can create a function that takes a filename and width/height as # an argument and converts it into a vector, just like in the Processing example def image_to_vector(filename, w, h): img = Image.open(filename) # open the image img = img.resize( (w,h) ) # resize it (note dims are in a 'tuple') img = img.convert('L') # convert to grayscale (L = luminance) pixels = list(img.getdata()) # get its pixel values as a list pixels = np.array(pixels) # convert that list into a numpy array pixels = pixels.astype('uint8') # we don't need float data, so convert it to integers return pixels # and send back the resulting array # convert the first image into a vector sample = image_to_vector(filenames[0], width, height) print sample.shape # print the dimensions of the vector print sample[0:3] # and print the first three values # let's use this to load up all the images into an array # first, create an empty array at the size we need print 'creating array of image vectors...' images = np.empty( [len(filenames), width*height] ) # then go though all the images, create vectors from them # and add them to the array for i, filename in enumerate(filenames): print '- ' + str(i+1) + '/' + str(len(filenames)) px = image_to_vector(filename, width,height) px = px.astype(np.float32) # convert back to float (since we'll normalize the data) images[i] = px # add it to our array # normalize image data into a range of 0-1 (instead of 0-255) images -= images.min() # make the lowest value 0 images /= images.max() # and divide by the max to make largest = 1 print images
import csv def read_question(): with open("sample_data/question.csv", "r") as csv_file: csv_reader = csv.reader(csv_file, delimiter = ',', quotechar = '"') list_to_return = [] for row in csv_reader: list_to_return.append(row) return list_to_return[1:] def write_question(matrix_of_questions): new_matrix_of_questions = [] new_matrix_of_questions.append([['id','submission_time','view_number','vote_number','title','message','image']]) for i in matrix_of_questions: new_matrix_of_questions.append(i) with open('sample_data/question.csv', 'w', newline='') as file: writer = csv.writer(file) for i in new_matrix_of_questions: writer.writerow(i)
# -*- coding: utf-8 -*- """ Created on Sat Apr 26 13:42:13 2014 @author: eocallaghan """ import pygame from pygame.locals import * import random import math import time """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ Model """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ """--------------------------------Drawable----------------------------------""" class Drawable(object): __metaclass__ = ABCMeta @abstractmethod def draw(self,screen): pass @abstractmethod def translate(self,deltaPosition): pass """--------------------------------Body and Planent----------------------------------""" class body(Drawable): def __init__(mass, radius, position, velocity, color): self.mass = mass; self.radius = radius; self.position = position; self.velocity = velocity; self.color = color; self.acceleration = (0,0); def draw(self, screen): pygame.draw.circle(screen, self.color, self.position, self.radius, 0); def translate(self, deltaPosition): self.position(0) += deltaPosition(0); self.position(1) += deltaPosition(1); def calculateAcceleration(self, force): self.accelearation = [force[1]/self.mass, force[0]/self.mass]; def deltaPosition(self,force, time): calculateAcceleration(force); deltaX = deltaPosition1D(self.acceleration(0),self.velocity(0), time); deltaY = deltaPosition1D(self.acceleration(1),self.velocity(1), time); return [deltaX, deltaY]; def deltaPositon1D(self,accel,vel,time): return (vel*time + .5*accel*time**2); def update(self, force, time): deltaPos = self.deltaPosition(force, time); self.translate(deltaPos); class planet(body): def __init__(mass, radius, position, velocity, color): super(planet,self).__init__(mass, radius, position, velocity, color); """--------------------------------dependantBody, rocketBody, thruster----------------------------------""" class dependantBody(Drawable): def __init__(mass, radius, position, color): self.mass = mass; self.radius = radius; self.position = position; self.color = color; def draw(self, screen): pygame.draw.circle(screen, self.color, self.position, self.radius, 0); def translate(self, deltaPosition): self.position(0) += deltaPosition(0); self.position(1) += deltaPosition(1); class rocketBody(dependantBody): def __init__(mass, radius, position, color = (72,209,204)): super(rocketBody,self).__init__( mass, radius, position, color); class thruster(dependantBody): def __init__(self, radius, position, color = (255,54,54)): super(rocketBody,self).__init__( mass, radius, position, color); def fire(self): return 123; #kJ of potential energy spent by emiting one fart of liquid hydrogen """--------------------------------thrusterSet----------------------------------""" class thrusterSet(): def __init__(mass,radius, positions): self.mass = mass; self.thrusterList = []; for position in positions: self.thrusterList.append(thruster(mass, radius, position)) def fireThruster(self,index): energyFired = self.thrusterList[index].fire(); direction = [0,0]; if (index == 0): direction = [0 , 1]; elif(index == 1): direction = [-1 , 0]; elif(index == 2 ): direction = [0 , -1]; elif(index == 3): direction = [1 , 0]; return [direction, energyFired]; def translate(self, deltaPosition): for thruster in self.thrusterList: thruster.translate(deltaPosition); def draw(self,screen): for thruster in self.thrusterList: thruster.draw(screen); """--------------------------------Rocket----------------------------------""" class rocket(): def __init__(bMass, bRadius, bPosition, tmass, tradius, velocity): self.body = rocketBody(bMass, bRadius, bPosition, velocity); x = bPosition(0); y = bPosition(1); self.acceleration = [0,0] self.thrusters = thrusterSet(tmass, tradius, (x,y-bRadius), (x+bRadius,y),(x,y+bRadius),(x-bRadius,y)); def fireThruster(self, index): poof = self.thruster.fireThruster(index); energy = poof[1]; directinon = poof[0]; force = energy/self.body.radius; directionalForce = [force*direction[0], force*direction[1]]; return directionalForce; def calculateAcceleration(self, force): mass = bMass + self.thrusters.mass; self.acceleration = [force[0]/mass, force[1]/mass]; return self.acceleration; def deltaPosition(self,force, time): self.calculateAcceleration(force); deltaX = deltaPosition1D(self.acceleration(0),self.velocity(0), time); deltaY = deltaPosition1D(self.acceleration(1),self.velocity(1), time); return [deltaX, deltaY]; def deltaPositon1D(self,accel,vel,time): return (vel*time + .5*accel*time**2); def translate(self,deltaPosition): self.body.translate(deltaPosition); self.thrusters.translate(deltaPosition); def update(self, force, time): deltaPos = self.deltaPosition(force, time); self.translate(deltaPos); def draw(self, screen): self.body.draw(screen); self.thrusters.draw(screen); class model(): def __init__(rbMass, rbRadius, position, tmass, tradius): self.planentsList = [] self.myRocket = rocket(rbMass, rbRadius, position, tmass, tradius, [0,0]); self.generatePlanets(1); def generatePlanets(self,numPlanets): pass def update(self, planetForces, rocketForce, time): for i in range(len(planetForces)): self.planetsList[i].update(planetForces[i], time); self.rocket.update(rocketForce, time); def fireRocket(self, index): self.myRocket.fireThruster(index); def objectsInWorld(self): return [self.myRocket, self.planentsList]; def draw(self,screen): for planet in self.planetList: planet.draw(screen); self.myRocket.draw(screen); """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ View """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ class view(): def __init__(self,model,screen): self.model = model self.screen = screen def draweverything(self): self.model.draw(self.screen); """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ Keybord Controller """ """ """ """ """ """ """ """ """ """ """ """ """ """ """ class keyboardController: def __init__(self): self.model = model def handle_keyboard_event(self,event): if event.type != KEYDOWN: return if event.key == K_UP: self.model.fireRocket(0) if event.key == K_RIGHT: self.model.fireRocket(1) if event.key == K_DOWN: self.model.fireRocket(2) if event.key == K_LEFT: self.model.fireRocket(3)
# object interaction class Player(object): """ Player """ def blast(self, enemy): print("The player blasts an enemy.\n") enemy.die() class Alien(object): """ Alien """ def die(self): print("Ugh! ...") #main print("\tAlien death") hero = Player() invader = Alien() hero.blast(invader) input("exit")
# create own functions def instructions(): """Display game instructions""" print( """ Prepare yourself. I am the master of Noughts and Crosses Though you may try, you will be no match for me. To make a move you should enter a number: 0 - 8 The number corresponds to a board position below: 0 | 1 | 2 --------- 3 | 4 | 5 --------- 6 | 7 | 8 \n """ ) # Main instructions() input("\nexit")
# loop with a string word = input("Enter a word: ") print("\nHere is each letter: ") for letter in word: print(letter) number = input("Enter a number: ") print("\nHere is each number: ") for integer in number: print(integer) input("\nexit")
# constants X = "X" O = "O" EMPTY = " " TIE = "TIE" NUM_SQUARES = 9 # instructions def display_instruct(): """Display game instructions""" print( """ 'Prepare yourself. I am the master of Noughts and Crosses Though you may try, you will be no match for me.' To make a move you should enter a number: 0 - 8 The number corresponds to a board position below: 0 | 1 | 2 --------- 3 | 4 | 5 --------- 6 | 7 | 8 \n """ ) # functions def ask_yes_no(question): """Ask a Y/N Question""" response = None while response not in ("y", "n"): response = input(question).lower() return response def ask_number(question, low, high): """Ask for a number 0-8""" response = None while response not in range(0, 9): response = int(input(question)) return response def pieces(): """player or comp first""" go_first = ask_yes_no("Would you like to go first? (y/n): ") if go_first == "y": print("\nYou are 'X' Take the first move") human = X computer = O else: print("\nI am 'X'. I will go first") computer = X human = O return computer, human def new_board(): """create new board""" board = [] for square in range(NUM_SQUARES): board.append(EMPTY) return board def display_board(board): """display board""" print("\n\t", board[0], "|", board[1], "|", board[2]) print("\t", "---------") print("\t", board[3], "|", board[4], "|", board[5]) print("\t", "---------") print("\t", board[6], "|", board[7], "|", board[8], "\n") def legal_moves(board): """legal moves""" moves = [] for square in range(NUM_SQUARES): if board[square] == EMPTY: moves.append(square) return moves def winner(board): """determine winner""" WAYS_TO_WIN = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) for row in WAYS_TO_WIN: if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY: winner = board[row[0]] return winner if EMPTY not in board: return TIE return None def human_move(board, human): """ human move """ legal = legal_moves(board) move = None while move not in legal: move = ask_number("\nWhere would you like to go? (0 - 8): ", O, NUM_SQUARES) if move not in legal: print("That square is already occupied\n") print("OK") return move def computer_move(board, computer, human): """computer move""" #making a copy to work with board = board[:] # AI BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7) print("I will take square", end=" ") # winning move for move in legal_moves(board): board[move] = computer if winner(board) == computer: print(move) return move board[move] = EMPTY for move in legal_moves(board): board[move] = human if winner(board) == human: print(move) return move board[move] = EMPTY for move in BEST_MOVES: if move in legal_moves(board): print(move) return move # next turn def next_turn(turn): """Switch turns""" if turn == X: return O else: return X # congrats def congrat_winner(the_winner, computer, human): """ Congrats to winner """ if the_winner != TIE: print(the_winner, "won!\n") else: print("It's a tie\n") if the_winner == computer: print("I knew I would beat you all along") elif the_winner == human: print("I can't believe you beat me!") elif the_winner == TIE: print("You were very lucky. Next time I will win!") # main def main(): display_instruct() computer, human = pieces() turn = X board = new_board() while not winner(board): if turn == human: move = human_move(board, human) board[move] = human else: move = computer_move(board, computer, human) board[move] = computer display_board(board) turn = next_turn(turn) the_winner = winner(board) congrat_winner(the_winner, computer, human) # start main() input("\nPress enter to exit")
"""#a is a variale that contain value. a = "Hello world" #print a print(a)""" # hello world using class class Myclass(object):#object is optional def show(self):#self is a variable. print("Hello world") #x is object x = Myclass() x.show()
# COMP9021 19T3 - Rachid Hamadi # Quiz 3 *** Due Thursday Week 4 # Reading the number written in base 8 from right to left, # keeping the leading 0's, if any: # 0: move N 1: move NE 2: move E 3: move SE # 4: move S 5: move SW 6: move W 7: move NW # # We start from a position that is the unique position # where the switch is on. # # Moving to a position switches on to off, off to on there. import sys from collections import defaultdict on = '\u26aa' off = '\u26ab' code = input('Enter a non-strictly negative integer: ').strip() try: if code[0] == '-': raise ValueError int(code) except ValueError: print('Incorrect input, giving up.') sys.exit() nb_of_leading_zeroes = 0 for i in range(len(code) - 1): if code[i] == '0': nb_of_leading_zeroes += 1 else: break print("Keeping leading 0's, if any, in base 8,", code, 'reads as', '0' * nb_of_leading_zeroes + f'{int(code):o}.' ) print() # INSERT YOUR CODE HERE octal_number = '0' * nb_of_leading_zeroes + f'{int(code):o}' matrix = defaultdict(int) switch = {0: off,1: on} def flip_switch(points): matrix[points] = 0 ** matrix[points] p = (0, 0) flip_switch(p) steps = {0: lambda coordinate: (coordinate[0], coordinate[1]+1), 1: lambda coordinate: (coordinate[0]+1, coordinate[1]+1), 2: lambda coordinate: (coordinate[0]+1, coordinate[1]), 3: lambda coordinate: (coordinate[0]+1, coordinate[1]-1), 4: lambda coordinate: (coordinate[0], coordinate[1]-1), 5: lambda coordinate: (coordinate[0]-1, coordinate[1]-1), 6: lambda coordinate: (coordinate[0]-1, coordinate[1]), 7: lambda coordinate: (coordinate[0]-1, coordinate[1]+1) } for i in reversed(octal_number): p = steps[int(i)](p) flip_switch(p) row = sorted((i[0][0] for i in matrix.items() if i[1] == 1)) column = sorted((i[0][1] for i in matrix.items() if i[1] == 1)) if len(column) != 0 and len(row) != 0: top_most, bottom_most = column[len(column) -1], column[0] left_most, right_most = row[0], row[len(row) -1] for y in range(top_most,bottom_most-1,-1): for x in range(left_most, right_most+1): print(switch[matrix[(x, y)]], end = ' ') print(end = '\n')
class Employee: company = "vinsys" def __init__(self):#superficial constructor print("I was initialized....") print(self) def __del__(self):#superficial destructor print("Destructor called") def calculatetax(self): print ("calculating tax") #def checkpasswd(self): # if self.username == "Abhishek": # print("You got this") def __str__(self): return "In python training" emp = Employee() emp.calculatetax() print(emp.company) #inheritance in python class Manager(Employee): def __init__(self): super().__init__() print("Manager") Manager() #emp.checkpasswd()
#! /usr/bin/python from datetime import datetime, timedelta import datetime import calendar #comments # print on console print "Hello Wolrd" # if elif else # conditinoal statment a = "HELLO" if a == "hello": print "a has lowercase" print a elif a == "HELLO": print "a has all caps" else : print "bad bad bad" #loop cnt = 0 while (cnt < 5): print "value is %d" % cnt cnt = cnt + 1 #function def msg( var ): print "this is func msg" #loops on string, list for l in var: print "letter is: ", l def list_print(li): for l in li: print "val is: ", l msg( "helllo") #list examples alphabets = [ "a", "b", "c", "d"] msg(alphabets) print "alphabets have abcd" list_print(alphabets) print "alphabets delete b" del alphabets[1] list_print(alphabets) print "alphabets add 'e' && over writting at index one" alphabets[1] = 'z' alphabets.append("e") list_print(alphabets) #tupple examples t = ("t1", "t2", "t3") print("Tupples is") list_print(t) a = "HELLO" b = "WORLD" ka = "test '%s' '%s' example" t = ka % (a , b) print t #dictonary examples dict_dict = { 1: {"name" : "Khader", "age" : 30, "height": 6}, 2: {"name" : "Basha", "age" : 32, "height": 2} } print dict_dict for key, value in dict_dict.iteritems() : print value d = {} cnt = 1 while (cnt < 5): y = datetime.date.fromordinal(datetime.date.today().toordinal()-cnt).strftime("%F") d[y] = cnt * 10; cnt = cnt + 1 print d cnt = "hello" if type(cnt) is int: print "cnt is integer" else: print "not integer" month = [1, 2, 3, 4] if type(month) == list: print "$$$$$$$$$$$$$$ LIST LIST LIST $$$$$$$$$$$$$$$$" for i in month: start_date = ("%s-%s-%s" %(year, str(i), "01")) print calendar.monthrange(2012, i)
#decorators takes a function (as a funciton argument) and add soem "decoration" then return it # decorating functions/outermost function, accecpts function pointer(first class function) as an argument # This first class function will be used in inner functions and invoked from this inner function #But in closures, both innner & outer functinos will have same argument list(strings as example) # Then this inner function will use that outermost func arguments(strings as example) # Common things in closure & decorators: # @ both have nested functions # @ both retunrs inner most functions def make_pretty(func): def inner(): print("I am decorated in 'inner'") func() return inner def ordinary(): print("I am ordinary") f = make_pretty(ordinary) f()
#!/usr/bin/python from math import sqrt for n in range(80, 5, -1): root = sqrt(n) if root == int(root): print n break else: print "Didn't find it!"
# -*- coding: UTF-8 -*- # filename: menushow.py # verson 1.0 # 2016.10.24 by HanPengfei def menushow(fathermenu, menucount = 1): """ This is a module that provides the display menu, you shoule give me the fathermenu'name and menucount, or default menucount is 1 """ index = 0 max_count = int(menucount) while index <= max_count: for son_menu in fathermenu.keys(): print son_menu if index == max_count: break son_menu = raw_input ('Next: ').lower() if fathermenu.has_key(son_menu): fathermenu = fathermenu[son_menu] else: break index += 1
import random pickList = [] randomNum = random.randint(1,46) userInput = int((input("How many picks:"))) while True: for i in range(userInput): pickList.append(randomNum) if randomNum not in pickList: continue else: pickList.append(randomNum) break print("{:2d}, {:2d}, {:2d}, {:2d}, {:2d}, {:2d}".format(pickList[0]),(pickList[1]),(pickList[2]),(pickList[3]), (pickList[4]),(pickList[5]))
# # Queue implementation with 2 Stacks # A queue is a list where items are added and # removed from opposite sites # # A queue implements following operations: # # add(item): Add an item to the end of the list # remove(): Remove the first item in the list # peek(): Return top of the queue # isEmpty(): Return true iff the queue is empty class MyQueue: # This stack stores the new incoming values stack_newest = [] # This stack has the popped values from the newest stack. # The elements are in the order of a FIFO Queue ready to be dequeued. stack_oldest = [] # This function pushes the contents of stack1 to stack2 # therefore reversing the order. def push_elements_to_stack(self, stack_newest, stack_oldest): while stack_newest: stack_oldest.append(stack_newest.pop()) # Append the item at the end of the list def add(self, item): self.stack_newest.append(item) # Lazy approach: # If the stack_oldest still has elements that means that these elements # need to be removed and dequeued first. # If this stack is empty then we need to push all the elements from # newest_stack to the oldest_stack to reverse the order and have # the oldest one at the top of the stack. def remove(self): # If the second stack has items, those need to be retrieved first # since they are the first one in the queue if self.stack_oldest: return self.stack_oldest.pop() # Both stacks are empty if not self.stack_newest: return -1 self.push_elements_to_stack(self.stack_newest, self.stack_oldest) return self.stack_oldest.pop() # Similar to remove but we need to push the element on the oldest_stack again. def peek(self): if not self.stack_oldest: self.push_elements_to_stack(self.stack_newest, self.stack_oldest) elem = self.stack_oldest.pop() self.stack_oldest.append(elem) return elem # Queue is empty iff both stacks are empty. def isEmpty(self): return not self.stack_oldest and not self.stack_newest myQueue = MyQueue() myQueue.add(3) myQueue.add(2) myQueue.add(6) myQueue.add(1) print(myQueue.remove()) print(myQueue.remove()) myQueue.add(10) print(myQueue.remove()) myQueue.add(12) myQueue.add(20) print(myQueue.remove()) print(myQueue.remove()) print(myQueue.remove()) print(myQueue.remove())
''' Exemplos While Rafael Alves 05/04/2021 - Senai - Jaguariúna - SP ''' ''' n = 5 while n > 0: if n > 1: print('Fail error: n maior que 1') else: print('Fail error: n menor que 1') print(n) n -= 1 print('fogo!') ''' ''' a = 1 b = 1000 while a!=b: print('Rafael: '+str(a)) a +=1 print("a = ",a) print("b = ",b) ''' ''' num = float(input("Informe um número:")) n = 1 while n<=5: print(n) if(num == n): break elif n == 3: break else: print("Ainda não parou o laço") n += 1 print('Fim!') ''' ''' segundos = 960 minutos = segundos / 60 while minutos > 6: print('Ainta faltam mais de 6 minutos, tempo atual:'+ str(minutos)) minutos-=1 if minutos < 7: break ''' ''' entrada = 0 while entrada != -1: entrada = eval(input('Digite a hora de entrada:')) if(entrada!= -1 and entrada < 7.25): print('Você bateu o cartão antes do horário, fale com o Paraguassu!') print('A casa caiu!') break elif entrada > 7.35: print('Você bateu o cartão depois do horário, fale com o Paraguassu!') print('A casa caiu, vai ter desconto na folha!') break elif( entrada !=-1): print('Vai para a sala de aula') ''' ''' num = float(input("Informe um número:")) while num > 0: num = num - 1 if num % 2 != 0: # Se é ímpar continue print(num) # Caso seja par print("Fim") ''' ''' num = float(input("Informe um número:")) while num > 0: num = num - 1 if num % 2 != 0: # Se é ímpar continue print(num) # Caso seja par print("Fim") ''' n = 0 bomba = 7 # Valor para acertar while n < 3: # Número de tentativas num = int(input('Informe um número inteiro')) n = n + 1 if num == bomba: # O usário acertou o bomba print("Parabéns, você acertou após", n, "tentativas") break # Ao executar o break não entra no else else: # Entra caso o usuário não acertou o bomba print("Não foi dessa vez") print("Fim!")
''' Exemplos String Rafael Alves 05/04/2021 - Senai - Jaguariúna - SP ''' #print('SENAI' == 'ETEC') #print('SENAI' > 'ETEC') #print('SENAI' != 'SENAI') # Concatenar #print('SENAI'+'Jaguariúna\t'+'SP') #print('SENAI\n'*4) #Indexação #varStr = "Jaguariúna" #print(varStr[3] + ' - '+ varStr[-7]) ''' num = 30563 num = str(num) print(str(len(num))+' - '+str(num.count('3'))) ''' ''' nome = "Roberto Pereira Dias Rob" subStr = "Rob" newSubstr = "Rafa" print(nome.replace(subStr,newSubstr)) ''' a = 'nada' b = 'eu' c = print(f'{a}, - ,{b}')
import numpy # Matrix Transpose m = numpy.mat([[1, 2], [3, 4], [5, 6]]) print("Original matrix\n", m) print("Transposed matrix:\n", m.T)
#! /usr/bin/python # A program to count the lines of a python program # mcb3k with help from alm4x 4.2.2k11 v0.6 # Goal: by v1.0, count all logic lines, or all phys. lines, user's choice def physLineCounter(pyScript): """takes a python script and returns a list of physical lines of code, including all the comments.""" scriptName = pyScript script = open(scriptName) #opens the file for the pyScript scriptList = script.readlines() #this splits the entire file into a list of strings. numberOfLines = len(scriptList) script.close() return [numberOfLines] # end of the function def logicalLineCounter(pyScript): """Takes a python script and returns the number of logical lines of code, the number of comments, and the number of physical lines of code in a list.""" #Lets do open up the file, push it into a list, and close the file scriptName = pyScript script = open(scriptName) scriptList = script.readlines() scipt.close() lineCount = len(scriptList) #set lineCount to the length physical lines commentCount = 0 for each in scriptList: if not 0 == scriptList[each].count(';') lineCount = lineCount + scriptList[each].count(';') #if the physical line contains a semicolon, i.e. contains multiple statements. if scriptList[each].endswith(';') == True lineCount = lineCount - 1 #because it's already been counted, right? if scriptList[each].startswith("#") == True lineCount = lineCount - 1 commentCount = commentCount + 1 #Count all lines that contain a '#'and add one to commentCount if scriptList[each].count('#') == True and scriptList[each].startswith("#") != True commentCount = commentCount + 1 return [lineCount, commentCount, len(scriptList)] #this is like the main function myPyScript = raw_input('Input file name: ') countType = raw_input('Physical or Logical lines: ') while countType.capitalize() != "Physical" or countType.capitalize() != "Logical" if countType.capitalize() == "Physical" tallies = physLineCounter(myPyScript) elif countType.capitalize() == "Logical" tallies = logicalLineCounter(myPyScript) else print "That wasn't a valid input!" for each in tallies print tallies[each]
list_one = [-423, 'Eye', 'sigh', 'Profession', 'Go', 'occupy', -51, 21, -345, 74, 'undertake', 'tiptoe', 11, -475, 'swipe', 'Burial', 280, 343, 218, 'general'] list_two = ['Conductor', -494, 'Difficulty', -234, -325, -466, 'loot', 457, 'blast', 'equal', -387, 'Bless', 'Candle', 'extinct', 495, 'Restless', 220, 'extinct', 'copyright', 'Bend'] list_three = ['Inject', 407, 'bless', 39, 'identification', -6, 'Adult', 172, 'difficulty', -279, 'Censorship', 163, 'tiptoe', 407, 'Inject', 59, 'Eye', 19, 'Candle', 193] list_of_lists = [['forest', 'Hypothesize', 135], [495, 'foreigner', 'Eye'], [141, 301, 'hope'], [383, 'Adult', 'difficulty'], [-403, 'General', 'Fixture'], ['Clock', 'management']] new_list = [] i = 0 for i in range(len(list_one)): new_list.append(list_one[i]) new_list.append(list_two[i]) i += 1 print(new_list) odd_list = [] even_list = [] for j in range(0, len(list_three), 2): odd_list.append(list_three[j]) even_list.append(list_three[j + 1]) print(odd_list) print(even_list) int_list = [] for k in range(len(list_one)): try: int_list.append(int(list_one[k])) except ValueError: continue print(int_list) items_of_all_list = [] for l in range(len(list_of_lists)): for m in range(len(list_of_lists[l])): items_of_all_list.append(list_of_lists[l][m]) print(items_of_all_list)
""" Program is driven by a menu that allows users the ability to add/delete items based on calendar events The events will be sortable by date """ import json from datetime import datetime running = True def menu(): # Choose Number print(""" -==Menu==- 1.) Create 2.) Delete 3.) Search 4.) Display 5.) Quit """) def get_choice(): choice = raw_input('>>') return choice class Item(): def __init__(self): self.c_message = """ To Create an Item enter all relevant information. This should include a <<Title>>, a <<Body>>, and a <<Priority Level>> """ self.file_path = 'files/intermediate_1_save.json' def create_item(self): print(self.c_message) # New Item n_item = {} n_item['title'] = raw_input('Title: ') n_item['body'] = raw_input('Body: ') n_item['priority'] = raw_input('Priority: ') n_item['tags'] = raw_input('Tags: ') # Get Datetime after writing d_time = datetime.now() # Formatted Date and Time f_date = d_time.strftime("%d/%m/%y") f_time = d_time.strftime("%I:%M") # Store Date/Time as separate entities so we can use # split() on them when we are searching n_item['date'] = f_date n_item['time'] = f_time #print(item) with open(self.file_path, 'r+') as f: # Read Old Data data = json.loads(f.read()) n_item['id'] = len(data) data.append(n_item) save_data = json.dumps(data) # Rewind file for writing f.seek(0) f.truncate() f.write("{0}\n".format(save_data)) # Confirmation print("Item Created") def show(self): with open(self.file_path, 'r') as f: item_list = json.loads(f.read()) print( """ ID | Title | Body | Tags | Date """ ) for i in item_list: print(" {5:3} | {0:13} | {1:13} | {2:13} | {3} {4}".format(i["title"], i["body"][:13], i["tags"][:13], i["date"], i["time"], str(i["id"])[:3])) def search(self): term = raw_input("Query: ") with open(self.file_path, 'r') as f: data = f.read() item_data = json.loads(data) for i in item_data: item_id = i["id"] title = i["title"] body = i["body"] if term.lower() in title.lower() or term.lower() in body.lower(): print( """ ID: {0} Title: {1} Body: {2}""".format(item_id, title, body)) def delete(self): print("Enter Id of the item you with to delete") select = int(raw_input('>>')) with open(self.file_path, 'r+') as f: data = f.read() item_data = json.loads(data) for i, v in enumerate(item_data): if v["id"] == select: del item_data[i] # Confirmation print("Deleted Successfully") data_save = json.dumps(item_data) # Rewind file for writing f.seek(0) f.truncate() f.write(data_save) def check_file(self): f = open(self.file_path, 'r+') r_file = f.read() if len(r_file) <= 2: # Rewind file for writing f.seek(0) f.truncate() f.write("[]") f.close() else: pass item = Item() item.check_file() # 1.) Create # 2.) Delete # 3.) Search # 4.) Display # 5.) Quit menu() choice = get_choice() while running: if '1' in choice: item.create_item() choice = get_choice() elif '2' in choice: item.delete() choice = get_choice() elif '3' in choice: item.search() choice = get_choice() elif '4' in choice: item.show() choice = get_choice() elif '5' in choice: print("Quitting") running = False elif 'h' in choice.lower(): menu() choice = get_choice()
def main(): #escribe tu código abajo de esta línea num=0 total=0 cantidad=0 while num>=0: num=float(input()) total=total+num cantidad+=1 else: total= (total-num)/(cantidad-1) print(total) if __name__=='__main__': main()
def adjacent(position): x, y = position return (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1) def explore(position, walls, keys, doors, gainedKeys, openedDoors): options = [] explored = {} queue = [(position, 0)] while len(queue) > 0: p, step = queue.pop() step += 1 for a in adjacent(p): if a in explored and explored[a] <= step: continue elif a in walls: continue explored[a] = step if a in keys and keys[a] not in gainedKeys: options.append((a, step, keys[a])) elif a in doors and doors[a] not in openedDoors: if doors[a].lower() in gainedKeys: options.append((a, step, doors[a])) else: queue.append((a, step)) return options globalCurrentBest = None def subsolve(position, walls, keys, doors, gainedKeys, openedDoors, step): global globalCurrentBest if globalCurrentBest is not None and step > globalCurrentBest: return [] if len(keys) == len(gainedKeys): if globalCurrentBest is None or step < globalCurrentBest: globalCurrentBest = step return [step] options = explore(position, walls, keys, doors, gainedKeys, openedDoors) solutions = [] for option in options: p, stepMod, type = option if type.isupper(): parts = subsolve(p, walls, keys, doors, gainedKeys, openedDoors + [type], step + stepMod) for part in parts: solutions.append(part) else: parts = subsolve(p, walls, keys, doors, gainedKeys + [type], openedDoors, step + stepMod) for part in parts: solutions.append(part) return solutions def solve(position, walls, keys, doors): gainedKeys = [] openendDoors = [] solutions = subsolve(position, walls, keys, doors, gainedKeys, openendDoors, 0) return min(solutions) def read(filename): keys = {} doors = {} walls = set() position = () with open(filename, 'r') as f: rows = [row.rstrip() for row in f.readlines()] for y, row in enumerate(rows): for x, c in enumerate(row): p = (x, y) if c == '.': continue elif c == '#': walls.add(p) elif c == '@': position = p elif c.isupper(): doors[p] = c else: keys[p] = c return position, walls, keys, doors def main(filename): position, walls, keys, doors = read(filename) print(solve(position, walls, keys, doors)) if __name__ == "__main__": import sys if (len(sys.argv) < 2): print('missing input parameter') exit() for f in sys.argv[1:]: main(f)
def main(): #f = open("textfile.txt", "w+") # create and write #f = open("textfile.txt", "a") #appends #for i in range(10): # f.write("Thia ia line " + str(i) + "\r\n") f = open("textfile.txt", "r") # reads file if f.mode == 'r': #contents = f.read() fl = f.readlines() #to add lines for x in fl: print(x) #print(contents) #f.close if __name__ == "__main__": main()
""" import matplotlib.pyplot as plt #%matplotlib inline # con esto solo es necesario imprimir y omites el show() gastos = [50,120,80,95] meses = ["enero", "febrero", "marzo", "Abril"] mapeo = range(len(meses)) plt.plot(gastos) plt.xticks(mapeo,meses) print(list(mapeo)) plt.show() # si no pones la clausula debes escribir .show() #eje x y Y x = [0,5,10,15] y = gastos plt.plot(x,y) # METODO QUE REPRESENTA DATOS EN PLANO CARTESIANO plt.show() #Grafico invertido plt.plot(y,x) plt.show() """ #COMPRENSION DE LISTAS #1 #metodo tradicional lista = [] for letra in "casa": lista.append(letra) #print(lista) #con compresion de listas lista = [letra for letra in "casa"] print(lista) #2 #metodo tradicional lista =[] for numero in range (0,11): lista.append(numero**2) pares =[] for numero in lista: if numero % 2 == 0: pares.append(numero) print(pares) #compresion de listas lista = [numero for numero in [numero**2 for numero in range(0,11)] if numero % 2 == 0] print(lista) #LIMITES xlim, ylim import matplotlib.pyplot as plt x = range(1,11) # numero del 1 al 10 y = [n**2 for n in x] # potencias de 2 del 1 al 10 print(y) plt.plot(x,y) #plt.xlim(-10,20) # zoom hacia afuera plt.xlim(len(x)-5, len(x)) # zoom hacia dentro plt.ylim(0,200) plt.show() #titulo y etiquetas x = range(1,11) y = [n**2 for n in x] plt.plot(x,y) plt.title("nombre") plt.xlabel("eje x") plt.ylabel("eje y") #como a;adir de una al plot el label de leyenda plt.plot(x,y, label ="a la 2") plt.title("potencias") plt.xlabel("numero") plt.ylabel("resultado") plt.legend() # con el parametro lo podemos establecer una posiicon del 0 al 10 (0 es por defecto, 10 es el centro)
try: seleccion =input("""\nMenu 1.Suma de dos numeros 2. Resta de dos numeros 3. Multiplicacion de los dos numeros seleccion: """) if seleccion == 1: num1 = int(input("Ingresa primer numero: ")) num2 = int(input("Ingresa segundo numero: ")) resultado = num1 + num2 print("\nEl valor de la suma es {}".format(resultado)) except Exception as e: print("\033[1;33m"+"ha ocurrido un error " +'\033[0;m', type(e).__name__)
""" while True: try: n = input("Introduce un numero: ") 5/n except Exception as e: print("ha ocurrido un error ", type(e).__name__) """ """ def mi_funcion(algo=None): try: if algo is None: raise ValueError("error no se permite un valor nulo") except ValueError: print("Error no se permite un valor nulo (desde la excepcion)") mi_funcion() while(True): try: n = float(input("Introduce un numero: ")) m=4 print("{}/{} = {}".format(n,m,n/m)) except: print("ha ocurrido un error") else: print("todo fucionando correctamente") break finally: print("fin de la interaccion ") """ while(True): try: numero = int(input("Ingrese un numero: ")) resultado = 10/numero print(resultado) except Exception as e: print("ha ocurrido un error ", type(e).__name__) #finally: """ while (True): lista = [] lista = list(input('Ingrese una lista: ')) contador =0 print(lista) for n,m in enumerate(lista): contador= contador+1 print("\x1b[1;33m"+"{}.-Valor de indice: {} y valor del indice {}".format(contador,n,m)) try: seleccion = int(input(("cual deseas sacar?: "))) valor = lista[seleccion-1] print("valor es: {}".format(valor)) except IndexError: print("No existe el indice ") except ValueError: print("Valor erroneo") #except TypeError: # print("Tipo de error") except Exception as e: print("ha ocurrido un error ", type(e).__name__) """
""" #ARCHIVOS PLANOS #1 READLINE() from io import open fichero= open('fichero.txt','r') texto = fichero.readlines() fichero.close() print(texto) #2 WITH DE MANERA AUTOMATICA, with open ("fichero.txt","r") as fichero: for linea in fichero: print(linea) #APPEND fichero = open('fichero.txt', "a") fichero.write('\n otra linea') fichero.close() #METODO SEEK(), PUNTERO EN EL FICHERO no retorna nada fichero = open("fichero.txt","r") fichero.seek(0) #puntero al inicio fichero.seek(10) # leemos los 10 caracteres """ """ texto = "una linea de texto \notra linea con texto" fichero=open('fichero.xml','w') fichero.write(texto) fichero.close() """ fichero = open("texto.txt","w") texto = "hola" fichero.write(texto) fichero.close
print("-----F L A M E S-----") name1 = input('Enter your name: ').lower().replace(" ","").replace(".","") name2 = input('Enter your partner\'s name: ').lower().replace(" ","").replace(".","") def flames(name1, name2): n1 = sum(letter in name2 for letter in name1) n2 = sum(letter in name1 for letter in name2) results = ["FRIENDS", "LOVE", "ACQUAINTANCES", "MARRIAGE", "ENEMY", "SIBLINGS"] print(name1, "---->", n1, " = " , results[n1%len(results)-1]) print(name2, "---->", n2, " = " , results[n2%len(results)-1]) counter = n1 + n2 print("Total: ",n1," + ",n2," = ",counter) index = counter % len(results) - 1 return results[index] print('Your Relationship is', flames(name1, name2))
# Import the pygame library import pygame import math # Initialize the game engine pygame.init() # Colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # Dimensions dimensions = (700, 500) screen = pygame.display.set_mode(dimensions) # Window title pygame.display.set_caption("Kath learning pygame") # Iterate until the user clicks on the close button. close_window = False # It is used to manage how quickly the screen is updated clock = pygame.time.Clock() # ---------- Main Loop of the Program ---------- while not close_window: for event in pygame.event.get(): if event.type == pygame.QUIT: close_window = True # Cleare the screen screen.fill(WHITE) for i in range(200): radianes_x = i / 20 radianes_y = i / 6 x = int(75 * math.sin(radianes_x)) + 200 y = int(75 * math.cos(radianes_y)) + 200 pygame.draw.line(screen, RED, [x, y], [x + 5, y], 5) for desplazamiento_x in range(30, 300, 30): pygame.draw.line(screen, GREEN, [desplazamiento_x, 100], [desplazamiento_x - 10, 90], 2) pygame.draw.line(screen, BLACK, [desplazamiento_x, 90], [desplazamiento_x - 10, 100], 2) # Update the screen pygame.display.flip() # Limited to 20 frames per second clock.tick(20) # Close the program pygame.quit()
# coding: utf-8 # # 4.1 선형대수 # In[1]: height_weight_age = [70,170,40] grades = [95,80,75,62] # In[4]: def vector_add(v,w): return [v_i + w_i for v_i,w_i in zip(v,w)] def vector_subtract(v,w): return [v_i - w_i for v_i,w_i in zip(v,w)] # In[7]: def vector_sum(vectors): result = vecotrs[0] for vector in vectors[1:]: result = vector_add(result,vector) return result def vector_sum(vectors): return reduce(vector_add,vectors) vector_sum = partial(reduce,vector_add) # reduce의 개념 #partial # In[8]: def scalar_multiply(c,v): return [ c * v_i in v] # In[9]: def vector_mean(vectors): n= len(vectors) return scalar_multiply(1/n,vector_sum(vectors)) # In[10]: def dot(v,w): return sum(v_i * w_i for v_i, w_i in zip(v,w)) # In[11]: def sum_of_squares(v): return dot(v,v) #내적의 개념? # In[12]: import math def magnitude(v): return math.sqrt(sum_of_squares(v)) # In[13]: def squared_distance(v,w): return sum_of_squares(vector_subtract(v,w)) def distance(v,w): return math.sqrt(squared_distance(v,w)) def distance(v,w): return magnitude(vector_subtract(v,w)) # # 4.2 행렬 # In[14]: #2개의 행(row)과 3개의 열(column)로 이루어져 있다. A = [[1,2,3],[4,5,6]] #3개의 행(row)과 2개의 열(column)로 이루어져 있다. B = [[1,2],[3,4],[5,6]] # In[15]: def shape(A): num_rows = len(A) num_columns = len(A[0]) if A else 0 return num_rows, num_columns # In[18]: def get_row(A,i): return A[i] def get_column(A,j): return [A_i[j] for A_i in A] # In[26]: def make_matrix(num_rows,num_cols,entry_fn): return [[entry_fn(i,j) for j in range(num_cols)] for i in range(num_rows)] # In[27]: def is_diagonal(i,j): return 1 if i==j else 0 # In[28]: identity_matrix = make_matrix(5,5,is_diagonal) # In[29]: identity_matrix # # 4.3 더 공부해 보고 싶다면 # - https://www.math.ucdavis.edu/~linear/ # - http://joshua.smcvt.edu/linearalgebra/ # - http://www.math.brown.edu/~treil/papers/LADW/LADW.html
from PIL import Image, ImageDraw name='' img = Image.new("RGB", (300, 1320)) img1 = ImageDraw.Draw(img) pos=(0,0) def printTable(table,iteration): global name # img = Image.new("RGB", (1500, 330)) # img1 = ImageDraw.Draw(img) global img1 global pos img1.rectangle([pos,(pos[0]+300,pos[1]+30)],fill='white') pos=(pos[0],pos[1]+30) img1.text((pos[0],pos[1]-15),"function: "+str(name)+" iterations: "+str(iteration),fill='black') print(name) for row in table: for element in row: if(len(str(element))==1): print('',element,end=' ') else: print(element,end=' ') if element=='*': img1.rectangle([pos,(pos[0]+300/len(table),pos[1]+300/len(table))], fill ="red", outline ="black") elif element==-1: img1.rectangle([pos,(pos[0]+300/len(table),pos[1]+300/len(table))], fill ="white", outline ="black") else: img1.rectangle([pos,(pos[0]+300/len(table),pos[1]+300/len(table))], fill ="yellow", outline ="black") img1.text((pos[0]+150/len(table),pos[1]+150/len(table)),str(element),fill="black") pos=(pos[0]+300/len(table),pos[1]) print() pos=(0,pos[1]+300/len(table)) # img.show() def update_name(n): global name name=n def show_image(): global img img.show()
def func(a): print (a+2) return a+2 x=1 print(x+1) y=str(x)+'1' print(y)