text
stringlengths
37
1.41M
number = None while number is None: try: userinput = input("Enter an integer number: ") number = int(userinput) except: print() print("Error: ") print("Please try again") print() else: print("You entered the valid number: ", number)
print(type(1)) # <type 'int'> print(type(1.)) # <type 'float'> print(type(1+3j)) # <type 'complex'> print(type("hello")) # <type 'str'> print(type([1,2,3])) # <type 'list'> # mutable print(type((1,2,3))) # <type 'tuple'> # immutable print(type({"name": "pat", "age": 12})) # <type 'dict'> # use is_instance to check the type, they will give a bool print(isinstance(1, int)) # True print(isinstance(1, float)) # False print(isinstance(1, str)) # False
# write a list with the ingredients salad, orange, mango # choose one element of the list # and write it to a file called "fruit.txt" fruit_list = ["salad", "orange", "mango"] chosen_fruit = fruit_list[1] with open("fruit.txt", "w") as f: f.write(chosen_fruit)
print(str(1)) print(type(1)) eingabe_1 = "1" eingabe_2 = "2" print(3 + 4) print(eingabe_1 + eingabe_2) # concat print(int(eingabe_1) + int(eingabe_2)) print(float(eingabe_1) + float(eingabe_2)) resultat_1 = int(eingabe_1) + int(eingabe_2) resultat_2 = float(eingabe_1) + float(eingabe_2) print(resultat_1, resultat_2) print(resultat_1 == resultat_2) print(resultat_1 is resultat_2) print(1 is 1)
capitals = {"France": "Paris", "Iceland": "Reykjavik", "Denmark": "Copenhagen", "Litauen": "Vilnius", "Canada": "Ottawa", "Austria": "Wien"} print("Study the following list:") print() print(capitals.items()) # [('Canada', 'Ottawa'), ('\xc3\x96sterreich', 'Wien'), ('Iceland', 'Reykjavik'), ('France', 'Paris'), ('Denmark', 'Copenhagen'), ('Litauen', 'Vilnius')] print() # items gives a list of tuples for country_capital in capitals.items(): print(country_capital) print() print("="*40) print() # we can unpack in forloop for country, capital in capitals.items(): print(country, capital) print(("Franek","Bartnik"))
#print True #print False # conditionals small_number = 100.0 big_number = 100 print(small_number > big_number) # False print(small_number < big_number) # True print(small_number == big_number) # False print(small_number != big_number) # True print(small_number is big_number) # False print(small_number is not big_number) # True #print "small_number > big_number: ", small_number > big_number # -> False
# Write a loop, which asks for an input, # until you entered a valid operator # hint: # "+" in "+-/*" # "+" in ["*", "+", "-", "/"] print("+-" in "+-/*") # True print("+-" in ["*", "+", "-", "/"]) # False operation = None while operation not in ["*", "+", "-", "/"]: operation = input("Please enter one of the following: '*', '+', '-', '/'") else: print(f"Thank you, you entered: {operation}")
entry = input("Enter a number: ") my_number = float(entry) print("You entered {}".format(my_number)) print(type(my_number)) bigger_than_30 = my_number > 30 if bigger_than_30: print("You entered a high number") else: print("You entered a low number")
# create a new file called "my_library.py" # write the functions from the previous exercise in that library # import the file "my_library.py" # use one of the functions and print it's result # Hier eine andere Variante: import Class5_Python3.math_functions print(Class5_Python3.math_functions.digit_cutter(123.456789, 3)) # oder das gleiche mit "as" umgeschrieben: import Class5_Python3.math_functions as MF print(MF.digit_cutter(123.456789, 3))
# write a shopping list # list should have the elements: "bread", "butter", "soup" # loop over the list and print each element with a sentence: # "I want to eat ..." (... should be replaced with the element) shopping_list = ["bread", "butter", "soup"] for food in shopping_list: print(f"I want to eat {food}")
capitals = {"France": "Paris", "Iceland": "Reykjavik", "Denmark": "Copenhagen", "Lithuania": "Vilnius", "Canada": "Ottawa", "Austria": "Vienna"} print(capitals["Japan"]) # this will make an error, KeyError
# Use GeoPy package from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="bimaplus-geolocation") # Ask a user for the input of the address address = input("Enter City, Country (e.g. Ljubljana, Slovenia): ") print("Location address:", address) # Get the location of the address and print it out to screen location = geolocator.geocode(address) print("Latitude and Longitude of the entered address:") print(location.latitude, location.longitude)
# Segmentation can be done through a variety of different ways but the typical output is a binary image. # A binary image is something that has values of zero or one. # Essentially a one indicates the piece of the image that we want to use and a zero is everything else. # Binary images are a key component of many image processing algorithms. These are pure, non alias black and white images. import numpy as np import cv2 bw = cv2.imread('detect_blob.png', 0) height, width = bw.shape[0:2] cv2.imshow("Original BW", bw) binary = np.zeros([height, width, 1], 'uint8') thresh = 85 for row in range(0, height): for col in range(0, width): if bw[row][col] > thresh: binary[row][col] = 255 cv2.imshow("Slow Binary", binary) ret, thresh = cv2.threshold(bw, thresh, 255, cv2.THRESH_BINARY) cv2.imshow("CV Threshold", thresh) cv2.waitKey(0) cv2.destroyAllWindows()
a=int(input()) list=[] for i in str(a): list.append(int(i)) list.sort(reverse=True) for i in list: print(i,end='')
"""Manipulate numeric data similar to numpy `ulab` is a numpy-like module for micropython, meant to simplify and speed up common mathematical operations on arrays. The primary goal was to implement a small subset of numpy that might be useful in the context of a microcontroller. This means low-level data processing of linear (array) and two-dimensional (matrix) data. `ulab` is adapted from micropython-ulab, and the original project's documentation can be found at https://micropython-ulab.readthedocs.io/en/latest/ `ulab` is modeled after numpy, and aims to be a compatible subset where possible. Numpy's documentation can be found at https://docs.scipy.org/doc/numpy/index.html""" class array: """1- and 2- dimensional array""" def __init__(self, values, *, dtype=float): """:param sequence values: Sequence giving the initial content of the array. :param dtype: The type of array values, ``int8``, ``uint8``, ``int16``, ``uint16``, or ``float`` The `values` sequence can either be another ~ulab.array, sequence of numbers (in which case a 1-dimensional array is created), or a sequence where each subsequence has the same length (in which case a 2-dimensional array is created). Passing a ~ulab.array and a different dtype can be used to convert an array from one dtype to another. In many cases, it is more convenient to create an array from a function like `zeros` or `linspace`. `ulab.array` implements the buffer protocol, so it can be used in many places an `array.array` can be used.""" ... shape: tuple = ... """The size of the array, a tuple of length 1 or 2""" size: int = ... """The number of elements in the array""" itemsize: int = ... """The number of elements in the array""" def flatten(self, *, order='C'): """:param order: Whether to flatten by rows ('C') or columns ('F') Returns a new `ulab.array` object which is always 1 dimensional. If order is 'C' (the default", then the data is ordered in rows; If it is 'F', then the data is ordered in columns. "C" and "F" refer to the typical storage organization of the C and Fortran languages.""" ... def sort(self, *, axis=1): """:param axis: Whether to sort elements within rows (0), columns (1), or elements (None)""" ... def transpose(self): """Swap the rows and columns of a 2-dimensional array""" ... def __add__(self): """Adds corresponding elements of the two arrays, or adds a number to all elements of the array. If both arguments are arrays, their sizes must match.""" ... def __sub__(self): """Subtracts corresponding elements of the two arrays, or adds a number to all elements of the array. If both arguments are arrays, their sizes must match.""" ... def __mul__(self): """Multiplies corresponding elements of the two arrays, or multiplies all elements of the array by a number. If both arguments are arrays, their sizes must match.""" ... def __div__(self): """Multiplies corresponding elements of the two arrays, or divides all elements of the array by a number. If both arguments are arrays, their sizes must match.""" ... def __pow__(): """Computes the power (x**y) of corresponding elements of the the two arrays, or one number and one array. If both arguments are arrays, their sizes must match.""" ... def __getitem__(): """Retrieve an element of the array.""" ... def __setitem__(): """Set an element of the array.""" ... int8 = ... """Type code for signed integers in the range -128 .. 127 inclusive, like the 'b' typecode of `array.array`""" int16 = ... """Type code for signed integers in the range -32768 .. 32767 inclusive, like the 'h' typecode of `array.array`""" float = ... """Type code for floating point values, like the 'f' typecode of `array.array`""" uint8 = ... """Type code for unsigned integers in the range 0 .. 255 inclusive, like the 'H' typecode of `array.array`""" uint16 = ... """Type code for unsigned integers in the range 0 .. 65535 inclusive, like the 'h' typecode of `array.array`""" def ones(shape, *, dtype=float): """ .. param: shape Shape of the array, either an integer (for a 1-D array) or a tuple of 2 integers (for a 2-D array) .. param: dtype Type of values in the array Return a new array of the given shape with all elements set to 1.""" ... def zeros(shape, *, dtype): """ .. param: shape Shape of the array, either an integer (for a 1-D array) or a tuple of 2 integers (for a 2-D array) .. param: dtype Type of values in the array Return a new array of the given shape with all elements set to 0.""" ... def eye(size, *, dtype=float): """Return a new square array of size, with the diagonal elements set to 1 and the other elements set to 0.""" ... def linspace(start, stop, *, dtype=float, num=50, endpoint=True): """ .. param: start First value in the array .. param: stop Final value in the array .. param int: num Count of values in the array .. param: dtype Type of values in the array .. param bool: endpoint Whether the ``stop`` value is included. Note that even when endpoint=True, the exact ``stop`` value may not be included due to the inaccuracy of floating point arithmetic. Return a new 1-D array with ``num`` elements ranging from ``start`` to ``stop`` linearly.""" ...
"""Numerical and Statistical functions Most of these functions take an "axis" argument, which indicates whether to operate over the flattened array (None), rows (0), or columns (1).""" def argmax(array, *, axis=None): """Return the index of the maximum element of the 1D array""" ... def argmin(array, *, axis=None): """Return the index of the minimum element of the 1D array""" ... def argsort(array, *, axis=None): """Returns an array which gives indices into the input array from least to greatest.""" ... def diff(array, *, axis=1): """Return the numerical derivative of successive elements of the array, as an array. axis=None is not supported.""" ... def flip(array, *, axis=None): """Returns a new array that reverses the order of the elements along the given axis, or along all axes if axis is None.""" ... def max(array, *, axis=None): """Return the maximum element of the 1D array""" ... def mean(array, *, axis=None): """Return the mean element of the 1D array, as a number if axis is None, otherwise as an array.""" ... def min(array, *, axis=None): """Return the minimum element of the 1D array""" ... def roll(array, distance, *, axis=None): """Shift the content of a vector by the positions given as the second argument. If the ``axis`` keyword is supplied, the shift is applied to the given axis. The array is modified in place.""" ... def std(array, *, axis=None): """Return the standard deviation of the array, as a number if axis is None, otherwise as an array.""" ... def sum(array, *, axis=None): """Return the sum of the array, as a number if axis is None, otherwise as an array.""" ... def sort(array, *, axis=0): """Sort the array along the given axis, or along all axes if axis is None. The array is modified in place.""" ...
import matplotlib.pyplot as plt from sklearn import datasets,svm digits = datasets.load_digits() # loading the data clf = svm.SVC(gamma=0.0001,C=100) # tuning the model print(len(digits.data)) X,y = digits.data[:-1], digits.target[:-1] # getting ready with or input and target clf.fit(X,y) # fitting model print("Prediction :" , clf.predict([digits.data[-8]])) # making prediction plt.imshow(digits.images[-8],cmap=plt.cm.gray_r, interpolation="nearest") # getting an image of the predicted value plt.show() # showing the image
import Forca import Adivinhação print("="*50) print(f"{'Escolha o seu Jogo':^50}") print("="*50) while True: jogo = int(input(""" Escolha um dos jogos disponíveis : |1| Forca |2| Adivinhação Defina o jogo : """)) if (jogo == 1): print("\nIniciando jogo da Forca ...\n\n") Forca.jogar() elif (jogo == 2): print("\nIniciando jogo d Adivinhação ...\n\n") Adivinhação.jogar() c = input("Digite qualquer letra para continuar : ").strip() if bool(c): print("Reiniciando o jogo...") else: break
""" 2. Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, второй массив надо заполнить значениями 0, 3, 4, 5 (помните, что индексация начинается с нуля), т. к. именно в этих позициях первого массива стоят четные числа. """ import random even_index_list = [] list_numbers = [random.randint(0, 20) for _ in range(10)] # Генерируем список чисел print('Initial list of numbers:', list_numbers) for elem in enumerate(list_numbers): # Создаем пару (индекс, число из списка) if elem[1] % 2 == 0: # Проверяем четность. Если Да, то сохраняем индекс even_index_list.append(elem[0]) print('List of even number indices', even_index_list)
""" 3. Написать программу, которая обходит не взвешенный ориентированный граф без петель, в котором все вершины связаны, по алгоритму поиска в глубину (Depth-First Search). Примечания: a. граф должен храниться в виде списка смежности; b. генерация графа выполняется в отдельной функции, которая принимает на вход число вершин. """ from sys import setrecursionlimit setrecursionlimit(100000) def graph_build(n): """Функция генерирует описание заданного в условии графа размера "n" в виде списка смежности""" g = [[i for i in range(n) if i != j] for j in range(n)] return g def deep_search(graph, visited, way, visited_name, start=0): """Рекурсивный обход в глубину с заданной вершины (по умолчанию 0)""" visited[start] = True visited_name.append(start) for v in graph[start]: way.append(v) if not visited[v]: deep_search(graph, visited, way, visited_name, v) nv = int(input('Введите количество вершин:')) start = int(input('Введите начальную вершину:')) print(f'Граф с {nv} взаимосвязанными вершинами в виде списка смежности: \n', graph_build(nv)) is_visited = [False] * nv way = [] visited_name = [] graph = graph_build(nv) deep_search(graph, is_visited, way, visited_name, start) print('Пройденные вершины:', visited_name) print('Путь обхода графа:', way)
""" 1. Проанализировать скорость и сложность одного любого алгоритма из разработанных в рамках домашнего задания первых трех уроков. 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. """ import timeit import cProfile import random def do_it(list_numbers): max_value = list_numbers[0] min_value = list_numbers[0] min_pair = None max_pair = None # print('Initial list of numbers:', list_numbers) for elem in enumerate(list_numbers): # Создаем пару: (индекс, число из списка) if elem[1] <= min_value: # Проверяем значение на минимум. Если Да, то сохраняем пару: (индекс, значение) min_pair = elem min_value = elem[1] elif elem[1] >= max_value: # Проверяем значение на максимум. Если Да, то сохраняем пару: (индекс, значение) max_pair = elem max_value = elem[1] list_numbers[max_pair[0]] = min_pair[1] # Меняем максимальное значение на минимальное list_numbers[min_pair[0]] = max_pair[1] # Меняем минимальное значение на максимальное # print('Max number:', max_pair[1]) # print('Min number:', min_pair[1]) # print('Modified list of numbers', list_numbers) # Вывод уже измененного списка def start(): list_numbers = [random.randint(0, 20) for _ in range(10000)] # Генерируем список чисел do_it(list_numbers) # Ниже результаты профилирования алгоритма при помощи timeit и cProfile # cProfile.run('start()') при длинне списка 1000 """ 5490 function calls in 0.015 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.015 0.015 <string>:1(<module>) 1 0.000 0.000 0.000 0.000 les_4_task_1.py:12(do_it) 1 0.000 0.000 0.015 0.015 les_4_task_1.py:32(start) 1 0.001 0.001 0.015 0.015 les_4_task_1.py:33(<listcomp>) 1000 0.004 0.000 0.011 0.000 random.py:174(randrange) 1000 0.002 0.000 0.013 0.000 random.py:218(randint) 1000 0.005 0.000 0.008 0.000 random.py:224(_randbelow) 1 0.000 0.000 0.015 0.015 {built-in method builtins.exec} 1000 0.001 0.000 0.001 0.000 {method 'bit_length' of 'int' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1484 0.002 0.000 0.002 0.000 {method 'getrandbits' of '_random.Random' objects} """ # "les_4_task_1.start()" # 100 loops, best of 5: 2.47 msec per loop # cProfile.run('start()') при длинне списка 10000 """ 55193 function calls in 0.142 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.142 0.142 <string>:1(<module>) 1 0.003 0.003 0.003 0.003 les_4_task_1.py:12(do_it) 1 0.000 0.000 0.142 0.142 les_4_task_1.py:32(start) 1 0.015 0.015 0.139 0.139 les_4_task_1.py:33(<listcomp>) 10000 0.029 0.000 0.101 0.000 random.py:174(randrange) 10000 0.023 0.000 0.124 0.000 random.py:218(randint) 10000 0.045 0.000 0.073 0.000 random.py:224(_randbelow) 1 0.000 0.000 0.142 0.142 {built-in method builtins.exec} 10000 0.010 0.000 0.010 0.000 {method 'bit_length' of 'int' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 15187 0.017 0.000 0.017 0.000 {method 'getrandbits' of '_random.Random' objects} """ # "les_4_task_1.start()" # 100 loops, best of 5: 25.3 msec per loop # Вывод: сложность алгоритма линейная О(n)
import sys def count_trees(grid, dx, dy): x = 0 y = 0 trees = 0 max_x = len(grid[0]) while y < len(grid): if grid[y][x % max_x] == "#": trees += 1 x += dx y += dy return trees def part1(grid): return count_trees(grid, 3, 1) def part2(grid): product = 1 for dx, dy in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]: product *= count_trees(grid, dx, dy) return product def main(): grid = sys.stdin.read().strip().split("\n") print(part1(grid)) print(part2(grid)) if __name__ == "__main__": main()
import sys from collections import namedtuple ParsedLine = namedtuple("ParsedLine", ["l", "h", "letter", "pw"]) def part1(parsed_lines): return sum(p.l <= p.pw.count(p.letter) <= p.h for p in parsed_lines) def part2(parsed_lines): return sum( (p.pw[p.l - 1] == p.letter) ^ (p.pw[p.h - 1] == p.letter) for p in parsed_lines ) def parse(): parsed_lines = [] for line in open("input.txt"): criteria, password = line.strip().split(": ") interval, letter = criteria.split() l, h = map(int, interval.split("-")) parsed_lines.append(ParsedLine(l, h, letter, password)) return parsed_lines def main(): parsed_lines = parse() print(part1(parsed_lines)) print(part2(parsed_lines)) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- print "1 choklad 10 kr" print "2 festis 8 kr" print "Tryck nummer för onskad vara" nr = int(raw_input(">>> ")) if nr == 1: print "mata in 10 kr" if nr == 2: print "mata in 8 kr" kr = int(raw_input(">>> ")) if nr == 1 and kr >= 10: print "choklad" print "Du får tillbaka %s kr." % (kr - 10) if nr == 2 and kr >= 8: print "choklad" print "Du får tillbaka %s kr." % (kr - 8) if nr == 1 and kr < 10: print "För lite pengar för din önskad vara" if nr == 2 and kr < 8: print "För lite pengar för din önskad vara"
import random n = int(input("колво элементов в массиве:")) arr=[] for i in range(n): arr.append(random.randint(0,1000)) #step sorting for i in range(len(arr)): for j in range(0, len(arr) - i - 1): if arr[j] > arr[j + 1]: (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]) print(arr) find = int(input("число для поиска:")) mid=n//2 left=0 right=n-1 while arr[mid]!=find and left<=right: if find>arr[mid]: left = mid+1 else: right = mid-1 mid = (left+right)//2 if left>right: print("Not find") else: print(mid) # 1 2 3 4 5 6 7 8 9 10 # n=10 # mid = 5 # left = 0 # right = 9 # find = 2 # arr[9] # left = 0 # right=mid-1 4
arr=[42,123,3894,212,422] arr1=[] arr2=[] for i in range(0,3): arr1.append(arr[i]) for i in range(3,len(arr)): arr2.append(arr[i]) print(arr) print(arr1) print(arr2) arr3=arr1+arr2 print(arr3)
arr = [] sumi=0 n = int(input("Write count of array:")) #code print(arr) for i in range(n): number = int(input()) arr.append(number) print(arr) print(arr) for i in range(n): sumi = sumi + arr[i] print(sumi)
# def plus(a,b): # print(a+b) # plus(10,20) def print_arr(arr): for i in arr: print(i) a=[1,2,3,4,5] b =["asdsad","adsad",1231,3123] print_arr(b)
# Final Intro to CS project created by NYU Abu Dhabi '18 students Peter Hadvab (@jozozchrenovej)and Mark Surnin (@marksurnin). # To be continued... import random class Board: def __init__(self, textfile): ''' Board is represented as a textfile that is in the same directory as this file. This method creates a board, which is a list of lists, where every sublist represents a row and every element in a sublist represents an individual square, which is denoted either by 'X' (wall), 'o' (unvisited square), '_' (visited square), '@' (PacMan) or 'M' (monster). Note: Monster can also be represented by a lowecase 'm', which signifies that the monster is on a visited square. PacMan and monster objects are created within this method; score and lives counters are also initialized. ''' self.textfile = textfile fp = open(textfile, 'r+') self.board = [] self.pacman = Pacman(0,0) self.score = 0 self.lives = 3 self.monster = Monster(0, 0) for line in fp: self.board.append(list(line.strip())) # Reading the file and creating a list of lists. def draw_board(self): ''' This method goes through the list of lists (board) and draws elements in corresponding positions as the board is being updated. ''' for row in range(len(self.board)): for col in range(len(self.board[0])): if self.board[row][col] == 'X': # Drawing a wall. fill(0,0,150) noStroke() rect(30*col, row*30, 30, 30) elif self.board[row][col] == 'o': # Drawing an unvisited square with a dot. fill(0) rect(30*col, row*30, 30, 30) fill(random.randint(0,255),random.randint(0,255),random.randint(0,255)) ellipse(30*col+15, 30*row+15, 10, 10) elif self.board[row][col] == '_': # Drawing a visited square without a dot. fill(0, 0, 0) rect(30*col, row*30, 30, 30) elif self.board[row][col] == '@': # Drawing the PacMan (a yellow square for now, animation is in progress). fill(255,255,0) rect(30*col, row*30, 30, 30) self.pacman.update(col,row,self.pacman.cur_direction) elif self.board[row][col].upper() == 'M': # Drawing the monster (one monster for now, in progress). fill(255,50,0) rect(30*col, row*30, 30, 30) self.monster.update(col,row) textSize(32) fill(0,102,153) text('Score: ' + str(self.score), 500, 430) # Printing the score. if self.lives > 0: text('Lives: ' + str(self.lives), 680, 430) #Printing remaining lives. # else: # self.board[1][1] = '_' # self.board[1][2] = '_' # self.board[2][1] = '_' # text('Game Over', 330, 450) def can_pacman_move(self, direction): ''' This method checks if the Pacman can move in a specified direction. ''' if direction == 'left': if self.board[self.pacman.y][self.pacman.x - 1] != 'X': return True if direction == 'right': if self.board[self.pacman.y][self.pacman.x + 1] != 'X': return True if direction == 'up': if self.board[self.pacman.y - 1][self.pacman.x] != 'X': return True if direction == 'down': if self.board[self.pacman.y + 1][self.pacman.x] != 'X': return True def move_pacman(self, move_direction): ''' This method moves the PacMan in a specified direction, updating a number of values in the list of lists. ''' if move_direction == 'left': if self.board[self.pacman.y][self.pacman.x - 1] == 'o': # Checking if there is an unvisited square (with a dot) on the left. self.board[self.pacman.y][self.pacman.x] = '_' # Making the previous coordinates a visited square (without a dot). self.board[self.pacman.y][self.pacman.x - 1] = '@' # Moving the PacMan to the left. self.pacman.x -= 1 # Decrementing the PacMan's X coordinate by 1. self.score += 1 # Incrementing the player's score by 1 when he lands on an unvisited square. elif self.board[self.pacman.y][self.pacman.x - 1] == '_': # Similar procedure if moving to a VISITED square. No incrementing of the score. self.board[self.pacman.y][self.pacman.x] = '_' self.board[self.pacman.y][self.pacman.x - 1] = '@' self.pacman.x -= 1 elif self.board[self.pacman.y][self.pacman.x - 1] == 'M' or self.board[self.pacman.y][self.pacman.x - 1] == 'm': self.pacman.x = 1 # If the sqaure on the left is a monster, reset PacMan's coordinates to (1,1). self.pacman.y = 1 self.board[1][1] = '@' if move_direction == 'right': # Analogous algorithm for PacMan moving right, down and up. if self.board[self.pacman.y][self.pacman.x + 1] == 'o': self.board[self.pacman.y][self.pacman.x] = '_' self.board[self.pacman.y][self.pacman.x + 1] = '@' self.pacman.x += 1 self.score += 1 elif self.board[self.pacman.y][self.pacman.x + 1] == '_': self.board[self.pacman.y][self.pacman.x] = '_' self.board[self.pacman.y][self.pacman.x + 1] = '@' self.pacman.x += 1 elif self.board[self.pacman.y][self.pacman.x + 1] == 'M' or self.board[self.pacman.y][self.pacman.x + 1] == 'm': self.pacman.x = 1 self.pacman.y = 1 self.board[1][1] = '@' if move_direction == 'up': if self.board[self.pacman.y - 1][self.pacman.x] == 'o': self.board[self.pacman.y][self.pacman.x] = '_' self.board[self.pacman.y - 1][self.pacman.x] = '@' self.pacman.y -= 1 self.score += 1 elif self.board[self.pacman.y - 1][self.pacman.x] == '_': self.board[self.pacman.y][self.pacman.x] = '_' self.board[self.pacman.y - 1][self.pacman.x] = '@' self.pacman.y -= 1 elif self.board[self.pacman.y - 1][self.pacman.x] == 'M' or self.board[self.pacman.y - 1][self.pacman.x] == 'm': self.pacman.x = 1 self.pacman.y = 1 self.board[1][1] = '@' if move_direction == 'down': if self.board[self.pacman.y + 1][self.pacman.x] == 'o': self.board[self.pacman.y][self.pacman.x] = '_' self.board[self.pacman.y + 1][self.pacman.x] = '@' self.pacman.y += 1 self.score += 1 elif self.board[self.pacman.y + 1][self.pacman.x] == '_': self.board[self.pacman.y][self.pacman.x] = '_' self.board[self.pacman.y + 1][self.pacman.x] = '@' self.pacman.y += 1 elif self.board[self.pacman.y + 1][self.pacman.x] == 'M' or self.board[self.pacman.y + 1][self.pacman.x] == 'm': self.pacman.x = 1 self.pacman.y = 1 self.board[1][1] = '@' def find_possible_directions_monster(self): ''' By counting the number of possible directions after every iteration, the program records whether the monster is at a junction. If there is not a wall to the left, for example, left is added to the list of possible directions. The number of choices is returned. ''' self.monster.pos_directions = [] choices = 0 if self.board[self.monster.y][self.monster.x - 1] != 'X': choices += 1 self.monster.pos_directions.append("left") if self.board[self.monster.y][self.monster.x + 1] != 'X': choices += 1 self.monster.pos_directions.append("right") if self.board[self.monster.y - 1][self.monster.x] != 'X': choices += 1 self.monster.pos_directions.append("up") if self.board[self.monster.y + 1][self.monster.x] != 'X': choices += 1 self.monster.pos_directions.append("down") return choices def change_direction_monster(self): ''' If there is only one possible direction, it means there is a dead end, need to reverse direction. Note: a list of directions = ['left', 'up', 'right', 'down'] is initialized in the setup() function. The program takes the current direction of the PacMan (ex. 'right'), finds the index of 'right' in the directions list. In our case it is 2. Note that the opposite directions are 1 apart from each other in the list. We add 2 to the index, get 4. The modulo operator makes sure we move to the next element in the list, creating a loop. In this case it directs us to 4 % 4 = 0 ('left'). If there are two directions: The PacMan is either moving in a straight line (keep going). The Pacman is at a 90-degree angle junction (randomly choose a direction from the list of possible directions.) If there are more than two directions: Randomly choose a direction from the list of possible directions. ''' if self.find_possible_directions_monster() == 1: self.monster.cur_direction = directions[(directions.index(self.monster.cur_direction)+2)%4] elif self.find_possible_directions_monster() == 2: if self.monster.pos_directions[1] != directions[(directions.index(self.monster.pos_directions[0])+2)%4]: # If the monster is NOT moving in a straight line self.monster.cur_direction = random.choice(self.monster.pos_directions) elif self.find_possible_directions_monster() > 2: self.monster.cur_direction = random.choice(self.monster.pos_directions) def move_monster(self): ''' A monster move function similar to the PacMan move function, with a minor tweak with upper or lowercase 'm'/'M', which signifies whether the moster is moving from a visited square or not. ''' if self.monster.cur_direction == 'left': if self.board[self.monster.y][self.monster.x] == 'm': self.board[self.monster.y][self.monster.x] = '_' elif self.board[self.monster.y][self.monster.x] == 'M': self.board[self.monster.y][self.monster.x] = 'o' if self.board[self.monster.y][self.monster.x-1] == '_': self.board[self.monster.y][self.monster.x - 1] = 'm' elif self.board[self.monster.y][self.monster.x-1] == 'o': self.board[self.monster.y][self.monster.x-1] = 'M' elif self.board[self.monster.y][self.monster.x-1] == '@': # The following lines are executed if the Pacman is moving to a square with the PacMan! self.board[self.monster.y][self.monster.x-1] = 'm' # Make the square to the left a lowercase 'm' (monster standing on a visited square). self.pacman.x = 1 # Make PacMan's coordinates (1,1) - resetting position. self.pacman.y = 1 self.board[1][1] = '@' # Place the '@' symbol in board[1][1]. self.lives -= 1 # Decrement the number of lives by 1. self.monster.x -= 1 # Decrement the monster's x coordinate by 1 (if moving to the left). if self.monster.cur_direction == 'right': # Analogous algorithm for the monster moving right, down and up. if self.board[self.monster.y][self.monster.x] == 'm': self.board[self.monster.y][self.monster.x] = '_' elif self.board[self.monster.y][self.monster.x] == 'M': self.board[self.monster.y][self.monster.x] = 'o' if self.board[self.monster.y][self.monster.x+1] == '_': self.board[self.monster.y][self.monster.x+1] = 'm' elif self.board[self.monster.y][self.monster.x+1] == 'o': self.board[self.monster.y][self.monster.x+1] = 'M' elif self.board[self.monster.y][self.monster.x+1] == '@': self.board[self.monster.y][self.monster.x+1] = 'm' self.pacman.x = 1 self.pacman.y = 1 self.board[1][1] = '@' self.lives -= 1 self.monster.x += 1 if self.monster.cur_direction == 'up': if self.board[self.monster.y][self.monster.x] == 'm': self.board[self.monster.y][self.monster.x] = '_' elif self.board[self.monster.y][self.monster.x] == 'M': self.board[self.monster.y][self.monster.x] = 'o' if self.board[self.monster.y-1][self.monster.x] == '_': self.board[self.monster.y-1][self.monster.x] = 'm' elif self.board[self.monster.y-1][self.monster.x] == 'o': self.board[self.monster.y-1][self.monster.x] = 'M' elif self.board[self.monster.y-1][self.monster.x] == '@': self.board[self.monster.y-1][self.monster.x] = 'm' self.pacman.x = 1 self.pacman.y = 1 self.board[1][1] = '@' self.lives -= 1 self.monster.y -= 1 if self.monster.cur_direction == 'down': if self.board[self.monster.y][self.monster.x] == 'm': self.board[self.monster.y][self.monster.x] = '_' elif self.board[self.monster.y][self.monster.x] == 'M': self.board[self.monster.y][self.monster.x] = 'o' if self.board[self.monster.y+1][self.monster.x] == '_': self.board[self.monster.y+1][self.monster.x] = 'm' elif self.board[self.monster.y+1][self.monster.x] == 'o': self.board[self.monster.y+1][self.monster.x] = 'M' elif self.board[self.monster.y+1][self.monster.x] == '@': self.board[self.monster.y+1][self.monster.x] = 'm' self.pacman.x = 1 self.pacman.y = 1 self.board[1][1] = '@' self.lives -= 1 self.monster.y += 1 class Pacman: ''' Pacman class. Purpose: storing current and next directions. Next direction is determined by which arrow key is pressed. ''' def __init__(self, x, y): self.x = x self.y = y self.cur_direction = None self.next_direction = None def update(self, row, col, dir): # Updating the current direction to the value of the passed variable. self.x = row self.y = col self.cur_direction = dir class Monster: ''' Monster class. Purpose: storing current direction and the list of possible directions at every iteration. ''' def __init__(self, x, y): self.x = x self.y = y self.pos_directions = [] self.cur_direction = 'up' def update(self, row, col): self.x = row self.y = col def setup(): size(1260, 510) background(200, 200, 210) frameRate(6) global board global directions directions = ['left', 'up', 'right', 'down'] # The direction list referred to in change_direction_monster() function documentation. board = Board('board.txt') # The board file, has to be in the same directory. def keyPressed(): ''' Updates next_direction according to which arrow key is pressed. ''' if keyCode == LEFT: board.pacman.next_direction = 'left' elif keyCode == RIGHT: board.pacman.next_direction = 'right' elif keyCode == UP: board.pacman.next_direction = 'up' elif keyCode == DOWN: board.pacman.next_direction = 'down' elif keyCode == SHIFT: # New game - reset all values and positions. for row in range(len(board.board)): for col in range(len(board.board[0])): if board.board[row][col] == '_' or board.board[row][col] == '@' or board.board[row][col] == 'M' or board.board[row][col] == 'm': board.board[row][col] = 'o' # Make all squares unvisited. board.board[1][1] = '@' # Place the PacMan at board[1][1]. board.board[11][21] = 'M' # Place the monster at board[11][21]. Row is the first sublist, so the coordinates are in the form (y,x). board.pacman.x = 1 board.pacman.y = 1 board.monster.x = 21 board.monster.y = 11 board.monster.cur_direction = 'up' # Reset monster's current direction to 'up'. Make sure there is actually space for it to move up. board.score = 0 # Reset the score and lives. board.lives = 3 def draw(): if board.lives == 0: # Game over image if there are no lives left. img = loadImage('game_over.jpg') image(img, 0, 0, 1260, 510) elif board.score == 219: # Winner image if all dots have been eaten. img = loadImage('winner.png') image(img, 0, 0, 1260, 510) else: # Main move function. if board.pacman.next_direction: # If there is a next direction (some arrow key was pressed): if board.can_pacman_move(board.pacman.next_direction): # Check if the PacMan can move in that direction. board.pacman.cur_direction = board.pacman.next_direction # If yes, make that the current direction. board.pacman.next_direction = None # Set next direction to None. board.move_pacman(board.pacman.cur_direction) # Move the PacMan in that direction. else: # If the PacMan can't move in the next direction yet: if board.can_pacman_move(board.pacman.cur_direction): # If the PacMan can move in the direction it was going in: board.move_pacman(board.pacman.cur_direction) # Move the PacMan in that direction. (Basically, keep moving the PacMan where it was going until it can go in the next direction). else: # If there is no specified next direction (no arrow keys were pressed): if board.can_pacman_move(board.pacman.cur_direction): # (Repeat the logic) If the PacMan can move in the direction it was going in: board.move_pacman(board.pacman.cur_direction) # Move the PacMan in that direction. board.change_direction_monster() # Changes the direction of the monster if it is at a junction or a dead end. Keeps it going if it is going in a straight line, passing no junction. board.move_monster() # Moves the monster in that very direction. board.draw_board() # Draw the board.
import csv import csv with open("new_names.csv",'r') as csvf: read_csv=csv.reader(csvf) next(read_csv) for x in read_csv: print(x[2]) ''' OUTPUT:>>> [email protected] [email protected] [email protected] [email protected] [email protected]' ''' with open("new_names.csv",'r') as csvf: read_csv=csv.reader(csvf) with open("my_newcsvfile.csv",'w') as ncsvf: write_csv=csv.writer(ncsvf,delimiter='-') for x in read_csv: write_csv.writerow(x) #then new file will bw as follows ''' first_name-last_name-email John-Doe-"[email protected]" Mary-"Smith-Robinson"[email protected] [email protected] [email protected] [email protected] [email protected] [email protected] ''' with open('names.csv', 'r') as csv_file: csv_reader = csv.DictReader(csv_file) with open('new_names.csv', 'w') as new_file: fieldnames = ['first_name', 'last_name'] csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames, delimiter='\t') csv_writer.writeheader() for line in csv_reader: del line['email'] csv_writer.writerow(line)
list_of_numbers = [-2,-1,1,2,3,4,5,6,7,8,9] print(list_of_numbers) smallest = 1 for number in list_of_numbers: if number < smallest: smallest = number print("========================\nThe smallest number is ") print(smallest)
board = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] # board display def print_board(board): for i in range(3): print() for j in range(3): print(board[i][j], end='') if j < 2: print('|', end='') # user input value def user_input(): pos = input("\n Enter any number from 1 to 9: ") pos = int(pos) -1 if pos <= 9: return pos else: pos = input("\n Enter any number from 1 to 9: ") pos = int(pos) -1 # position of the player input in board def place_player(pos, player): row = pos // 3 column = pos % 3 board[row][column] = player return 1 # check if game tie def game_tie(): for i in range(3): for j in range(3): if board[i][j] == '_': return else: continue print("The game is tied.") game_on = False # check if column player win def check_column(j): x = 0 y = 0 for i in range(3): if board[i][j] == 'x': x += 1 if board[i][j] == 'y': y += 1 if x == 3: print('x won') return game_on == False elif y == 3: print('y won') return game_on == False else: return game_on == True # check if row player win def check_row(j): x = 0 y = 0 for i in range(3): if board[j][i] == 'x': x += 1 if board[j][i] == 'y': y += 1 if x == 3: print('x won') return game_on == False elif y == 3: print('y won') return game_on == False else: return game_on == True # check diagonal def check_diagonal(a,b,c): var = [a, b, c] x = 0 y = 0 for i in var: if i == 'x': x += 1 if i == 'y': y += 1 if x == 3: print('x won') return game_on == False elif y == 3: print('y won') return game_on == False else: return game_on == True # main function of game tic tac toe def main(): counter = 1 global game_on game_on = True while game_on: if counter % 2 == 0: player = 'y' else: player = 'x' pos = user_input() place_player(pos, player) counter += place_player(pos, player) for j in range(3): game_on = check_column(j) game_on = check_row(j) check_diagonal(board[0][0], board[1][1], board[2][2]) check_diagonal(board[0][2], board[1][1], board[2][0]) print (print_board(board)) game_tie() main()
# Tic Tac Toe import random # Draws empty board def drawBoard(board): print(" "+board[7]+"| "+board[8]+" | "+board[9]+" ") print("---|---|---") print(" "+board[4]+" | "+board[5]+" | "+board[6]+" ") print("---|---|---") print(" "+board[1]+" | "+board[2]+" | "+board[3]+" ") # Makes player choose X or O and assigns computer opposite value from the player def chooseLetter(): letter = '' while not (letter == 'X' or letter == 'O'): print('Do you want to be X or O?') letter = input().upper() if letter == 'X': return ['X', 'O'] else: return ['O', 'X'] # Defines who will make first move, if player chooses X computer will go first, if player chooses O he will go first def FirstMove(): if random.randint(0, 1) == 0: return 'computer' else: return 'player' def makeMove(board, letter, move): board[move] = letter # Defines options for winning the game def Winner(Player1, Computer): return ((Player1[7] == Computer and Player1[8] == Computer and Player1[9] == Computer) or (Player1[4] == Computer and Player1[5] == Computer and Player1[6] == Computer) or (Player1[1] == Computer and Player1[2] == Computer and Player1[3] == Computer) or (Player1[7] == Computer and Player1[4] == Computer and Player1[1] == Computer) or (Player1[8] == Computer and Player1[5] == Computer and Player1[2] == Computer) or (Player1[9] == Computer and Player1[6] == Computer and Player1[3] == Computer) or (Player1[7] == Computer and Player1[5] == Computer and Player1[3] == Computer) or (Player1[9] == Computer and Player1[5] == Computer and Player1[1] == Computer)) def newBoard(board):
def armstrong(number): temp = number sum1 = 0 print temp while temp > 0: digit = temp % 10 sum1 = sum1 + pow(digit, 3) temp = temp / 10 print sum1 if number == sum1: print "{} is armstrong".format(number) else: print "{} is not armstrong".format(number) def all_armstrong_numbers(limit): # there is problem while printing armstrong .. it prints only till 407 for i in range(1, limit): number = i sum1 = 0 while number > 0: digit = number % 10 sum1 = sum1 + pow(digit, 3) number = number / 10 if i == sum1: print i def fibonacci(count): sequence = (0, 1) for i in range(2, count): sequence += (reduce(lambda a, b: a + b, sequence[-2:]), ) return sequence[:count] def printTrg(rows): r1 = [1] r2 = [1, 1] trg = [r1, r2] r = [] if rows == 1: r1[0] = str(r1[0]) print(' '.join(r1)) elif rows == 2: for o in trg: for a in range(len(o)): o[a] = str(o[a]) print ' '*(2-(a+1)), (' '.join(o)) else: for i in range(2, rows): trg.append([1]*i) for n in range(1, i): trg[i][n] = (trg[i-1][n-1]+trg[i-1][n]) trg[i].append(1) for x in range(len(trg)): for y in trg[x]: s = str(y) r.append(s) print ' '*(rows-(x+1)), (' ' .join(r)) r = [] def pattern(): for i in range(7): print ('*' + " ") * i def main(): while True: try: print "--------------------------------------Menu--------------------------------------" print "\n\t 1. Check whether no. is Armstrong or not" print "\n\t 2. Armstrong number between 1 to n" print "\n\t 3. Fibonacci series up to n" print "\n\t 4. pascal triangle up to n rows" print "\n\t 5. print star pattern" print "\n\t 6. Exit" ch = input("Enter your choice :") if ch == 1: no = input("Enter a number : ") armstrong(no) elif ch == 2: n = input("Enter a limit : ") all_armstrong_numbers(n) elif ch == 3: print(fibonacci(10)) elif ch == 4: n = input("Enter a limit : ") printTrg(n) elif ch == 5: pattern() else: break except Exception as e: print "Error : {}".format(e) main()
import time class BookingClass(object): business = "BUSINESS" economy = "ECONOMY" class SeatingArea(object): def __init__(self, booking_class, start_row, row_count, seats_per_row): self.booking_class = booking_class self.start_row = start_row self.row_count = row_count self.seats_per_row = seats_per_row self.total_seats = row_count * seats_per_row self.window_seats = 2 * self.row_count self.Aisle = 2 * self.row_count self.otherSeats = self.total_seats - (self.Aisle + self.window_seats) self.book_count = 0 self.remaining_seat_count = 0 def get_booking_class(self): return self.booking_class def get_start_row(self): return self.start_row def get_row_count(self): return self.row_count def get_seats_per_row(self): return self.seats_per_row def get_total_seats(self): return self.total_seats def get_window_seats(self): return self.window_seats def get_aisle(self): return self.Aisle def get_middle_seats(self): return self.otherSeats def get_book_count(self): return self.book_count def get_remaining_count(self): return self.remaining_seat_count business = SeatingArea(booking_class=BookingClass.business, start_row=1, row_count=5, seats_per_row=6) economy = SeatingArea(booking_class=BookingClass.economy, start_row=6, row_count=20, seats_per_row=8) business_seats = business.get_total_seats() economy_seats = economy.get_total_seats() business_window_seats = business.get_window_seats() economy_window_seats = economy.get_window_seats() business_aisle_seats = business.get_aisle() economy_aisle_seats = economy.get_aisle() business_middle_seats = business.get_middle_seats() economy_middle_seats = economy.get_middle_seats() business_book_count = business.get_book_count() business_remaining_seat_count = business.get_remaining_count() business_total_seats = business.get_total_seats() economy_book_count = economy.get_book_count() economy_remaining_seat_count = economy.get_remaining_count() economy_total_seats = economy.get_total_seats() book_count = business_book_count + economy_book_count remaining_seat_count = business_remaining_seat_count + economy_remaining_seat_count total_seats = business_total_seats + economy_total_seats while True: response = raw_input('Do you want to book a ticket now? ') if response == "yes": class_response = raw_input("Which class do you prefer ?") if class_response == "business": seat_response = raw_input("Which Seat do you want ? window | aisle : ") if seat_response == "window": print "Please wait I am booking window seat for you ..." time.sleep(2) business_window_seats -= 1 print "Window seats remaining = {} ".format(business_window_seats) book_count += 1 remaining_seat_count = total_seats - book_count print "Total seats booked = {}".format(book_count) print "Total seats remaining = {}".format(remaining_seat_count) elif seat_response == "aisle": print "Please wait I am booking aisle seat for you ..." time.sleep(2) business_aisle_seats -= 1 print "Window seats remaining = {} ".format(business_aisle_seats) book_count += 1 remaining_seat_count = total_seats - book_count print "Total seats booked = {}".format(book_count) print "Total seats remaining = {}".format(remaining_seat_count) elif seat_response == "middle": print "Please wait I am booking middle seat for you ..." time.sleep(2) business_middle_seats -= 1 print "Window seats remaining = {} ".format(business_aisle_seats) book_count += 1 remaining_seat_count = total_seats - book_count print "Total seats booked = {}".format(book_count) print "Total seats remaining = {}".format(remaining_seat_count) print "Window seats remaining = {} ".format(business_aisle_seats) book_count += 1 remaining_seat_count = total_seats - book_count print "Total seats booked = {}".format(book_count) print "Total seats remaining = {}".format(remaining_seat_count) else: print "You made a wrong choice" if class_response == "economy": seat_response = raw_input("Which Seat do you want ? window | aisle : ") if seat_response == "window": print "Please wait I am booking window seat for you ..." time.sleep(2) economy_window_seats -= 1 print "Window seats remaining = {} ".format(economy_window_seats) book_count += 1 remaining_seat_count = total_seats - book_count print "Total seats booked = {}".format(book_count) print "Total seats remaining = {}".format(remaining_seat_count) elif seat_response == "aisle": print "Please wait I am booking aisle seat for you ..." time.sleep(2) economy_aisle_seats -= 1 print "Window seats remaining = {} ".format(economy_aisle_seats) book_count += 1 remaining_seat_count = total_seats - book_count print "Total seats booked = {}".format(book_count) print "Total seats remaining = {}".format(remaining_seat_count) elif seat_response == "middle": print "Please wait I am booking middle seat for you ..." time.sleep(2) print "Please wait I am booking aisle seat for you ..." time.sleep(2) economy_middle_seats -= 1 print "Window seats remaining = {} ".format(economy_middle_seats) book_count += 1 remaining_seat_count = total_seats - book_count print "Total seats booked = {}".format(book_count) print "Total seats remaining = {}".format(remaining_seat_count) print "Window seats remaining = {} ".format(business_aisle_seats) book_count += 1 remaining_seat_count = total_seats - book_count print "Total seats booked = {}".format(book_count) print "Total seats remaining = {}".format(remaining_seat_count) else: print "You made a wrong choice" else: print "Thanks for using Flight Booking system" break
from structure import ListNode class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: pp = None res = None p1 = l1 p2 = l2 while p1 is not None or p2 is not None: if p1 is None and p2 is not None: p = p2 p2 = p2.next elif p1 is not None and p2 is None: p = p1 p1 = p1.next else: if p1.val < p2.val: p = p1 p1 = p1.next else: p = p2 p2 = p2.next if pp is not None: pp.next = p pp = pp.next else: pp = res = p return res l1 = ListNode.fromList([1, 2, 4]) l2 = ListNode.fromList([1, 3, 4]) lm=Solution().mergeTwoLists(l1, l2) print(lm)
def quick_sort(nums, a, b): if b>=a: return pivot = nums[a] l, r = a, b while l < r: while l < r and nums[r] > pivot: r -= 1 if l < r: nums[l] = nums[r] l += 1 while l < r and nums[l] < pivot: l += 1 if l < r: nums[r] = nums[l] r -= 1 nums[l] = pivot quick_sort(nums, a, l - 1) quick_sort(nums, l + 1, b) nums = [5, 3, 4, 7] quick_sort(nums, 0, len(nums) - 1) print(nums)
from structure import ListNode class Solution: def isPalindrome(self, head: ListNode) -> bool: pre = None slow = head fast = head while fast is not None and fast.next is not None: fast = fast.next.next tmp = slow.next slow.next = pre pre = slow slow = tmp if fast is not None: slow = slow.next while slow is not None: if slow.val != pre.val: return False slow = slow.next pre = pre.next return True if __name__ == '__main__': node = ListNode.fromList([1, 2, 2, 1]) print(Solution().isPalindrome(node))
import heapq from typing import List from structure import ListNode class MyNode: def __init__(self, node: ListNode): self.node = node def __lt__(self, other): return self.node.val < other.node.val class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: my_lists=[MyNode(node) for node in lists] heapq.heapify(my_lists) dummy = ListNode(0) p = dummy while my_lists: node = heapq.heappop(my_lists).node p.next = node p = p.next if node.next: heapq.heappush(my_lists, MyNode(node.next)) p.next = None return dummy.next
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : qichun tang # @Date : 2021-01-26 # @Contact : [email protected] from typing import List, Tuple class Solution: def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool: if not matrix: return False N = len(matrix) M = len(matrix[0]) def rec(root: Tuple[int, int]): x, y = root if not (0 <= x < N or 0 <= y < M): return False root_val = matrix[x][y] if root_val == target: return True if root_val < target: return rec((x, y + 1)) # 下 else: return rec((x - 1, y)) # 左 return rec((0, M - 1))
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : qichun tang # @Date : 2021-01-26 # @Contact : [email protected] class Solution: # 返回构造的TreeNode根节点 def reConstructBinaryTree(self, pre, tin): # write code here if not pre: return None in_ix = tin.index(pre[0]) node = TreeNode(pre[0]) node.left = self.reConstructBinaryTree(pre[1:in_ix + 1], tin[:in_ix]) node.right = self.reConstructBinaryTree(pre[in_ix + 1:], tin[in_ix + 1:]) return node
from structure import ListNode class Solution: def recurse(self, head: ListNode): # 写错↓ if head is None or head.next is None: return head # ←写错 last = self.recurse(head.next) head.next.next = head head.next = None return last successor = None def recurseN(self, head: ListNode, n: int): if n == 1: self.successor = head.next return head last = self.recurseN(head.next, n - 1) head.next.next = head head.next = self.successor return last def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: if m == 1: return self.recurseN(head, n) head.next = self.reverseBetween(head.next, m - 1, n - 1) return head node = ListNode.fromList([1, 2, 3, 4, 5]) print(Solution().recurse(node)) node = ListNode.fromList([1, 2, 3, 4, 5]) print(Solution().recurseN(node, 2)) node = ListNode.fromList([1, 2, 3, 4, 5]) print(Solution().reverseBetween(node, 2, 4))
from typing import List import heapq def heap_sort(nums): heapq.heapify(nums) res = [] while nums: res.append(heapq.heappop(nums)) return res class Solution: def sortArray(self, nums: List[int]) -> List[int]: return heap_sort(nums) # import random # nums = list(range(10)) # random.shuffle(nums) nums = [5, 2, 3, 1] print(Solution().sortArray(nums))
from typing import List class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) left, right, ret = [[0] * n for _ in range(3)] left[0] = 1 for i in range(1, n): left[i] = left[i - 1] * nums[i - 1] right[n - 1] = 1 for i in range(n - 2, -1, -1): right[i] = right[i + 1] * nums[i + 1] for i in range(n): ret[i] = left[i] * right[i] return ret ret = Solution().productExceptSelf([1, 2, 3, 4]) print(ret)
from typing import List class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: s_nums=sorted(nums) num2cnt={} for i,num in enumerate(s_nums): if num not in num2cnt: num2cnt[num]=i return [num2cnt[num] for num in nums]
from typing import List class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ z = nz = 0 n = len(nums) while z < n and nz < n: while z < n and nums[z] != 0: z += 1 while nz < n and nums[nz] == 0: nz += 1 if z >= n or nz >= n: break if z < nz: nums[z], nums[nz] = nums[nz], nums[z] else: nz = z + 1 print(nums) Solution().moveZeroes([0, 1, 0, 3, 12]) Solution().moveZeroes([1, 0, 0]) Solution().moveZeroes([1, 0, 1])
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : qichun tang # @Contact : [email protected] from structure import ListNode class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if not head: return head oddHead, evenHead = head, head.next odd, even = oddHead, evenHead while even and even.next: odd.next = even.next odd = odd.next # 别忘了自己要移动 even.next = odd.next even = even.next odd.next = evenHead return head if __name__ == '__main__': nodes = ListNode.fromList([1, 2, 3, 4, 5]) solved = Solution().oddEvenList(nodes) print(solved)
# Import Dependencies = import random # Define all my global functions def scramble(word): word = list(word) random.shuffle(word) return ''.join(word) # The question def TheCyberKingQuestion1(): # At this point we will be requesting for the player to enter the source of the games data in a text file(.txt) format. file_name = input("Give the name of the words and their meanings file:") # After entering the filename, I can now read the file. # Note that - The file must be in the same folder as the python file. read_file = open(file_name, 'r') # Take the read file and convert to a key value pair. answer = {} for line in read_file: k, v = line.strip().split(',') answer[k.strip()] = v.strip() #Define some initial variables yes = "yes" no = "no" user_entered_value = "" question_mark = "?" # I will start an infinite loop here. while True: # if user input is empty if(user_entered_value == ""): # select a list from the key value pair answer word, meaning = random.choice(list(answer.items())) # declare more variable the_word = word the_meaning = meaning # Create a scrambled word scrambled_word = scramble(the_word) # User Input user_entered_value = input("Unscramble the following letters to form a word. Type ? for the meaning of the unscambled word:{}\n\nEnter the answer [or ? for the meaning]:".format(scrambled_word)) # User Input if equals to question mark if(user_entered_value == question_mark): print("\n\nThe word means:" + the_meaning) user_entered_value = input("Enter the answer [or ? for the meaning]:") # User Input if equals to question mark elif (user_entered_value == question_mark): print("\n\nThe word means:" + the_meaning) user_entered_value = input("Enter the answer [or ? for the meaning]:") # User Input if equals to no elif (user_entered_value == no): user_entered_value = "no" print("Goodbye!") break # User Input if equals to yes elif (user_entered_value == "yes"): user_entered_value = "" # User Input if equals to wrong elif (user_entered_value != the_word): print("\n\nWrong, try again") user_entered_value = input("Enter the answer [or ? for the meaning]:") # User Input if equals to right answer elif (user_entered_value == the_word): user_entered_value = input("You got it! Do you want to continue[yes or no]") # Call function TheCyberKingQuestion1()
from random import randint from art import logo def guess_number(user_input, random_num): if user_input == random_num: return True elif user_input > random_num: return False elif user_input < random_num: return False print(logo) print('Welcome to the Number Guessing Game!') print('I\'m thinking of a number between 1 and 100.') difficulty_level = input('Choose a difficulty. Type \'easy\' or \'hard\': ') is_game_over = False RANDOM_NUMBER = randint(1, 100) if difficulty_level == 'easy': attempts = 10 elif difficulty_level == 'hard': attempts = 5 while not is_game_over: print(f'You have {attempts} attempts remaining to guess the number.') user_guess = int(input('Make A Guess: ')) is_correct_guess = guess_number(user_input=user_guess, random_num=RANDOM_NUMBER) is_wrong_guess = guess_number(user_input=user_guess, random_num=RANDOM_NUMBER) if is_correct_guess: print(f'You Got It! The Answer Was {RANDOM_NUMBER}') is_game_over = True elif not is_wrong_guess: attempts -= 1 if attempts > 0 and user_guess > RANDOM_NUMBER: print('Too High.') print('Guess Again.') elif attempts > 0 and user_guess < RANDOM_NUMBER: print('Too Low.') print('Guess Again.') if attempts == 0: is_game_over = True print('You\'ve Run Out Of Guesses, You Lose')
# expected input/output in_ = '49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d' out_ = 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t' # string of b64 characters, index of each character in string is the # equivalent numerical value of the string in decimal b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" # pre: input must be a valid hexadecimal string # post: outputs resulting b64 encoded string for input hex string def hexToB64(in_): # to convert hexadecimal to b64, we note that a single hex digit # can be encoded by a nibble (4 bits), while a single b64 digit # can be encoded by 6 bits, we can deduce from this that the representational # power of 6 hex digits is the equivalent of 4 b64 digits, and thus we can # convert each 6 bits of a hex string to a b64 string character out_ = [] currentDigit = 0 # we will add either 4 or 2 bits at a time when encoding to b64, # need to track the missingDigits at each step to know how many # digits we must still add missingDigits = 6 for hexChar in reversed(in_): # convert digit of hex string to numerical value hexNum = int(hexChar, 16) # case 1: we have not included any hex bits in the current # base64 digit, in this case, we want to add all 4 bits of # the current hex digit, and set the missing digits to 2 # as we are encoding groups of 6 bits if missingDigits == 6: currentDigit = hexNum missingDigits = 2 # case 2: the previous hex character in the hex string has # been added to the currentDigit value, and thus we only need # the two remaining most significant bits to complete our # six bit b64 digit, we can apply the below bitwise operations # to get the two LSB of the current hex digit, and shift them to # be the 2 MSB of currentDigit elif missingDigits == 2: lastTwoBits = (hexNum & 0x3) << 4 currentDigit += lastTwoBits # get the b64 character that represents the numerical value # of the six bits of the currentDigit out_.append(b64[currentDigit]) # use remaining two MSB of the current hex character as the # two LSB of the next b64 numerical value currentDigit = (hexNum >> 2) & 0x3 missingDigits = 4 # case 3: the previous hex character was split up between the last # and current b64 digit, meaning that the 2 LSB of the current b64 # digit have already been determined, we can now use all four # bits of the current hex digit as the 4 MSB of the next b64 digit elif missingDigits == 4: lastFourBits = hexNum << 2 currentDigit += lastFourBits out_.append(b64[currentDigit]) currentDigit = 0 missingDigits = 6 # combine each b64 character into resulting output string return "".join(reversed(out_)) def main(): res = hexToB64(in_) print("output value is:", res) print("expected value is:", out_) assert res == out_ if __name__ == '__main__': main()
""" Module contains the Object class. """ from engine.texturemanager import TextureManager, TextureInfo class Object: """ An Object in the scene representing by a texture. An object can be attached to a scene node. """ def __init__(self, scenenode=None): """ Constructor for an object class. Keyword arguments: scenenode -- The scene node which this object is attached to. (default = None) """ self.texture_id = 'steve' self.size = (32, 32) self.node = scenenode def setTextureID(self, id): """ Sets the textureID for this object. Keyword arguments: id -- The TextureID stored in TextureManager """ self.texture_id = id def setSize(self, size): """ Sets the size of this object Keyword arguments: size -- A Tuple of Width and Height (w, h) """ self.size = size def setSceneNode(self, node): """ Sets the scenenode which this object is attached to, should never really be called except for by the scene node which it is attached to. Keyword arguments: node -- The node which this object is now attached to. """ self.node = node def update(self, delta): """ Blank function, Override this when creating a new object. Should contain most game logic for an object, called once per frame. Keyword arguments: delta -- The elapsed time since the last update call. """ pass def handle_collision(self, collision_data): """ Blank function, Override this when creating a new object. Called when this object is in a collision. Keyword arguments: collision_data -- The CollisionInformation object describing the collision. """ pass def move(self, amount): """ Tells node to move by amount Keyword arguments: amount -- (tx, ty) How much to translate by. """ self.node.translate(amount) def switch_texture(self, new_texture): """ Changes the texture id, and resets the new textures animation. It is better practise to use this than changing textureID or setTextureID() Keyword arguments: new_texture -- The TextureID to switch to. """ if self.texture_id == new_texture: return TextureManager.get_texture_info(newTexture).reset_anim() self.texture_id = new_texture
import pygame from pygame.locals import * class InputManager: """ InputManager is the class responsible for registering, and keeping current inputs up to date. """ def setup(): """ setup should be called when the game starts up, it creates empty dictionaries for the the controls. """ InputManager.controls = {} InputManager.old_control_values = {} InputManager.control_values = {} def get_control(id): """ Returns whether a control by the name of id is currently down. Keyword arguments: id -- The ID assigned to the control. Raises: ControlDoesntExistException -- When id has not been assigned to a control. """ if id in InputManager.controls: key = InputManager.controls[id] if key in InputManager.control_values: return InputManager.control_values[key] == 1 return False raise ControlDoesntExistException def get_control_pressed(id): """ Returns whether a control by the name of id got pressed down this frame. Keyword arguments: id -- The ID assigned to the control. Raises: ControlDoesntExistException -- When id has not been assigned to a control. """ if id in InputManager.controls: key = InputManager.controls[id] if key in InputManager.control_values and key in InputManager.old_control_values: return InputManager.control_values[key] == 1 and InputManager.old_control_values[key] == 0 return False raise ControlDoesntExistException def get_control_released(id): """ Returns whether a control by the name of id got released down this frame. Keyword arguments: id -- The ID assigned to the control. Raises: ControlDoesntExistException -- When id has not been assigned to a control. """ if id in InputManager.controls: key = InputManager.controls[id] if key in InputManager.control_values and key in InputManager.old_control_values: return InputManager.control_values[key] == 0 and InputManager.old_control_values[key] == 1 return False raise ControlDoesntExistException def update(events): """ Updates the current values for controls that ahve been registered. Keyword arguments: events -- The events list received from pygame.event.get() """ InputManager.old_control_values = InputManager.control_values InputManager.control_values = {} for e in events: if e.type == pygame.KEYDOWN: InputManager.control_values[e.key] = 1 elif e.type == pygame.KEYUP: InputManager.control_values[e.key] = 0 for key in InputManager.old_control_values: if key not in InputManager.control_values: InputManager.control_values[key] = InputManager.old_control_values[key] def assign_control(id, key): """ Assigns an ID to a pygame keycode, and registers it. Keyword arguments: id -- The ID to assign the keycode to. key -- The keycode to assign Raises: ControlExistsExeception -- When id has already been assigned to a control. """ if id not in InputManager.controls: print("Assigning key {0} to id: {1}".format(pygame.key.name(key), id)) InputManager.controls[id] = key else: raise ControlExistsException class ControlExistsException(Exception): """ Raised when a trying to register a keycode to an ID that already exists. """ pass class ControlDoesntExistException(Exception): """ Raised when a trying to find a control with an ID that doesn't exist. """ pass
import sys a=float(input('Insira o valor de a: ')) b=float(input('Insira o valor de b: ')) c=float(input('Insira o valor de c: ')) if a==0: print('Nao eh equacao de segundo grau') sys.exit() delta=(b**2)-4*a*c raizDelta=delta**0.5 if delta<0: print('A equacao nao possui raizes reais') sys.exit() elif delta==0: print('A equacao possui apenas uma raiz real:') raiz=(-b)/(2*a) print('raiz da equacao: {0:.2f}'.format(raiz)) sys.exit() else: print('A equacao possui duas raizes reais:') raiz1=(-b+raizDelta)/(2*a) raiz2=(-b-raizDelta)/(2*a) print('Raiz 1 {0:.2f} e Raiz 2 {1:.2f}'.format(raiz1,raiz2))
num=int(input('Insira um numero de 1 a 7: ')) if num==1: print('1-Domingo') elif num==2: print('2-Segunda') elif num==3: print('3-Terca') elif num==4: print('4-Quarta') elif num==5: print('5-Quinta') elif num==6: print('6-Sexta') elif num==7: print('7-Sabado') else: print('Valor Invalido')
import math valorSaque=int(input('Digite o valor do saque: ')) notas100=int(valorSaque/100) resto=valorSaque-notas100*100 if resto>=50: notas50=1 else: notas50=0 resto=resto-(notas50*50) if resto>=40: notas20=2 elif resto<40 and resto>=20: notas20=1 else: notas20=0 resto=resto-(notas20*20) if resto>=10: notas10=1 else: notas10=0 resto=resto-(notas10*10) if resto>=5: notas5=1 else: notas5=0 resto=resto-(notas5*5) if resto>=4: notas2=2 elif resto<4 and resto>=2: notas2=1 else: notas2=0 resto=resto-(notas2*2) if resto==1: notas1=1 else: notas1=0 print('Notas de R$100:{}'.format(notas100)) print('Notas de R$50:{}'.format(notas50)) print('Notas de R$20:{}'.format(notas50)) print('Notas de R$10:{}'.format(notas10)) print('Notas de R$5:{}'.format(notas5)) print('Notas de R$2:{}'.format(notas2)) print('Notas de R$1:{}'.format(notas1))
import math num=int(input('Digite um numero: ')) verificador=num%2 if verificador==1: print('Eh impar') else: print('Eh par')
print("# Create new threads") for i in range(500): print("thread{} = myThread({})".format(i+1, i+1, i, i)) print("# Start new Threads") for i in range(500): print("thread{}.start()".format(i+1)) print("# Add threads to thread list") for i in range(500): print("threads.append(thread{})".format(i+1))
#! /usr/bin/env python __author__ = 'Arana Fireheart' from math import pi # This is an example of a function with an optional parameter # The optional parameter was added as an upgrade to handle # griviances about the lack of a "report and crash" mode # of operation. def avSphere(radius, raiseError = True, errorMessage = ""): surfaceArea = 4 * pi * radius ** 2 volume = 4 / 3 * pi * radius ** 3 if radius >= 0: return (surfaceArea, volume) else: if raiseError == True: raise ValueError else: print(errorMessage) return (abs(surfaceArea), abs(volume)) # The following code are test cases for my function. print(avSphere(3)) print(avSphere(43.5)) print(avSphere(0)) try: print(avSphere(-323)) except ValueError: print("Oops!") print(20 * '-') try: print(avSphere(-323, False)) except ValueError: print("Oops!") print(20 * '-') try: print(avSphere(-323, False, "Died due to negative radius, RIP")) except ValueError: print("Oops!") print(20 * '-') mySurfaceArea, myVolume = avSphere(43.5) print("Surface Area: {0} Volume: {1}".format(mySurfaceArea, myVolume))
import backtrader as bt # Import Backtrader # Create a strategy class MyStrategy(bt.Strategy): # Initialize policy parameters params = ( (...,...), # the last one “,” It's better not to delete ! ) # Log printing : Official documents for reference def log(self, txt, dt=None): ''' Function to build policy print log : It can be used to print order records or transaction records, etc ''' dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) # Initialization function def __init__(self): ''' Initialization property 、 Calculation index, etc ''' # The index calculation can be referred to 《backtrader Indicators 》 self.add_timer() # Add timers pass # In the whole test cycle , Functions corresponding to different time periods def start(self): ''' It is called before the test starts , Corresponding to the first 0 root bar''' # The relevant processing logic before the start of backtesting can be written here # Empty... Is called by default start() function , Used to start backtesting pass def prenext(self): ''' Strategy preparation phase , Corresponding to the first 1 root bar- The first min_period-1 root bar''' # This function is mainly used for waiting index calculation , Before the indicator calculation is completed, it will be called by default prenext() Empty function # min_period Namely __init__ To complete all the indicators in the calculation 1 The minimum period of time required for each value pass def nextstart(self): ''' The first time when the policy works properly , Corresponding to the first min_period root bar''' # Only in __init__ In the case that all the indicators in have values available , To start running the strategy # nextstart() Only run once , It's mainly used to tell you that you can start later next() 了 # nextstart() The default implementation of is to simply call next(), therefore next The logic of strategy in min_period root bar It has already been implemented pass def next(self): ''' The normal operation phase of the policy , Corresponding to the first min_period+1 root bar- The last one bar''' # The main strategy logic is written under this function # After entering this stage , It's going to be in turn in each bar Up cycle running next function # Query function print(' Current position ', self.getposition(self.data).size) print(' The current cost of holding ', self.getposition(self.data).price) # self.getpositionbyname(name=None, broker=None) print(' List of dataset names ',getdatanames()) data = getdatabyname(name) # Returns a dataset by name # General single function self.order = self.buy( ...) # purchase 、 Do more long self.order = self.sell(...) # sell 、 Short short self.order = self.close(...) # close a position cover self.cancel(order) # Cancellation of order # The objective is a single function # Order by target number self.order = self.order_target_size(target=size) # Order by target amount self.order = self.order_target_value(target=value) # Order by target percentage self.order = self.order_target_percent(target=percent) # Order mix brackets = self.buy_bracket() brackets = self.sell_bracket() pass def stop(self): ''' The end of the strategy , Corresponding to the last one bar''' # Inform the system that the back test has been completed , You can reset the policy and sort out the test results pass # Print the test back log def notify_order(self, order): ''' Notification of order information ''' pass def notify_trade(self, trade): ''' Notification of trading information ''' pass def notify_cashvalue(self, cash, value): ''' Inform current funds and total assets ''' pass def notify_fund(self, cash, value, fundvalue, shares): ''' Return the current funds 、 total assets 、 The value of the Fund 、 Fund share ''' pass def notify_store(self, msg, *args, **kwargs): ''' Return the information notification from the supplier ''' pass def notify_data(self, data, status, *args, **kwargs): ''' Return data related notification ''' pass def notify_timer(self, timer, when, *args, **kwargs): ''' Return notification of timer ''' # The timer can be set by the function add_time() add to pass # All kinds of transaction functions and query functions : Please check out 《 Trading ( On )》 and 《 Trading ( Next )》 ...... # Add strategy to the brain cerebro.addstrategy(MyStrategy)
# 次方 def myAbs(x): if not isinstance(x,(int,float)): raise TypeError("lalala") if x >0: return x else: return -x def power(x,n = 2): s = 1 while n > 0: n=n-1 s=s*x return s
import re # I (sort of) know regular expressions! # Calculate number of each element def calculate_quantity(eq,multiplier=1): splitted = re.findall('[A-Z][^A-Z]*', eq) element_dict = {} for i in splitted: try: element_dict[i] += multiplier except: element_dict[i] = multiplier return element_dict # Find if the equation is balanced def find_balanced(iteration_count,eq1,eq2): quantities_left = {} for i in range(len(eq1)): coefficient = int(str(iteration_count)[i]) quantities = calculate_quantity(eq1[i],coefficient) for j in quantities: try: quantities_left[j] += quantities[j] except: quantities_left[j] = quantities[j] quantities_right = {} for i in range(len(eq2)): coefficient = int(str(iteration_count)[i+len(eq1)]) quantities = calculate_quantity(eq2[i],coefficient) for j in quantities: try: quantities_right[j] += quantities[j] except: quantities_right[j] = quantities[j] if quantities_left == quantities_right: return True return False # Parse subscripts def parse_subscripts(eq): res = [] for term in eq: parsed_term = '' elements = re.findall('([A-Z][a-z]*)([2-9]*)',term) for element in elements: if element[1].isnumeric(): parsed_term+=element[0]*int(element[1]) else: parsed_term+=element[0] res.append(parsed_term) return res # Render final result def subtag(term): subbed_term = '' elements = re.findall('([A-Z][a-z]*)([2-9]*)', term) for element in elements: subbed_term+=element[0] if element[1].isnumeric(): subbed_term+='<sub>'+element[1]+'</sub>' return subbed_term def render(i,eq1,eq2,colortags=False): res = '' for j in range(len(eq1)): if colortags: eq1[j] = subtag(eq1[j]) if str(i)[j] != '1': if colortags: res+='<span style="color:rgb(39, 162, 211);">'+str(i)[j]+'</span>' else: res+=str(i)[j] res+=eq1[j] if j!=len(eq1)-1: res+='+' res+='->' for j in range(len(eq2)): if colortags: eq2[j] = subtag(eq2[j]) if str(i)[j+len(eq1)] != '1': if colortags: res+='<span style="color:rgb(39, 162, 211);">'+str(i)[j+len(eq1)]+'</span>' else: res+=str(i)[j+len(eq1)] res+=eq2[j] if j!=len(eq2)-1: res+='+' print(res) return res def run(eq1,eq2): # Split equation eq1 = eq1.split('+') eq2 = eq2.split('+') # Brute force raw_eq1 = eq1 raw_eq2 = eq2 eq1 = parse_subscripts(eq1) eq2 = parse_subscripts(eq2) iteration_count = int('9'*(len(eq1) + len(eq2))) for j in range(int('1'*(len(eq1)+len(eq2))),iteration_count): if find_balanced(j,eq1,eq2): break else: return 'Cannot balance equation. Make sure your inputs are correct, then try again.' return render(j,raw_eq1,raw_eq2,colortags=True) def main(): # Obtain sides of equation eq1 = input('eq1: ') eq2 = input('eq2: ') run(eq1,eq2) if __name__ == '__main__': main()
from nltk import word_tokenize from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from nltk.tag import pos_tag import nltk # Function to Tokenize the input text def Tokenize(text): tokens = word_tokenize(text) print '******** Tokenize *********' print tokens, '\n' return tokens # Function to remove stop words def StopWordsRemoval(tokens): stopWords = stopwords.words('english') filteredWords = [wo for wo in tokens if wo not in stopWords] wordsWithoutStops = [wo for wo in filteredWords if len(wo) > 2] print '******** Filtered Words *********' print wordsWithoutStops, '\n' return wordsWithoutStops # Function to Lemmatize def Lemmatizer(nonstop): resultList = list() for j in nonstop: resultList.append(WordNetLemmatizer().lemmatize(j)) print '******** Lemmatized Words *********' print resultList, '\n' return resultList # Function to remove verbs def RemoveVerbs(lemwords): resultList = list() for j in pos_tag(lemwords): if j[1][:2] == 'VB': continue else: resultList.append(j[0]) print '******** Verb Removal *********' print resultList, '\n' return resultList # Function to calculate word frequency def WordFrequenxy(verbless): wordsFreq = nltk.FreqDist(verbless) topFive = dict() for w, f in wordsFreq.most_common(5): topFive[w] = f print '******** Top Five Keys and Values *********' print topFive, '\n' return topFive # Function to get just top five words def GetWords(topfive): topFiveWords = topfive.keys() print '******** Top Five Words *********' print topFiveWords, '\n' return topFiveWords # Function to find sentences with top five words def FindSentences(text, topfive): result = list() for l in text.split('\n'): for w in topfive: if w in l.lower(): result.append(l) break return result # Function to summarize def Summarizer(sentences): print '******** Summary *********' print '\n'.join(sentences) def main(): text = open('/Volumes/Sibi-CLG/PythonFall17/Python-FL17/Lab-3/Source/data/input.txt', "r").read() tokens = Tokenize(text) nonstop = StopWordsRemoval(tokens) lemwords = Lemmatizer(nonstop) verbless = RemoveVerbs(lemwords) topfive = WordFrequenxy(verbless) topfivewords = GetWords(topfive) sentences = FindSentences(text, topfivewords) Summarizer(sentences) if __name__ == "__main__": main()
import unittest from sudoku import SudokuCell, Sudoku class TestSudokuCellMethods(unittest.TestCase): def test_init(self): test_cell = SudokuCell(3, 4) self.assertFalse(test_cell.value) self.assertEqual(test_cell.valid_numbers, range(1, 10)) def test_box_coordinates(self): test_cell = SudokuCell(1, 1) test_values = [(a+1, b) for a, b in enumerate([1, 1, 1, 2, 2, 2, 3, 3, 3])] for input_coord, box_coord in test_values: self.assertEqual(box_coord, test_cell.return_box_coord(input_coord)) def test_coordinate_generation(self): test_values = [[(1, 1), (1, 1, 1)], [(1, 4), (1, 4, 4)], [(4, 7), (4, 7, 8)], [(7, 4), (7, 4, 6)], [(9, 9), (9, 9, 9)]] for (x, y), output_coords in test_values: test_cell = SudokuCell(x, y) self.assertEqual(test_cell.get_coordinates(x, y), output_coords) def test_invalidate_number(self): test_cell = SudokuCell(1, 1) test_values = [1, 2, 3, 5, 6, 7, 8, 9] test_cell.invalidate_number(4) self.assertEqual(test_cell.valid_numbers, test_values) def test_pick_value(self): test_values = range(1, 10) test_cell = SudokuCell(1, 1) test_cell.pick_value() self.assertTrue(test_cell.value in test_values) def additional_tests(self): more_test_values = [1, 2, 5, 7, 9] test_cell = SudokuCell(1, 1) for num in [3, 4, 6, 8]: test_cell.invalidate_number(num) test_cell.pick_value() self.assertTrue(test_cell.value in more_test_values) class TestSudokuMethods(unittest.TestCase): def test_init(self): test_grid = Sudoku() self.assertEqual(len(test_grid.cells), 81) for cell in test_grid.cells: self.assertTrue(cell.coordinates[0] in range(1, 10)) self.assertTrue(cell.coordinates[1] in range(1, 10)) self.assertTrue(cell.coordinates[2] in range(1, 10)) self.assertEqual(test_grid.lowest_valid_numbers, 9) def test_invalidate_numbers_in_other_cells(self): test_grid = Sudoku() set_cell = test_grid.cells[0] set_cell.value = 1 set_cell.valid_numbers = [1] test_grid.invalidate_numbers_in_other_cells(set_cell) for other_cell in test_grid.cells: if any([coord_this == coord_other for (coord_this, coord_other) in zip(set_cell.coordinates, other_cell.coordinates)]) and not other_cell.value: self.assertFalse(1 in other_cell.valid_numbers) else: self.assertTrue(1 in other_cell.valid_numbers) def test_determine_lowest_valid_numbers(self): test_grid = Sudoku() counter = 0 for cell in test_grid.cells: if counter % 2 == 0: cell.valid_numbers = [1, 2, 3, 4, 5] else: cell.value = 1 cell.valid_numbers = [1] counter += 1 test_grid.determine_lowest_valid_numbers() self.assertEqual(test_grid.lowest_valid_numbers, 5) def test_generate_cell(self): test_grid = Sudoku() for n in range(len(test_grid.cells)): candidate_cell = next(cell for cell in test_grid.cells if (len(cell.valid_numbers) == test_grid.lowest_valid_numbers and not cell.value)) test_grid.generate_cell() self.assertTrue(candidate_cell.value in range(1, 10)) self.assertEqual(candidate_cell.valid_numbers, [candidate_cell.value]) def test_generate_full(self): test_grid = Sudoku() test_grid.generate_full() for coord in range(1, 10): x_rows = sorted([cell.value for cell in test_grid.cells if cell.coordinates[0] == coord]) y_cols = sorted([cell.value for cell in test_grid.cells if cell.coordinates[1] == coord]) z_boxes = sorted([cell.value for cell in test_grid.cells if cell.coordinates[2] == coord]) self.assertEqual(x_rows, range(1, 10)) self.assertEqual(y_cols, range(1, 10)) self.assertEqual(z_boxes, range(1, 10)) if __name__=="__main__": unittest.main()
import numpy as np import nnfs from nnfs.datasets import spiral_data nnfs.init() np.random.seed(0) X, y = spiral_data(100, 3) inputs = [0, 2, -1, 3.3, -2.7, 1.1, 2.2, -100] output = [] class Layer_Dense: def __init__(self, n_inputs, n_neurons): self.weights = 0.10 * np.random.randn(n_inputs, n_neurons) self.biases = np.zeros((1, n_neurons)) def forward(self, inputs): self.output = np.dot(inputs, self.weights) + self.biases class Activation_ReLU: def forward(self, inputs): self.output = np.maximum(0, inputs) layer1 = Layer_Dense(2, 5) activation1 = Activation_ReLU() layer1.forward(X) activation1.forward(layer1.output) print(activation1.output)
import numpy as np from enum import Enum class Rotation(Enum): ROLL = 0 PITCH = 1 YAW = 2 class EulerRotation: def __init__(self, rotations): """ `rotations` is a list of 2-element tuples where the first element is the rotation kind and the second element is angle in degrees. Ex: [(Rotation.ROLL, 45), (Rotation.YAW, 32), (Rotation.PITCH, 55)] """ self._rotations = rotations self._rotation_map = {Rotation.ROLL : self.roll, Rotation.PITCH : self.pitch, Rotation.YAW : self.yaw} def roll(self, phi): """Returns a rotation matrix along the roll axis""" phi = phi * (np.pi / 180.0) m = np.array([ [1, 0, 0], [0, np.cos(phi), -np.sin(phi)], [0, np.sin(phi), np.cos(phi)] ]) return m def pitch(self, theta): """Returns the rotation matrix along the pitch axis""" theta = theta * (np.pi / 180.0) m = np.array([ [ np.cos(theta), 0, np.sin(theta)], [ 0 , 1, 0], [-np.sin(theta), 0, np.cos(theta)] ]) return m def yaw(self, psi): """Returns the rotation matrix along the yaw axis""" psi = psi * (np.pi / 180.0) m = np.array([ [np.cos(psi), -np.sin(psi), 0], [np.sin(psi), np.cos(psi), 0], [0 , 0 , 1] ]) return m def rotate(self): """Applies the rotations in sequential order""" # reverse the apparent order in the code # to match the matrix multiplication conventions t = np.eye(3) for r in self._rotations: # select the function f = self._rotation_map[r[0]] # get the angle a = r[1] # multiply the matrix t = np.dot(f(a), t) #np.dot(self._rotation_map[self._rotations[2][0]](self._rotations[2][1]), # self._rotation_map[self._rotations[1][0]](self._rotations[1][1])), # self._rotation_map[self._rotations[0][0]](self._rotations[0][1])) return t def euler_to_quaternion(angles): roll = angles[0] pitch = angles[1] yaw = angles[2] # complete the conversion # and return a numpy array of # 4 elements representing a quaternion [a, b, c, d] cos_psi = np.cos(yaw / 2.0) sin_psi = np.sin(yaw / 2.0) cos_phi = np.cos(roll / 2.0) sin_phi = np.sin(roll / 2.0) cos_tht = np.cos(pitch / 2.0) sin_tht = np.sin(pitch / 2.0) a = np.array([ cos_phi * cos_tht * cos_psi + sin_phi * sin_tht * sin_psi, sin_phi * cos_tht * cos_psi - cos_phi * sin_tht * sin_psi, cos_phi * sin_tht * cos_psi + sin_phi * cos_tht * sin_psi, cos_phi * cos_tht * sin_psi - sin_phi * sin_tht * cos_psi ]) return a.flatten(); def quaternion_to_euler(quaternion): a = quaternion[0] b = quaternion[1] c = quaternion[2] d = quaternion[3] # complete the conversion # and return a numpy array of # 3 element representing the euler angles [roll, pitch, yaw] y = 2 * (a * b + c * d) x = 1 - 2 * (b * b + c * c) phi = np.arctan2(y,x) theta = np.arcsin(2 * (a * c - d * b)) y = 2 * (a*d + b*c) x = 1- 2 * (c*c + d*d) psi = np.arctan2(y,x) return np.array([phi,theta,psi]) def create_grid(data, drone_altitude, safety_distance): """ Returns a grid representation of a 2D configuration space based on given obstacle data, drone altitude and safety distance arguments. """ # minimum and maximum north coordinates north_min = np.floor(np.amin(data[:, 0] - data[:, 3])) north_max = np.ceil(np.amax(data[:, 0] + data[:, 3])) print(0, north_max - north_min) # minimum and maximum east coordinates east_min = np.floor(np.amin(data[:, 1] - data[:, 4])) east_max = np.ceil(np.amax(data[:, 1] + data[:, 4])) print(0,east_max-east_min) # given the minimum and maximum coordinates we can # calculate the size of the grid. north_size = int(np.ceil(north_max - north_min)) east_size = int(np.ceil(east_max - east_min)) # Initialize an empty grid grid = np.zeros((north_size, east_size)) # Center offset for grid north_min_center = np.min(data[:, 0]) east_min_center = np.min(data[:, 1]) # Populate the grid with obstacles for i in range(data.shape[0]): north, east, alt, d_north, d_east, d_alt = data[i, :] # TODO: Determine which cells contain obstacles # and set them to 1. # # Example: # # grid[north_coordinate, east_coordinate] = 1 nc = int(north - north_min) ec = int(east - east_min) dn = int(d_north) de = int(d_east) sd = int(safety_distance) x0 = int(ec - (de + sd)) y0 = int(nc - (dn + sd)) xm = int(ec + (de + sd)) ym = int(nc + (dn + sd)) nm = north_max - north_min em = east_max - east_min print(drone_altitude,alt,d_alt) for e in range(x0,xm): for n in range(y0,ym): # skip out of range conditions if e < 0: continue if e >= em: continue if n < 0: continue if n >= nm: continue # check if drone is above obstacle altitude if alt + d_alt + safety_distance > drone_altitude: continue # plot it grid[n][e] = 1 return grid
#!/usr/bin/env python # coding: utf-8 # ## Co-axial drone dynamics # # <img src="Drone1.png" width="300"> # # In this exercise, you will populate the ```CoaxialCopter``` class with three methods. These functions will calculate vertical acceleration $\ddot{z}$, angular acceleration $\ddot{\psi}$ along the $z$ axis and the angular velocities $\omega_1$ and $\omega_2$ of the propellers required to achieve any desired $\ddot{z}$ and $\ddot{\psi}$. # # We assume that drone only can travel and rotate along the vertical $z$ axis. # # Remember, the positive $z$ axis points downwards. # # Also notice that the first propeller rotates clockwise, while the second propeller rotates counterclockwise. # # **Reminder**: The second propeller rotates counterclockwise thus the angular velocity needs to be positive, while angular velocity of the first propeller needs to be negative as it rotates clockwise. # # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'retina'") import numpy as np import math import matplotlib.pyplot as plt import matplotlib.pylab as pylab import jdc from ExerciseAnswers import Answers pylab.rcParams['figure.figsize'] = 10, 10 # #### Helpful Equations # # $$F_z = m \ddot{z}$$ # # $$M_z = I_z \ddot{\psi}$$ # # $$ \ddot{z} = g- \frac{k_f}{m}\left( \omega_1^2 +\omega_2^2 \right) \\ # \ddot{\psi} =\frac{k_m}{I_z} (-\omega_1^2 + \omega_2^2 ) $$ # # _Hint_: # From those equations you can derive the following: # # $$ \omega_1^2 = \frac{m}{k_f} (g-\ddot{z}) - \omega_2^2 $$ # # $$ \omega_2^2 = \frac{I_z}{k_m} \ddot{\psi} + \omega_1^2 $$ # # and replacing the omega_squared variables in the two equations leads to: # # $$ \omega_1^2 =\frac{1}{2}\frac{m}{k_f} (g-\ddot{z}) - \frac{1}{2}\frac{I_z}{k_m} \ddot{\psi} $$ # # $$ \omega_2^2 =\frac{1}{2}\frac{m}{k_f} (g-\ddot{z}) + \frac{1}{2}\frac{I_z}{k_m} \ddot{\psi} $$ # # $$ $$ # $$ $$ # _Note_: In the notebook we will refer to # $ \ddot{\psi} $ as angular_acceleration and # $\ddot{z}$ as linear_acceleration # In[18]: class CoaxialCopter: def __init__(self, k_f = 0.1, # value of the thrust coefficient k_m = 0.1, # value of the angular torque coefficient m = 0.5, # mass of the vehicle i_z = 0.2, # moment of inertia around the z-axis ): self.k_f = k_f self.k_m = k_m self.m = m self.i_z = i_z self.omega_1 = 0.0 self.omega_2 = 0.0 self.g = 9.81 self.z = 0.0 self.z_dot = 0.0 self.psi = 0.0 self.psi_dot = 0.0 self.y = 0.0 self.y_dot = 0.0 @property def z_dot_dot(self): """Calculates current vertical acceleration.""" # TODO: # 1. Calculate the lift force generated by the first # and second propellers # 2. Calculate the total vertical force acting on the drone # 3. Calculate the vertical acceleration due to the # total force acting on the drone keep in mind that the # z-axis is directed downward acceleration = self.g - (self.k_f / self.m) * (self.omega_1**2 + self.omega_2**2) return acceleration @property def psi_dot_dot(self): """Calculates current rotational acceleration.""" # TODO: # 1. Calculate the torques generated by both propellers # 2. Calculate the angular acceleration # clocksize M1 = self.k_m * self.omega_1**2 P1 = M1 / self.i_z # counter clocksize| M2 = self.k_m * self.omega_2**2 P2 = -M2 / self.i_z angular_acc = P1 + P2 return angular_acc def set_rotors_angular_velocities(self, linear_acc, angular_acc): """ Sets the turn rates for the rotors so that the drone achieves the desired linear_acc and angular_acc. """ # TODO # 1. Calculate the correct values of omega_1 and omega_2 # 2. Set self.omega_1 and self.omega_2 to those values # 3. Don't forget to return omega_1, omega_2 # Reminder: The second propeller rotates counterclockwise # thus the angular velocity needs to be positive, # while angular velocity of the first propeller needs to be # negative as it rotates clockwise. self.omega_1 = -1.0 * np.sqrt(0.5 * (self.m / self.k_f) * (self.g - linear_acc) - 0.5 * (self.i_z / self.k_m * angular_acc)) self.omega_2 = -self.omega_1 return self.omega_1, self.omega_2 def advance_state_uncontrolled(self,dt): # update z_dot z_dot_dot = self.g delta_z_dot = z_dot_dot * dt self.z_dot = self.z_dot + delta_z_dot # update y_dot y_dot_dot = 0.0 delta_y_dot = y_dot_dot * dt self.y_dot = self.y_dot + delta_y_dot def advance_state(self,dt): # # TODO # Implement this method! Your implementation may look # VERY similar to the uncontrolled version of this function. # update z_dot z_dot_dot = self.g delta_z_dot = z_dot_dot * dt self.X[3] += delta_z_dot # update y_dot y_dot_dot = 0.0 delta_y_dot = y_dot_dot * dt self.X[4] += delta_y_dot delta_X = np.array([self.X[3], self.X[4], 0.0, 0.0, 0.0, 0.0]) * dt self.X += delta_X # In[19]: # TEST CODE 1 bi = CoaxialCopter() stable_omega_1,stable_omega_2 = bi.set_rotors_angular_velocities(0.0, 0.0) print('Drone achieves stable hover with angular velocity of %5.2f' % stable_omega_1, 'for the first propeller and %5.2f' % stable_omega_2, 'for the second propeller.') Answers.angular_velocities(bi.m, bi.g, bi.i_z, bi.k_f, bi.k_m, 0.0, 0.0, stable_omega_1, stable_omega_2) # In[20]: # TEST CODE 2 - Checking the linear acceleration value bi.omega_1 = stable_omega_1 * math.sqrt(1.1) bi.omega_2 = stable_omega_2 * math.sqrt(1.1) vertical_acceleration = bi.z_dot_dot print('Increase by %5.2f' % math.sqrt(1.1), 'of the propeller angular velocity will result in', '%5.2f' % vertical_acceleration, 'm/(s*s) vertical acceleration.' ) Answers.linear_acceleration(bi.m, bi.g, bi.k_f, bi.omega_1, bi.omega_2, vertical_acceleration) # In[21]: # TEST CODE 3 - checking the angular acceleration bi.omega_1 = stable_omega_1 * math.sqrt(1.1) bi.omega_2 = stable_omega_2 * math.sqrt(0.9) ang_acceleration = bi.psi_dot_dot print('Increase in %5.2f'%math.sqrt(1.1),' of the angular velocity for the first propellr and', ' decrease of the angular velocity of the second propellr by %f.2f'%math.sqrt(0.9),' will result in', '%5.2f'%ang_acceleration, 'rad/(s*s) angular acceleration.' ) Answers.angular_acceleration(bi.i_z, bi.k_m, bi.omega_1, bi.omega_2, ang_acceleration) # [Solution](/notebooks/1.%20Coaxial%20Drone%20Dynamics%20SOLUTION.ipynb) # In[ ]: class Drone2D: def __init__(self, k_f=0.1, # value of the thrust coefficient I_x=0.1, # moment of inertia around the x-axis m=1.0, # mass of the vehicle l=0.5, # distance between the center of # mass and the propeller axis ): self.k_f = k_f self.I_x = I_x self.l = l self.m = m self.omega_1 = 0.0 self.omega_2 = 0.0 self.g = 9.81 # z, y, phi, z_dot, y_dot, phi_dot self.X = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) def advance_state_uncontrolled(self, dt): """Advances the state of the drone by dt seconds. Note that this method assumes zero rotational speed for both propellers.""" X_dot = np.array([ self.X[3], self.X[4], self.X[5], self.g, 0.0, 0.0]) # Change in state will be self.X = self.X + X_dot * dt return self.X # NOTE - this is a new helper function which you may find useful def get_thrust_and_moment(self): """Helper function which calculates and returns the collective thrust and the moment about the X axis""" f1 = self.k_f * self.omega_1 ** 2 f2 = self.k_f * self.omega_2 ** 2 # c is often used to indicate "collective" thrust c = f1 + f2 M_x = (f1 - f2) * self.l return c, M_x ################################## # BEGIN TODOS #################### @property def z_dot_dot(self): """Calculates vertical (z) acceleration of drone.""" # TODO 1 # Calculate the vertical component of the acceleration # You might find get_thrust_and_moment helpful c, M = self.get_thrust_and_moment() return self.g - c * np.cos(self.X[2]) @property def y_dot_dot(self): """Calculates lateral (y) acceleration of drone.""" # TODO 2 # Calculate the horizontal component of the acceleration c, M = self.get_thrust_and_moment() return c * np.sin(self.X[2]) @property def phi_dot_dot(self): # TODO 3 # Calculate the angular acceleration about the x-axis. c, M = self.get_thrust_and_moment() return M / self.I_x
#listbox ==> A listing of selectable text items within it's own container from tkinter import * def submit(): food = [] for index in my_box.curselection(): food.insert(index,my_box.get(index)) print("You have ordered: ") for index in food: print(index) def add(): my_box.insert(my_box.size(), entry_box.get()) my_box.config(height=my_box.size()) def delete(): for index in reversed(my_box.curselection()): my_box.delete(index) my_box.config(height=my_box.size()) window = Tk() my_box = Listbox(window, bg="#f7ffde", font=('Constantia', 20), width=12, selectmode=MULTIPLE, ) my_box.pack() my_box.insert(1, 'pizza') my_box.insert(2, 'hamburger') my_box.insert(3, 'hotdog') my_box.insert(4, 'samosa') my_box.insert(5, 'sausage') my_box.config(height=my_box.size()) entry_box = Entry(window) entry_box.pack() button = Button(window, text="Submit", font=('Consolas', 12), command=submit) button.pack() add_button = Button(window, text="Add", font=('Consolas', 12), command=add) add_button.pack() delete_button = Button(window, text="Delete", font=('Consolas', 12), command=delete) delete_button.pack() window.mainloop()
# *args ==> is a parameter that will pack all arguments into a tuple # useful so that a function can accept a varying amount of arguments def add(*addition): sum = 0 addition = list(addition) addition[1] = 10 for i in addition: sum += i return sum print(add(1, 7, 8, 8,66, 76))
from tkinter import * from tkinter import messagebox #This imports message box library def click(): #messagebox.showinfo(title="messagebox", message="Successfully installed Virus") #messagebox.showwarning(title="Warning", message="Virus in your PC!!!") #messagebox.showerror(title="error", message="something went wrong") """if messagebox.askokcancel(title="Ask ok cancel", message="Leave Page!"): print("page left :(") else: print("Page running")""" #*********************************************************************************************** """if messagebox.askretrycancel(title="Ask retry cancel", message="loading failed! \nRetry?"): messagebox.showinfo(title='load retry', message="retrying...") else: messagebox.showerror(title='error', message="Loading Cancelled")""" #******************************************************************************************* """if messagebox.askyesno(title='user response', message="Do you have a girl?"): messagebox.showinfo(title='$$', message="Congratulations") else: messagebox.showerror(title='**', message="Quit bitching and look for one!!")""" #***************************************************************************************** """response = messagebox.askquestion(title='ask question', message='Do you like fish?') if(response == 'yes'): messagebox.showinfo(title='response', message="You're a real african person") else: messagebox.showerror(title='error', message="Why are you even in Africa!?")""" #******************************************************************************************** answer = messagebox.askyesnocancel(title="mandatory question", message="Do you love coding?") if(answer == True): messagebox.showinfo(title='response', message="You're a computer nerd") elif(answer == False): messagebox.showinfo(title='response', message="Start loving it!!") else: messagebox.showerror(title='response', message="What are you even doing here!?") window = Tk() button = Button(window, text="Click Here", command=click) button.pack() window.mainloop()
"""A variable is a container for a value. It behaves as the value that it contains""" #VARIABLES #strings => they store a series of characters first_name = "Marcus" last_name = "Ogutu" full_name = first_name + " "+ last_name print("Hey "+ full_name) #Integers => they are data types of numeric value that can only store whole numbers with no decimal portion age = 21 age += 1 print("Your age is: "+ str(age)) #FLOATS #A float data type is a numeric value that can strore a number that includes a decimal portion height = 252.6 print("Your height is: "+str(height)+" centimeters") #BOOLEAN => they can only contain two logical statements; True or False human = True print("Are you a human? "+ str(human))
"""slicing => is the creating of a sub string by extracting elements from another string index[] or slice() start:stop:step""" #INDEXING name = "Smart Developer" first_name = name[:5] last_name = name[5:15] funcky_name = name[::1] reversed_name = name[::-1] #print(reversed_name) #SLICING website1 = "www.itaxKenya.com" website2 = "www.myPortfolio.com" slicing = slice(4, -4) print(website1[slicing]) print(website2[slicing])
#canvas => widget that is used to draw graphs, plots, images in a window from tkinter import * window = Tk() canvas = Canvas(window, height=500, width=500) """blue_line = canvas.create_line(0,0,500,500, fill="blue", width=5) red_line = canvas.create_line(0,500,500,0, fill="red", width=5) rectangle = canvas.create_rectangle(50,50,250,250, fill="purple") coordinates = [250,0, 500,500, 0,500] triangle = canvas.create_polygon(coordinates, fill="DodgerBlue", outline="black", width=2) canvas.create_arc(0,0,500,500, fill="DodgerBlue", outline="black", width=2, style=PIESLICE, start=120, extent=180)""" canvas.create_arc(0,0,500,500,fill="red", extent=180, width=10) canvas.create_arc(0,0,500,500,fill="white", extent=180, start=180, width=10) canvas.create_oval(190,190,310,310, fill="white", width=10) canvas.pack() window.mainloop()
from tkinter import * count = 0 def display(): if(x.get()==1): global count count += 1 print(count) else: print("You don't Agree :(") window = Tk() x= IntVar() check_button = Checkbutton(window, text="Check it", variable=x, onvalue=1, offvalue=0, command=display, font=('Arial', 15), fg="#00FF00", bg="black", activeforeground="#00FF00", activebackground="black", padx=25, pady=10) check_button.pack() window.mainloop()
#! python 3 from icalendar import Calendar import os import shutil class Module(): def __init__(self, modCode, modName): self.code = modCode self.name = modName self.lessons = [] def createYearDir(dirArr): yearNum = len(dirArr) + 1 os.makedirs(f'Year {yearNum}', exist_ok=True) dirArr.append(f'Year {yearNum}') print(f'Made a Year {yearNum} Directory') def createEmptySem(root): # Gets all the Year directories in root dirArr = sorted([i for i in os.listdir(root) if (os.path.isdir(i) and 'Year' in i)]) print(dirArr) # If there are no year directories if not (dirArr): createYearDir(dirArr) for yrDir in dirArr: # Checks current year if semester directories exist semDir = os.listdir(yrDir) if len(semDir)< 2: newSemDir = os.path.join('.',yrDir,f'Sem {len(semDir)+1}') os.makedirs(newSemDir) print(f'Make module directories in {newSemDir}') return newSemDir # Both semester directories are in else: # Walks down the year directories and check if they are not empty for dirPath, dirNames, _ in sorted(os.walk(yrDir)): # If a semester directory is empty, setup module directories in there if 'Sem' in os.path.basename(dirPath) and not(dirNames): print(f'Make module directories in {dirPath}') return newSemDir else: # All semester directories have modules, create a new year directory createYearDir(dirArr) # TODO: Probably change the input in future FILE_PATH = 'nusmods_calendar.ics' MOD_DICT = {} ROOT_DIR = os.getcwd() with open(FILE_PATH, 'rb') as calFile: cal = Calendar.from_ical(calFile.read()) # Gather the module information from the ical file for comp in cal.walk(): if comp.name == "VEVENT": # Returns [ Module Code, Lesson Type] summary = comp.get('summary').split(' ') # Returns [ Module Name, Tutorial Group] desc = comp.get('description').split('\n') modCode, modName, lessonType = summary[0], desc[0], ' '.join(summary[1:]) # If the module is not registered yet if not(modCode in MOD_DICT.keys()): MOD_DICT[modCode] = Module(modCode, modName) # If the lesson is not registered yet if not(lessonType in MOD_DICT[modCode].lessons): MOD_DICT[modCode].lessons.append(lessonType) targetSem = createEmptySem(ROOT_DIR) # Creating the module directories for key in MOD_DICT.keys(): os.makedirs(os.path.join(targetSem,key)) # Creating the subdirectories for each module for dirPath, dirNames, fileNames in os.walk(targetSem): mod = os.path.basename(dirPath) # Checks if the directory is the module if not(mod in MOD_DICT.keys()): continue # Creates a directory for each lesson type [os.makedirs(os.path.join(dirPath, lesson)) for lesson in MOD_DICT[mod].lessons]
from time import gmtime, strftime def time_helper(): """ Get the current time :return: formatted time string """ curr_time = strftime("%H:%M", gmtime()) return curr_time def date_helper(): """ Get the current date :return: formatted date string """ curr_date = strftime("%m-%d-%Y", gmtime()) return curr_date if __name__ == "__main__": time_helper() date_helper()
import time import asyncio import cozmo from cozmo.util import degrees, distance_mm, speed_mmps, Pose def say_text(robot: cozmo.robot.Robot): print("Saying text") x = input("What do you want cozmo to say?") robot.say_text(x).wait_for_completed() def drive_straight(robot: cozmo.robot.Robot): print("Driving straight") distance = int(input("Distance: ")) speed = int(input("Speed: ")) robot.drive_straight(distance_mm(distance), speed_mmps(speed)).wait_for_completed() def turn_in_place(robot: cozmo.robot.Robot): print("Turning in place") degrees_ = int(input("Degrees: ")) robot.turn_in_place(degrees(degrees_)).wait_for_completed() def drive_in_square(robot: cozmo.robot.Robot): print("Driving in square") # Use a "for loop" to repeat the indented code 4 times # Note: the _ variable name can be used when you don't need the value for _ in range(4): robot.drive_straight(distance_mm(150), speed_mmps(50)).wait_for_completed() robot.turn_in_place(degrees(90)).wait_for_completed() def move_head_(robot: cozmo.robot.Robot): print("Moving head") radiansps = input("Radians per second: ") robot.move_head(radiansps) time.sleep(9) def move_lift_(robot: cozmo.robot.Robot): print("Moving lift") radiansps = input("Radians per second: ") robot.move_lift(radiansps) time.sleep(3) def drive_wheels_(robot: cozmo.robot.Robot): print("Driving wheels motors") leftwheelspeed = input("Left wheel speed: ") rightwheelspeed = input("Right wheel speed: ") robot.drive_wheels(leftwheelspeed, rightwheelspeed) time.sleep(9) def roomcreation(robot: cozmo.robot.Robot): cubesize = 50 initialPosition = 0 origin1 = robot.world.create_custom_fixed_object(Pose(-100, initialPosition - cubesize, 0, angle_z=degrees(0)), cubesize, cubesize, cubesize, relative_to_robot=True) origin2 = robot.world.create_custom_fixed_object(Pose(-100, 0, initialPosition, angle_z=degrees(0)), cubesize, cubesize, cubesize, relative_to_robot=True) origin3 = robot.world.create_custom_fixed_object(Pose(-100, initialPosition + cubesize, 0, angle_z=degrees(0)), cubesize, cubesize, cubesize, relative_to_robot=True) ''' target1 = robot.world.create_custom_fixed_object(Pose(-300, initialPosition-100, 0, angle_z=degrees(0)), 100, 100, 100, relative_to_robot=True) target2 = robot.world.create_custom_fixed_object(Pose(-300, initialPosition, 0, angle_z=degrees(0)), 100, 100, 100, relative_to_robot=True) target3 = robot.world.create_custom_fixed_object(Pose(-300, initialPosition+100 , 0, angle_z=degrees(0)), 100, 100, 100, relative_to_robot=True) ''' if origin1 and origin2 and origin3: print("Created origins succesfully") # robot.go_to_pose(Pose(100, 0, 0, angle_z=degrees(180)), relative_to_robot=True).wait_for_completed() ''' if target1 and target2 and target3: print("Created targets succesfully") #robot.go_to_pose(Pose(300, 0, 0, angle_z=degrees(180)), relative_to_robot=True).wait_for_completed() ''' robot.go_to_pose(Pose(-100, 0, 0, angle_z=degrees(0)), relative_to_robot=True).wait_for_completed() robot.move_lift(3) time.sleep(5) robot.go_to_pose(Pose(-100, 0, 0, angle_z=degrees(180)), relative_to_robot=True).wait_for_completed() robot.move_lift(-3) time.sleep(5) ########################################## # program = say_text # program = drive_straight # program = turn_in_place # program = drive_in_square # program = move_head_ # program = move_lift_ # program = drive_wheels_ # program = roomcreation, use_3d_viewer=True ########################################## cozmo.run_program(roomcreation, use_3d_viewer=True)
def max(x, y): if x <= y: return y else: return x def max1(x, y): return y if x <= y else x def max2(x, y, z): return z if max1(x, y) <= z else max1(x, y)
from typing import Tuple, List import math import numpy as np def distance_min(state): """input: state output: la distance minimal entre un de nos groupes et les groupes ennemies""" distances = [] groups = [None, None] for position_nous in state.our_species.tile_coordinates(): distance_cette_unité = math.inf for position_ennemie in state.enemy_species.tile_coordinates(): if distance(position_ennemie, position_nous) < distance_cette_unité: distance_cette_unité = distance(position_ennemie, position_nous) groups[0] = position_nous groups[1] = position_ennemie distances.append(distance_cette_unité) return min(distances), groups def win_probability(attack_troops: int, defense_troops: int, defense_type: int) -> float: """ Return the probability of attacking troops winning a battle :param attack_troops: :param defense_troops: :param defense_type: :return: """ if defense_type == 1: if attack_troops >= defense_troops: return 1 else: return random_battle_win_probability(attack_troops, defense_troops) else: if attack_troops >= 1.5 * defense_troops: return 1 elif defense_troops >= 1.5 * attack_troops: return 0 else: return random_battle_win_probability(attack_troops, defense_troops) def random_battle_win_probability(species_1_units: int, species_2_units: int) -> float: """ Given the number of units, measures the probability that species 1 wins. :param species_1_units: int, number of units of species 1 :param species_2_units: int, number of units of species 2 :return: float, probability that species 1 wins """ if species_1_units <= species_2_units: p = species_1_units / (2 * species_2_units) else: p = species_1_units / species_2_units - .5 return p def expected_battle_outcome(attacking_species_units: int, defending_species_type: int, defending_species_units: int) -> int: """ Returns the expected number of attacking species units to result from battle, note that this is not a simulation. :param attacking_species_units: int, number of units of attacking species :param defending_species_units: int, number of units of defending species :param defending_species_type: int, can be any species (1, 2, 3) :return: int """ expected_outcome = 0 # True if the battle is not an outright win if ((defending_species_units == 1) & (attacking_species_units < defending_species_units)) | ( (defending_species_units != 1) & (attacking_species_units < 1.5 * defending_species_units)): probability_of_winning = random_battle_win_probability(attacking_species_units, defending_species_units) expected_outcome += int(probability_of_winning * attacking_species_units) # Under estimate # If losers are humans, every one of them has a probability of being transformed. if defending_species_type == 1: expected_outcome += int(probability_of_winning * defending_species_units) # Under estimate # If it is an outright win else: expected_outcome += (attacking_species_units >= defending_species_units) * attacking_species_units if defending_species_type == 1: expected_outcome += defending_species_units return expected_outcome def distance(square_1: Tuple[int, int], square_2: Tuple[int, int]) -> int: """ Returns the distance in number of moves between 2 squares :param square_1: tuple, square 1 coordinates :param square_2: tuple, square 2 coordinates :return: int, distance between squares """ return max(abs(square_1[0] - square_2[0]), abs(square_1[1] - square_2[1])) def battle_simulation(species_1_units: int, species_1_type: int, species_2_units: int, species_2_type: int) -> Tuple[int, int]: """ Simulates a battle between two species :param species_1_units: int, number of units of species 1 :param species_1_type: int, species 1 type :param species_2_units: int, number of units of species 2 :param species_2_type: int, species 2 type :return: tuple, battle outcome, winning species type and number of remaining units """ if ((species_2_type == 1) and (species_1_units < species_2_units)) or ((species_2_type != 1) and ( species_1_units < 1.5 * species_2_units) and species_2_units < 1.5 * species_1_units): p = random_battle_win_probability(species_1_units, species_2_units) # If species 1 wins if p >= np.random.random(): # Every winner's unit has a probability p of surviving. winner = species_1_type remaining_units = np.random.binomial(species_1_units, p) if species_2_type == 1: # If losers are humans, every one of them has a probability p of being transformed. remaining_units += np.random.binomial(species_2_units, p) # If species 2 wins else: winner = species_2_type # Every winner's unit has a probability 1-p of surviving remaining_units = np.random.binomial(species_2_units, 1 - p) else: winner = species_1_type if species_1_units >= species_2_units else species_2_type if winner == species_1_type: remaining_units = species_1_units + (species_2_type == 1) * species_2_units else: remaining_units = species_2_units return winner, remaining_units def species_coordinates(state, species: int) -> List[Tuple[int, int]]: """ Returns a list of coordinates of all the squares occupied by a given species :param state: The current state object :param species: The species to look for :return: """ return list(zip(*np.where(state.board[:, :, 0] == species))) def ordered_board_content_for_given_coordinates(state, coordinate_list: List[Tuple[int, int]] ) -> List[Tuple[int, int, int, int]]: """ Returns the contents of the squares given a list of coordinates :param state: The current state object :param coordinate_list: List of coordinates :return: List of tuples containing square contents, the format is [x, y, species type, unit count] ordered by count """ contents = [] if len(coordinate_list) == 0: return contents for coordinates in coordinate_list: temp = [coordinates[0], coordinates[1]] temp.extend(state.board[coordinates[0], coordinates[1]]) contents.append(temp) contents = np.array(contents) contents = contents[contents[:, -1].argsort()] return contents def hash_array(array: np.ndarray) -> int: return array.tobytes()
import random # Give an S element, find the first 2 elements in a list where the sum is the same as S, return True or false and + # + the index's # Ex: S = 8 # list = [1, 2, 4, 4] # 4 + 4 = 8 so, result = True, index 2 and index 3 # Ex2: S= 8 # list = [1,2,3,9] # result = False, index -1 and index -1 #return bool, index 0 and index 1 def find(S, randomlist): sumlist = [] sumlist.append(S-randomlist[0]) for index,val in enumerate(randomlist): if index > 0: if val in sumlist: return (True,sumlist.index(val),index) else: sumlist.append(S-val) return (False,-1,-1) if __name__ == '__main__': randomlist = random.sample(range(0,100),100) S=random.randint(0,200) print('list:',randomlist) result,ix0,ix1 = find(S,randomlist) print('sum:',S) print('result',result) print('index 0:',ix0) print('index 1:',ix1)
#7.5 show row space and column space to be equivalent from triangular import * from GF2 import * from matutil import * from solver import solve from The_Basis_problems import * from independence import * from vecutil import * """A [120] [021] row space == [1,0][0,1] column space == [1,0][0,1] row space == column space therefore they have the same span and both span R2 B [1400] [0220] [0011] row space == [140][020][001] column space == [100][420][001] rank rs == rank cs because both are bases therefore linearly indpendent therefore not superfluous. definition of row rank is rank of basis of rows C [1] [2] [3] row basis == [1] column basis == [1] this is a point, I think""" #6.7.5 def morph(S, B): """procedure that morphs one set into another using the exchange lemma""" #6.7.6 def my_is_independent(L): """procedure that uses rank to test whether or not a set is indpendent using the concept of rank. The idea here is that a basis for any Span must have rank == that span. E.g. a basis for r3 is 001 010 100. All bases are the same size, so any basis for R3 will have rank 3. Thus, if the length of a se of vectors is > it's rank, there must be a linear dependency.""" return rank(L) == len(L) L = [list2vec(l) for l in [[2,4,0],[4,5,6],[0,0,7]]] print(my_is_independent(L)) #6.7.7 def my_rank(L): """uses subset basis to find a basis for L, then finds the length of that basis. Because all bases are the same size, we can know dimension L and therefore rank L""" return len(subset_basis(L)) L = [list2vec(l) for l in [[1,2,3],[4,5,6],[1.1,1.1,1.1]]] print(my_rank(L)) #6.7.8 prove that if a vector space has dimension N then N+1 of it's vectors are linearly dependent. """let V be a vector space of dimension N and S be a basis for V. By the morphing lemma, a set of linearly independent vectors contained in the generators for V will have at most |generators|. By theorem 6.1.3, the smallest set of generators must be a basis. By proposition 6.2.4, rank S (the dimension of the vector space V) <= |S|. So, dim V == dim S == N All bases have the same size (rank N), and by definition span the entire vector space V. Therefore, any additional vector added to S already exists in the span, and by the definition of linear dependence is linearly dependent. Any such vector added to S would bring make rank S == N+1. All of S in contained in V, therefore this holds for V as well as S""" #6.7.9 def is_solution(A, x, b): residual = b - A * x if residual * residual <= 10**-14: return True else: return False def direct_sum_decompose(U_basis, V_basis, w): """finds the u in U and v in V that were added to create the vector w in the direct sum uses the fact that U_basis union V_basis is a basis for V direct sum U """ U_V_basis = U_basis + V_basis A = coldict2mat(U_V_basis) u_plus_v = solve(A,w) print(u_plus_v) print(list(u_plus_v.D)) if not is_solution(A,u_plus_v, w): return "not a solution" else: print(A*u_plus_v) list_D = list(u_plus_v.D) u_D = set(list_D[:len(U_basis)]) v_D = set(list_D[:len(V_basis)]) print(u_D, v_D) u_coeffs = Vec((u_D),{k:u_plus_v.f[k] for k in u_D}) v_coeffs = Vec(v_D,{k:u_plus_v.f[k+len(u_D)] for k in v_D}) print(u_coeffs, v_coeffs) u = coldict2mat(U_basis) * u_coeffs v = coldict2mat(V_basis) * v_coeffs return [u, v] #running into some very weird rounding errors here, but theory is correct. U_basis = [list2vec(l) for l in [[2,1,0,0,6,0],[11,5,0,0,1,0],[3,1.5, 0,0,7.5,0]]] V_basis = [list2vec(l) for l in [[0,0,7,0,0,1],[0,0,15,0,0,2]]] print(direct_sum_decompose(U_basis, V_basis, list2vec([2,5,0,0,1,0]))) #6.7.10 def is_invertible(M): """tests to see if a matrix is invertible based on the criteria that it's square and that the columns are linearly independent. Implied is that the rows are also linearly independent""" cols = mat2coldict(M) rows = mat2rowdict(M) col_vals = [vec for vec in cols.values()] return len(cols) == len(rows) and my_is_independent(col_vals) m1 = listlist2mat([[1,2,3],[3,1,1]]) m2 = listlist2mat([[1,0,1,0],[0,2,1,0],[0,0,3,1],[0,0,0,4]]) print(is_invertible(m2)) #6.7.13 def find_inverse(GF2_M): """finds the inverse of a matrix over GF2, using the fact that a matrix * it's inverse is the identity matrix""" assert is_invertible(GF2_M) == True cols = mat2coldict(GF2_M) b_list = [Vec({i for i in range(len(cols))},{i:one}) for i in range(len(cols))] print(b_list) inverse_vecs = [solve(GF2_M, b) for (col, b) in zip( cols,b_list)] inverse = coldict2mat(inverse_vecs) identity = GF2_M * inverse return inverse, identity mat = listlist2mat([[0,one,0],[one, 0,0],[0,0,one]]) print(find_inverse(mat)) #6.7.14 def find_triangular_matrix_inverse(A): """uses the fact that A * A ^-1 is the identity matrix""" rows = [row for row in mat2rowdict(A).values()] labels = {d for d in range(len(rows))} b = Vec(labels, {i:1 for i in labels}) new_b = [Vec({i for i in range(len(rows))},{i:1}) for i in range(len(rows))] print(rows, 'rows',list(labels), b) result = [triangular_solve(rows, list(labels), b) for b in new_b] print(result) res_A = coldict2mat(result) print(res_A*A) A = listlist2mat([[1, .5, .2, 4], [0, 1,.3 ,.9], [0, 0, 1, .1 ], [0,0,0,1]]) print(find_triangular_matrix_inverse(A))
import sqlite3 # Read in Data from table, row def read_data(table, row): db = sqlite3.connect('database.sqlite') cursor = db.cursor() cursor.execute("SELECT " + row + " FROM " + table) return cursor.fetchall() # Reads in Data from table,row, with an id def read_id(table, row, id): db = sqlite3.connect('database.sqlite') cursor = db.cursor() cursor.execute("SELECT " + row + " FROM " + table + " WHERE player_api_id= " + id + " ") return cursor.fetchall() def stats_from_id(player_IDs, needed_stats, standard_values): """ # Reads in the stats of the players player_ID needs to be an list of player_ID's, for example by calling "read_data("Match", "home_player_1")[:1000]" needed_stats are the player stats that you want to extract standard_values are the standard values that will be used if the ID equals None, and needs to be in brackets [] """ api_id = read_data("Player_Attributes", "player_api_id, " + needed_stats) p1_ratings = [] # For every player id for item in player_IDs: # Parse in some value if None, else parse in the player stat retrieved from Player_attributes if item[0] is None: p1_ratings.append(standard_values) else: for player in api_id: if item[0] == player[0]: p1_ratings.append(list(player[1:])) break return p1_ratings # Some old code that might be useful sometime # def stat_from_id(player_IDs, needed_stat, standard_value): # api_id = read_data("Player_Attributes", "player_api_id, " + needed_stat) # # # Make sure the overall rating of every player is available, if the player ID is NONE, a custom value is parsed in. # p1_rating = [] # #for every player 1 of a match # for item in player_IDs: # # Parse in some value if None, else parse in the player strength # if item[0] is None: # p1_rating.append([standard_value]) # else: # for i in range(len(api_id)): # # if item[0] == api_id[i][0]: # #print("found!") # p1_rating.append([api_id[i][1]]) # # break # return p1_rating
def square(x): return x*x print square(10) #You can pass functions around as parameters def dosomething(f, x): return f(x) print dosomething(square, 3) print dosomething(lambda x : x*x*x, 3) #lambda = none function, so we make new function
from typing import Tuple, List import tp6 def my_function_tuple() -> Tuple[int ,int]: return 0, 10 x, y = my_function_tuple() print(x, y) def min_max_avg(l: List[float]) -> Tuple[float, float, float]: min = l[0] max = l[0] sum = 0 for val in l: sum += val if val < min: min = val if val > max: max = val return min, max, sum / len(l) # TP # Créer la fonction min_max_avg(l: List[float]) -> Tuple[float, float, float]
#! usr/bin/python3 """ Construct a function that finds the missing value between two lists. """ from functools import reduce def reverse_list(x): i = 0 j = len(x)-1 # completes in O(n) time while (i < j): x[i],x[j] = x[j],x[i] i += 1 j -= 1 return ''.join(x) def reverse_python(x): output = [''] * len(x) for i,c in enumerate(x): output[-1*(i+1)] = c return ''.join(output) def reverse(x): output = ['']*len(x) i = len(x) - 1 for c in x: output[i] = c i -= 1 return ''.join(output) def find_missing(arr1, arr2): """ Assume that arr2 has more elements than arr1 and that there is exactly one element missing. Brute force is search for each element in arr1 inside of arr2. This takes O(mn) time where m is length of arr1 and n is length of arr2. Pythonic: return set(arr2) - set(arr1) really Add all the numbers in both and then substracting the two is another one. However, this can potentially result in a very large number. Using XOR... <https://stackoverflow.com/questions/45747177/xor-to-find-the-missing-element-between-two-lists> - number ^ number = 0 always - number ^ 0 = number - order of operations does not matter """ s = 0; # this never gets above the missing integer for i in arr1: s ^= i for j in arr2: s ^= j return s def find_missing_item_pythonicly(arr1,arr2): """Do it in one line!""" return reduce(lambda x,y: x^y, arr1) ^ reduce(lambda x,y: x^y, arr2); def find_missing_pair(arr1,arr2): """ Find two missing values between the arrays. """ s = sum(arr1) - sum(arr2) # this could be large print(s) # Now I search through arr2 to find the two numbers that sum up to s # This can be done with hash maps resulting O(2n) = O(n) time d = {} for v in arr1: if v not in d: d[s-v] = v ret = () for v in arr1: if v in d and d.get(v,-1) != v: ret = (v,d[v]) return ret if __name__ == "__main__": # first question was to implement a reversed array #print(reverse('too bad i hid a boot')) #print(find_missing([1,2,3,4,5,6,7],[3,7,2,1,4,5])) #print(find_missing_pair([1,2,3,4,5,6,7,8],[3,7,2,1,4,5])) print(find_missing_item_pythonicly([1,2,3,4,5,6,7],[3,2,1,4,5,6]))
#! usr/bin/env python3 def waterArea(heights): max_height = float('-inf') max_i = -1 valleys = [] last_valley_i = -1 running_area = 0 for i,current_height in enumerate(heights): if current_height >= max_height and current_height != 0: # >=? # if we haven't initialized yet, set it and continue if max_height == float('-inf') and max_i == -1: max_height = current_height max_i = i continue # we perform a calculation of the area minus past issues calc_width = i - max_i - 1 calc_height = max_height # we want the "current" max height valley_subtraction = sum(valleys) # all are width 1 so 1xheight added up running_area += calc_width*calc_height - valley_subtraction valleys = [] max_height = current_height max_i = i elif len(valleys) > 1 and current_height < valleys[-1]: # if I have valleys and my new valley is smaller than my last valley # calculate against the last valley and up until that point calc_width = last_valley_i - max_i - 1 calc_height = valleys[-1] valley_subtraction = sum(valleys[:-1]) running_area += calc_width*calc_height - valley_subtraction # set the new max height to the last valley, add the new point to # valleys, empty everything else max_height = valleys[-1] max_i = last_valley_i valleys = [current_height] last_valley_i = i elif current_height < max_height and current_height != 0: # if we're at a non-zero point, the result is a valley valleys.append(current_height) last_valley_i = i elif current_height < 0: # apparently we can have subterranean walls -- does this matter? pass if valleys and last_valley_i != i: calc_width = last_valley_i - max_i - 1 calc_height = min(max_height, valleys[-1]) valley_subtraction = sum(valleys[:-1]) running_area += calc_width*calc_height - valley_subtraction return running_area def waterArea(heights): max_height = float('-inf') max_i = -1 valleys = [] # will hold tuples of (index,height) running_area = 0 for i,current_height in enumerate(heights): if current_height >= max_height and current_height != 0: # >=? # if we haven't initialized yet, set it and continue if max_height == float('-inf') and max_i == -1: max_height = current_height max_i = i continue # we perform a calculation of the area minus past issues calc_width = i - max_i - 1 calc_height = max_height # we want the "current" max height valley_subtraction = sum(x[1] for x in valleys) # all are width 1 so 1xheight added up running_area += calc_width*calc_height - valley_subtraction valleys = [] max_height = current_height max_i = i elif current_height < max_height and current_height != 0: # if we're at a non-zero point, the result is a valley valleys.append((i,current_height)) print(valleys) if valleys and max(x[1] for x in valleys) == valleys[-1][1]: # if we have valleys and our last valley was the greatest last_valley_i, last_valley_height = valleys[-1] calc_width = last_valley_i - max_i - 1 calc_height = min(max_height, last_valley_height) valley_subtraction = sum(x[1] for x in valleys) running_area += calc_width*calc_height - valley_subtraction return running_area def waterArea2(heights): maxes = [0 for _ in heights] # iterate finding the maxes from the left to right as out default fill leftMax = 0 for i,height in enumerate(heights): maxes[i] = leftMax leftMax = max(leftMax, height) # iterate finding the heights from right to left, subtracting for when we # find points lower than our total fill rightMax = 0 for i,height in reversed(list(enumerate(heights))): minHeight = min(rightMax, maxes[i]) if height < minHeight: maxes[i] = minHeight - height else: maxes[i] = 0 rightMax = max(rightMax, height) print(maxes) return sum(maxes) def waterArea(heights): maxes = [0 for x in heights] leftMax = 0 for i in range(len(heights)): height = heights[i] maxes[i] = leftMax leftMax = max(leftMax, height) rightMax = 0 for i in reversed(range(len(heights))): height = heights[i] minHeight = min(rightMax, maxes[i]) if height < minHeight: maxes[i] = minHeight - height else: maxes[i] = 0 rightMax = max(rightMax, height) print(maxes) return sum(maxes) if __name__ == "__main__": #print(waterArea(heights=[0,0,8,0,0,5,0,0])) print(waterArea(heights=[0,8,0,0,5,0,0,10,0,0,1,1,0,3])) print(waterArea2(heights=[0,8,0,0,5,0,0,10,0,0,1,1,0,3])) #print(waterArea(heights=[0,100,0,0,10,1,1,10,1,0,1,1,0,100])) #print(waterArea(heights=[0,100,0,0,10,1,1,10,1,0,1,1,0,0])) # this won't solve this case ugh
#! usr/bin/env python3 def subarraySort(array): i = 0 j = len(array)-1 print("array[i]\tarray[j]\tcenter_min\tcenter_max") while i <= j: # O(n) time operation center_max = max(array[i+1:j]) center_min = min(array[i+1:j]) if array[i] >= center_min and array[j] <= center_max: return [i, j] print("%d\t\t%d\t\t%d\t\t%d" % (array[i],array[j],center_min,center_max)) if array[i] < center_min: i += 1 if array[j] > center_max: j -= 1 return [-1, -1] def subarraySort(array): i = 0 j = len(array)-1 while i < j: # O(n) time operation center_array = array[i+1:j] if center_array != []: center_max = max(center_array) center_min = min(center_array) else: if array[j] >= array[i]: return [-1,-1] else: return [i,j] if not (array[i] <= center_min) and not (array[j] >= center_max): return [i, j] if array[i] <= center_min: print(center_array) i += 1 if array[j] >= center_max: j -= 1 print("%d,%d" % (i,j)) if i > j: return [-1, -1] else: return [i-1,j] def subarraySort(array): minOOO = float('inf') maxOOO = float('-inf') for i,x in enumerate(array): if is_out_of_order(i,x,array): minOOO = min(minOOO,x) maxOOO = max(maxOOO,x) if minOOO == float('inf'): return [-1,-1] i,j = 0,len(array)-1 while i < j: if array[i] > minOOO: break; i += 1 while i < j: if array[j] < maxOOO: break j -= 1 return [i,j] def is_out_of_order(i,x,array): if i == 0: return not (x <= array[i+1]) if i == len(array)-1: return not (x >= array[i-1]) return not (x <= array[i+1]) or not (x >= array[i-1]) if __name__ == "__main__": print(subarraySort([1,2,4, 7,10,11,7,12,6,7, 16,18,19])) print(subarraySort([1,2,4,7, 10,11,7,12,7,7, 16,18,19])) print(subarraySort([2,1])) print(subarraySort([1,2]))
#! usr/bin/python3 """ Find the minimum spanning tree (MST) that connects all the vertices in the graph while minimizing the total edge weights. Solution -------- We'll use Prim's algorithm. this is a classic greedy algorithm. (1) Create an empty structure M (adj matrix or binary tree) which will be the MST (2) Choose a random vertex v from the graph (3) Add the edges taht are connected to v into some data structure E (4) Find the edge in E with the minimum weight, and add this edge to M. Now, make v equal to the other vertex in the edge and repeat from step 3. https://coderbyte.com/algorithm/find-minimum-spanning-tree-using-prims-algorithm """ graph = { 'a': [('b',2),('c',3)], 'b': [('a',2),('c',5),('d',3),('e',4)], 'c': [('a',3),('b',5),('e',4)], 'd': [('b',3),('e',2),('f',3)], 'e': [('b',4),('c',4),('d',2),('f',5)], 'f': [('d',3),('e',5)] } def prims(G): edges = [] collected_vertices = ['a'] for k in G.keys(): minEdge = (None,float('inf')) # vertex,distance for v,e in G[k]: if (e < minEdge[1]) and (v==minEdge[0]): if __name__ == "__main__": print(find_mst(graph))
#! usr/bin/python3 import sys from time import time def fibonacci_naive(n): if n == 1: return 0 elif n == 2: return 1 else: return fibonacci_naive(n-1) + fibonacci_naive(n-2) def fibonacci(n,memo={1:0,2:1}): if n in memo: return memo[n] memo[n] = fibonacci(n-1,memo) + fibonacci(n-2,memo) return memo[n] if __name__ == "__main__": start_time = time() print(fibonacci_naive(int(sys.argv[1]))); print("Took %0.6f" % (time()-start_time)) start_time = time() print(fibonacci(int(sys.argv[1]))); print("Took %0.6f" % (time()-start_time))
#! usr/bin/python3 """ Good morning! Here's your coding interview problem for today. This problem was asked by Google. The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method. Hint: The basic equation of a circle is x2 + y2 = r2. """ import random import math def monte_carlo_circle(Cx=1,Cy=1,radius=1,X=100): Y = 0 for _ in range(X): # generate a random point x = random.random() y = random.random() # its in the circle, count it if math.sqrt((x-Cx)**2 + (y-Cy)**2) <= radius: Y += 1 # return the ratio of points inside the circle vs outside times the area return float(Y/X)*Cx**2 if __name__ == "__main__": print(monte_carlo_circle(Cx=1,Cy=1,radius=1,X=100000)) print("Real Area is %0.5f" % (math.pi*0.5**2))
#! usr/bin/python3 """ Print all subsets of a set input set = [1, 2, 3] power set = [[], [1], [2], [3], [1, 2], [2, 3], [1, 3] [1, 2, 3]] """ def subsets_of_set(lArray): results = []; n = 2**len(lArray) # 2**n total subsets for i in range(n): going = [] rep = "{0:b}".format(i) while len(rep) < len(lArray): rep = '0' + rep; for j,x in enumerate(rep): if x == '1': going.append(lArray[j]) elif x == '0': continue results.append(going) return results if __name__ == "__main__": print(subsets_of_set([1,2,3])); print(subsets_of_set([1,2,3,4])); print(subsets_of_set(list(range(1200))));
#! usr/bin/python4 """ Good morning! Here's your coding interview problem for today. This problem was asked by Twitter. Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix. For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal]. Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries. """ class TrieNode(object): def __init__(self,char): self.char = char self.children = [] self.word_finished = False # if this is the end of a word or not self.counter = 1 def __str__(self): return "%s" % self.char def add(root, word: str): node = root for char in word: found_in_child = False for child in node.children: if child.char == char: node = child found_in_child = True break if not found_in_child: new_node = TrieNode(char) node.children.append(new_node) node = new_node print(node.children) node.word_finished = True def find_prefix(root, prefix: str): node = root if not root.children: # if we have no children, return False return False for char in prefix: char_not_found = True for child in node.children: if child.char == char: char_not_found = False node = child break if char_not_found: return False return True; def autocomplete(s): """ I tried a trie but it didn't fucking work becuase shit is so gay """ pass if __name__ == "__main__": root = TrieNode('*') add(root, "hackathon") add(root, 'hack') print([str(x) for x in root.children]) print(find_prefix(root, 'hac')) print(find_prefix(root, 'hack')) print(find_prefix(root, 'hackathon')) print(find_prefix(root, 'ha')) print(find_prefix(root, 'hammer')) #print(autocomplete(s="",prefixes=[]))
dias=int(input('Quantos dias usou o veículo? ')) km=float(input('Quantos quilometros foram rodados? ')) diar=dias*60 kmt=km*0.15 print('O valor das diárias foi R$ {:.2f} e o valor da quilometragem usada foi R$ {:.2f}.\n' 'O total a pagar é R${:.2f}.\nObrigado!\n' 'Volte sempre!'.format(diar,kmt,diar+kmt))
import matplotlib.pyplot as plt import pdb from math import sqrt """This was probably a waste of time - Dylan""" def pressure(V,n,R,T): return n*R*T/V def Force(P,A): return P * A def acceleration(F,m): return F / m def velocity(u,a,dt): return u + a * dt def position(x,u,dt): return x + u * dt def moles(n,flow,dt): return n + flow * dt def Volume(x,A): return x * A def flowrate_in(P,air_density,P_wall,A_inlet,R,T,k): if ( (P_wall - P) < 0):#This will be replaced by full emprical equation return sqrt( (2/air_density) * (P - P_wall) ) * A_inlet * ( P / (R*T) * k ) * -1.0 return sqrt( (2/air_density) * (P_wall - P) ) * A_inlet * ( P_wall / (R*T) * k ) def flowrate_out(P,air_density,P_STP,A_inlet,R,T,k): if ( (P - P_STP) < 0):#This will be replaced by full emprical equation return sqrt( (2/air_density) * (P_STP - P) ) * A_inlet * ( P_STP / (R*T) * k ) return sqrt( (2/air_density) * (P - P_STP) ) * A_inlet * ( P / (R*T) * k ) * -1.0 #negative sign to represent moles leaving def update_state_up(step_size, s): s["flow_1"] = flowrate_in(s["P_1"],s["air_density"],s["P_wall"],s["A_inlet"],s["R"],s["T"],s["k"])#calculate the flow rate s["flow_2"] = flowrate_out(s["P_2"],s["air_density"],s["P_STP"],s["A_inlet"],s["R"],s["T"],s["k"])#calculate the flow rate s["n_1"] = moles(s["n_1"],s["flow_1"],step_size) #update num moles s["n_2"] = moles(s["n_2"],s["flow_2"],step_size) #update num moles s["P_1"] = pressure(s["V_1"],s["n_1"],s["R"],s["T"]) # update pressure s["P_2"] = pressure(s["V_2"],s["n_2"],s["R"],s["T"]) # update pressure s["F_1"] = Force(s["P_1"],s["A"]) # subtract room air pressure and estimate friction s["F_2"] = Force(s["P_2"],s["A"]) # subtract room air pressure and estimate friction s["a"] = acceleration(s["F_1"] - s["F_2"] + s["impact"] - s["friction_loss"] ,s["m"]) #calculate a s["u"] = velocity(s["u"],s["a"],step_size ) #update velocity s["x"] = position(s["x"],s["u"],step_size ) #update position s["V_1"] = Volume(s["A"],s["x"]) # calculate V s["V_2"] = Volume(s["A"],s["x_max"]-s["x"]+s["x_min"]) # calculate V s["time"] = s["time"]+step_size if s["x"] >= s["x_max"] : s["impact"] = - s["impulse_k"] * (s["x"]-s["x_max"]) s["transfer"] = s["a"] / (s["mass_table"]/s["m"]) elif s["x"] <= s["x_min"]: s["impact"] = - s["impulse_k"] * (s["x"]-s["x_min"]) s["transfer"] = s["a"] / (s["mass_table"]/s["m"]) else: s["transfer"] = 0.0 s["impact"] = 0.0 return s def update_state_down(step_size, s): s["flow_1"] = flowrate_out(s["P_1"],s["air_density"],s["P_STP"],s["A_inlet"],s["R"],s["T"],s["k"])#calculate the flow rate s["flow_2"] = flowrate_in(s["P_2"],s["air_density"],s["P_wall"],s["A_inlet"],s["R"],s["T"],s["k"])#calculate the flow rate s["n_1"] = moles(s["n_1"],s["flow_1"],step_size) #update num moles s["n_2"] = moles(s["n_2"],s["flow_2"],step_size) #update num moles s["P_1"] = pressure(s["V_1"],s["n_1"],s["R"],s["T"]) # update pressure s["P_2"] = pressure(s["V_2"],s["n_2"],s["R"],s["T"]) # update pressure s["F_1"] = Force(s["P_1"],s["A"]) # subtract room air pressure and estimate friction s["F_2"] = Force(s["P_2"],s["A"]) # subtract room air pressure and estimate friction s["a"] = acceleration(s["F_1"] - s["F_2"] + s["impact"] - s["friction_loss"],s["m"]) #calculate a s["u"] = velocity(s["u"],s["a"],step_size ) #update velocity s["x"] = position(s["x"],s["u"],step_size ) #update position s["V_1"] = Volume(s["A"],s["x"]) # calculate V s["V_2"] = Volume(s["A"],s["x_max"]-s["x"]+s["x_min"]) # calculate V s["time"] = s["time"]+step_size if s["x"] >= s["x_max"] : s["impact"] = - s["impulse_k"] * (s["x"]-s["x_max"]) s["transfer"] = s["a"] / (s["mass_table"]/s["m"]) elif s["x"] <= s["x_min"]: s["impact"] = - s["impulse_k"] * (s["x"]-s["x_min"]) s["transfer"] = s["a"] / (s["mass_table"]/s["m"]) else: s["transfer"] = 0.0 s["impact"] = 0.0 return s def propogate(step_size,num_steps,num_cycles,state_vector): #Globals P1_list = [] # for plotting pos_list = [] times = [] vel_list = [] moles1_list = [] a_list = [] flow1_list = [] P2_list = [] moles2_list = [] flow2_list = [] transfer_a = [] vol_2 = [] pressure = state_vector["P_wall"] for cycle in range(0,num_cycles): #Algorithm Engine if cycle == 0: state_vector["P_wall"] = 0.5 * pressure else: state_vector["P_wall"] = pressure for dt in range(1,num_steps): state_vector= update_state_up(step_size,state_vector) #Gather for plotting flow1_list.append(state_vector["flow_1"]) flow2_list.append(state_vector["flow_2"]) moles1_list.append(state_vector["n_1"]) moles2_list.append(state_vector["n_2"]) times.append(state_vector["time"]) P1_list.append(state_vector["P_1"]) P2_list.append(state_vector["P_2"]) a_list.append(state_vector["a"]) vel_list.append(state_vector["u"]) pos_list.append(state_vector["x"]) transfer_a.append(state_vector["transfer"]/9.8) vol_2.append(state_vector["V_2"]) for dt in range(1,num_steps): state_vector= update_state_down(step_size,state_vector) flow1_list.append(state_vector["flow_1"]) flow2_list.append(state_vector["flow_2"]) moles1_list.append(state_vector["n_1"]) moles2_list.append(state_vector["n_2"]) times.append(state_vector["time"]) P1_list.append(state_vector["P_1"]) P2_list.append(state_vector["P_2"]) a_list.append(state_vector["a"]) vel_list.append(state_vector["u"]) pos_list.append(state_vector["x"]) transfer_a.append(state_vector["transfer"]/9.8) vol_2.append(state_vector["V_2"]) #for x in pos_list: # print(x) #Plots plt.subplot(6, 2, 1) plt.plot(times, P1_list, 'ko-') plt.title('Time evolution of bottom of piston') plt.ylabel('Pressure Pascals') plt.subplot(6, 2, 2) plt.plot(times, P2_list, 'ko-') plt.title('Time evolution of top of piston') plt.ylabel('Pressure Pascals') plt.subplot(6, 2, 3) plt.plot(times, flow1_list, 'y-') plt.ylabel('moles/sec') plt.subplot(6, 2, 4) plt.plot(times, flow2_list, 'y-') plt.ylabel('moles/sec') plt.subplot(6, 2, 5) plt.plot(times, moles1_list, 'y.-') plt.ylabel('gas moles') plt.subplot(6, 2, 6) plt.plot(times, moles2_list, 'y.-') plt.ylabel('gas moles') plt.subplot(6, 2, 7) plt.plot(times, a_list, 'ko-') plt.ylabel(' m/s**2') plt.subplot(6, 2, 8) plt.plot(times, transfer_a, 'ko-') plt.ylabel("transfer g's") plt.subplot(6, 2, 9) vel_average = sum(vel_list)/len(vel_list) #plt.plot(times, vel_list, [-10,num_steps],[vel_average,vel_average] ,'b.-') plt.plot(times, vel_list ,'b.-') plt.ylabel(' m/s') plt.subplot(6, 2, 11) table_height = 0.05 plt.plot(times, pos_list, 'r-') plt.ylabel('position m') tot = 0 for each in transfer_a: print(each) tot = tot + each**2 print("The grms is : " + str(sqrt( tot / (len(transfer_a) * step_size) ) ) ) plt.show() #main loop gauge_pressure = 112476 #Pressure supplied to system mass = 0.5#mass of cylinder r = 0.01#radius of cylinder cycles = 5 state_vector ={ "P_1":101300,#Pressure in Pascals "P_STP":101300,#Standard Temp and Pressure P "P_2": 101300,#Pressure of seond piston cavity "air_density":1.225,#Desnity of air in kg/m^3 "radius": r,#radius of cylinder in meters "A_inlet":3.14 * 0.003175**2,#Cross sectional area of inlet, meters "k":0.01,#imperical flow resistance "x_max":0.020,#length at which piston hits table "x_min":0.005,#Min position of piston "R":8.314,#Ideal Gas Const J/mol K "T":273,#Temp in Kelvin "m":mass,#mass of cylinder in kg "u":0.0,#velocity m/s "a":0.0,#Acceleration m/ss "F_1":0.0,#Force applied to piston, N "F_2":0.0,#Force top side of piston "friction_loss":1.0,#empirical friction force of piston "flow_1":0.0, #Air flow in moles/s this will be function of pressure differential "time":0.0, #Global time variables sec "impact": 0.0, #Force due t impact Newtons "impulse_k": 500000, #emprical impulse coefficient "mass_table": 10.0, #mass of table "transfer": 0.0, #Energy transfered to the table "momentum_loss_factor":1.0 #emprical factor to gauge inefficency (sound, heat loss) } state_vector.update({ "P_wall":state_vector["P_STP"] + gauge_pressure,#Pressure of regulator "A":3.14 * state_vector["radius"]**2,#Cross sectional area of cylinder "x":state_vector["x_min"],#Postion of piston meters }) state_vector.update({ "V_1":state_vector["A"] * state_vector["x"], "V_2":state_vector["A"] * (state_vector["x_max"]-state_vector["x"]) }) state_vector.update({ "n_1":(state_vector["P_1"] * state_vector["V_1"]) / (state_vector["R"] * state_vector["T"]), "n_2":(state_vector["P_2"] * state_vector["V_2"]) / (state_vector["R"] * state_vector["T"]) }) propogate(0.001,500,cycles,state_vector) #Step size and num_steps
while True: print("looping") break count = 1 while count <= 4: print("looping") count += 1 print(f"We're counting odd numbers: {count}") colors = ['blue', 'green', 'red', 'purple'] for color in colors: print(color) print(color) for color in colors: if color == 'blue': continue elif color == 'red': break print(color) for letter in "my_string": print(letter) ages = {'kevin': 59, 'bob': 40, 'kayla': 21} for name, age in ages.items(): print(f"Person Named: {name}") print(f"Age of: {age}")
""" This File demonstrates solving the crossword problem using constraints satisafiction """ import sys from crossword import * from crossword_creator import * import itertools import timeit class CSP(): def __init__(self, crossword_creator): """ Create new CSP crossword generate. """ self.crossword_creator=crossword_creator def solve(self): """ Enforce node and arc consistency, and then solve the CSP. """ valid=self.words_variables_consistency() if valid==None: return None self.enforce_node_consistency() self.ac3() return self.backtrack(dict()) def words_variables_consistency(self): """ Check if there are m variables with length l then there should be m words or greater that have length l """ max_len=0 for word in self.crossword_creator.crossword.words: if max_len<len(word): max_len=len(word) occ_word=[0 for i in range(max_len+1)] occ_variables=[0 for i in range(max_len+1)] for var in self.crossword_creator.crossword.variables: occ_variables[var.length]+=1 for word in self.crossword_creator.crossword.words: occ_word[len(word)]+=1 for idx,word in enumerate(occ_word): if occ_variables[idx]>occ_word[idx]: return None return True def enforce_node_consistency(self): """ Apply node consistency on all variables """ for var in self.crossword_creator.crossword.variables: new_domain=[] for word in self.crossword_creator.domains[var]: if var.length == len(word): new_domain.append(word) self.crossword_creator.domains[var]=new_domain def revise(self, x, y): """ This function implements the Arc-consistency between two variables, it makes X arc-consistent with Y, for X to be arc consistent with respect to Y we should ensure that every value in X's domain has at least one possible choice from Y's domain """ revised= False # revised indicates whether or not we made a change for x'domain overlap_idx=self.crossword_creator.crossword.overlaps[(x,y)] for x_word in self.crossword_creator.domains[x]: # check if there is possible value in Y's domain that statisifies the binary constraint between X and Y. y_words=self.crossword_creator.domains[y] no_match_found=any([True if y_word[overlap_idx[1]]==x_word[overlap_idx[0]] else False for y_word in y_words]) if no_match_found == False: self.crossword_creator.domains[x].remove(x_word) # delete x_word from the domain of X revised=True # We made a change for x'domain return revised def ac3(self, arcs=None): """ Enforce the arc consistency across the entire problem """ queue=None if arcs==None: queue = list(itertools.product(self.crossword_creator.crossword.variables, self.crossword_creator.crossword.variables)) queue = [arc for arc in queue if arc[0] != arc[1] and self.crossword_creator.crossword.overlaps[arc[0], arc[1]] is not None] else: queue=arcs while len(queue)!=0: cur_element=queue.pop(0) x=cur_element[0] y=cur_element[1] if self.revise(x,y)==True: if len(self.crossword_creator.domains[x])==0: return False # There is no way to solve the problem because we can't find a value # for the X that statisfies all the overlapping constraint else: """ after changing the x's domain, it might become not arc consistent with other variables so we will check the consistency again along with x and it's neighbours except for y because we have already checked it. """ other_neighbours=self.crossword_creator.crossword.neighbors(x).remove(y) if other_neighbours!=None: for z in other_neighbours: queue.append(tuple([x,z])) return True def assignment_complete(self, assignment): """ check if `assignment` is complete (i.e., each variable is assigned to a value to each); """ if set(assignment.keys()) == self.crossword_creator.crossword.variables and all(assignment.values()): return True else: return False def consistent(self, assignment): """ The assignment will be inconsistent if it violates one of the following 3 rules 1) the length of the value should be equal to the length of the variable ==> Node Consistency 2) Values should be distinct for the variables ==> Arc Consistency 3) There should be no conflicts between the neighbouring variables ==> Arc Consistency """ """ First Rule """ for var in assignment.keys(): if len(assignment[var])!=var.length: return False """ Second Rule """ """ as the elements of the set are unique so we will put the values of the assignment in a set and check if it's length is equal to the length of keys of assignment dict """ if len(set(assignment.values())) != len(set(assignment.keys())): return False """ Third Rule """ for var in assignment.keys(): neighbors=self.crossword_creator.crossword.neighbors(var) for n in neighbors: overlap_idx=self.crossword_creator.crossword.overlaps[(var,n)] if n in assignment: if assignment[var][overlap_idx[0]]!=assignment[n][overlap_idx[1]]: return False return True def order_domain_values(self, var, assignment): """ Return a list of values in the domain of `var`, in order by the number of values they rule out for neighboring variables. The first value in the list, for example, should be the one that rules out the fewest values among the neighbors of `var`. """ num_choices_avaliable = {word: 0 for word in self.crossword_creator.domains[var]} neighbors=self.crossword_creator.crossword.neighbors(var) var_words=self.crossword_creator.domains[var] for w in var_words: for neighbor in (neighbors - assignment.keys()): overlap = self.crossword_creator.crossword.overlaps[var, neighbor] # Loop through each word in neighbor's domain for word_n in self.crossword_creator.domains[neighbor]: if w[overlap[0]]==word_n[overlap[1]]: num_choices_avaliable[w]+=1 sorted_list = sorted(num_choices_avaliable.items(), key=lambda x:x[1]) return reversed([x[0] for x in sorted_list]) def select_unassigned_variable(self, assignment): """ Return an unassigned variable not already part of `assignment`. Choose the variable with the minimum number of remaining values in its domain. If there is a tie, choose the variable with the highest degree. If there is a tie, any of the tied variables are acceptable return values. """ unassigned_variables = self.crossword_creator.crossword.variables - assignment.keys() num_remaining_values = {variable: len(self.crossword_creator.domains[variable]) for variable in unassigned_variables} sorted_num_remaining_values = sorted(num_remaining_values.items(), key=lambda x: x[1]) if len(sorted_num_remaining_values) == 1 or sorted_num_remaining_values[0][1] != sorted_num_remaining_values[1][1]: return sorted_num_remaining_values[0][0] else: num_degrees = {variable: len(self.crossword_creator.crossword.neighbors(variable)) for variable in unassigned_variables} sorted_num_degrees = sorted(num_degrees.items(), key=lambda x: x[1], reverse=True) return sorted_num_degrees[0][0] def backtrack(self, assignment): """ Using Backtracking Search, take as input a partial assignment for the crossword and return a complete assignment if possible to do so. `assignment` is a mapping from variables (keys) to words (values). If no assignment is possible, return None. """ if self.assignment_complete(assignment)==True: return assignment var=self.select_unassigned_variable(assignment) for value in self.order_domain_values(var,assignment): new_assignment=assignment.copy() new_assignment[var]=value if self.consistent(new_assignment)==True: assignment[var]=value result=self.backtrack(assignment) if result !=None: # indicates failure we got stuck with this value and we have to try another one return result assignment.pop(var, None) return None # indicates that There is no possible assignment for this variable # So,the problem has no solution def main(): # Check usage if len(sys.argv) not in [3, 4]: sys.exit("Usage: python generate.py structure words [output]") # Parse command-line arguments structure = sys.argv[1] words = sys.argv[2] output = sys.argv[3] if len(sys.argv) == 4 else None # Generate crossword crossword = Crossword(structure, words) creator = CrosswordCreator(crossword) CSP_Problem=CSP(creator) start = timeit.default_timer() assignment = CSP_Problem.solve() stop = timeit.default_timer() print('Time Taken to solve the problem: ', stop - start) # Print result if assignment is None: print("No solution.") else: creator.print(assignment) if output: creator.save(assignment, output) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- import pandas as pd import time from datetime import date def clean_people(df): # rename columns: df = df.rename(columns={'email address': 'email'}) # remove rows which have an empty "first_name" (NA): #df = df[df.first_name.notna()] <- equivalent to next line: df = df.dropna(subset=['first_name']) # drop duplicates on ID column: df = df.drop_duplicates() # Normalize gender column: df['gender'] = df['gender'].replace({'Female': 'F', 'Male': 'M'}) # Convert column "age" to number (coerce: put NaN for bad values): df['age'] = pd.to_numeric(df.age, errors='coerce') # Convert columns to date type: df['registration'] = pd.to_datetime(df.registration) df['last_seen'] = pd.to_datetime(df.last_seen, unit='s') # When missing, last seen should fallback to the registration date: df['last_seen'] = df.last_seen.combine_first(df.registration) # Add a "full_name" column by concatenating two other ones: df['full_name'] = df.first_name + " " + df.last_name # Add a "country" column by extracting it from the address, with a split: df['country'] = df.address.str.split(', ').str[1] # Column "money" contains values like "$50.23" or "€23,09". # We want to make it uniform (only dollar currency) and as number, not str. df['currency'] = df.money.str[0] # extract first char ($/€) to a new "currency" column df['money'] = df.money.str[1:].str.replace(',', '.') # extract remaining chars and replace , by . df['money'] = pd.to_numeric(df.money) # convert to number # convert euros cells to dollar: df.loc[df.currency == '€', 'money'] = df[df.currency == '€'].money * 1.10 del df['currency'] # remove "currency" column which is now useless # Keep only rows where email is not NA: df = df.dropna(subset=['email']) # Keep only rows where email is a good email: # CAUTION: in the real world you should not use dummy regexes like this to validate email addresses, # but instead use a dedicated tool like https://github.com/syrusakbary/validate_email. df = df[df.email.str.contains('.+@[0-9a-zA-Z\.\-_]+\.\w{2,}')] # Some users may use email alias (example: [email protected] is an alias for [email protected]). # We want to drop these duplicates. To do that, we extract the 'alias' part with a regex: groups = df.email.str.extract('([0-9a-zA-Z\.\-_]+)(\+[0-9a-zA-Z\.\-_]+)?(@[0-9a-zA-Z\.\-_]+\.\w{2,})') df['email'] = groups[0] + groups[2] # we override the email with the email without the alias part # Then, just use drop_duplicates, which will keep the first line by default: df = df.drop_duplicates(subset=['email']) df['inactive']=df['last_seen'].map(lambda x: True if(x.year-2018<1) else False) df = df[df.phone.str.contains('\w{10}', na=False)] df['mobile_phone']=df['phone'].map(lambda x: True if(x[0:2]=="06") else False) return df df_people = pd.read_csv('people.csv', sep=',') df_people = clean_people(df_people)
"""Loop Detection Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop. DEFINITION Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list. EXAMPLE Input: A -> B -> C -> D -> E -> C [thesameCasearlier] Output: C Hints: #50 There are really two parts to this problem. First, detect if the linked list has a loop. Second, figure out where the loop starts. #69 To identify if there's a cycle, try the "runner" approach described on page 93. Have one pointer move faster than the other. #83 You can use two pointers, one moving twice as fast as the other. If there is a cycle, the two pointers will collide. They will land at the same location at the same time. Where do they land? Why there? #90 If you haven't identified the pattern of where the two pointers start, try this: Use the linked list 1->2->3->4->5->6->7->8->9->?, where the? links to another node. Try making the? the first node (that is, the 9 points to the 1 such that the entire linked list is a loop). Then make the? the node 2. Then the node 3. Then the node 4. What is the pattern? Can you explain why this happens? """ from SingleLinkedList import SingleLinkedList import unittest def find_starting_point(linkedlist): first_runner = linkedlist.head second_runner = linkedlist.head while second_runner: first_runner = first_runner.next second_runner = second_runner.next.next if first_runner is second_runner: break if second_runner is None and second_runner.next is None: return None second_runner = linkedlist.head while first_runner: if first_runner is second_runner: return first_runner.data first_runner = first_runner.next second_runner = second_runner.next return None class CircularLinkedList(SingleLinkedList): def make_circuit(self): current_node = self.head while current_node.next: current_node = current_node.next current_node.next = self.head class SingleLinkedListWithNode(SingleLinkedList): def append_node(self, node): current_node = self.head while current_node.next: current_node = current_node.next current_node.next = node class Test(unittest.TestCase): def setUp(self): cll = CircularLinkedList() cll.append(2) cll.append(5) cll.append(7) cll.append(9) cll.append(1) cll.make_circuit() self.sll = SingleLinkedListWithNode() self.sll.append(4) self.sll.append(5) self.sll.append(6) self.sll.append_node(cll.head) def test_find_starting_point(self): self.assertEqual(find_starting_point(self.sll), 2) if __name__ == "__main__": unittest.main()
"""Three in one Describe how you could use a single array to implement three stacks. Hints: #2 A stack is simply a data structure in which the most recently added elements are removed first. Can you simulate a single stack using an array? Remember that there are many possible solutions, and there are tradeoffs of each. #12 We could simulate three stacks in an array by just allocating the first third of the array to the first stack, the second third to the second stack, and the final third to the third stack. One might actually be much bigger than the others, though. Can we be more flexible with the divisions? #38 If you want to allow for flexible divisions, you can shift stacks around. Can you ensure that all available capacity is used? #58 Try thinking about the array as circular, such that the end of the array "wraps around" to the start of the array. """ import unittest class StacksInArray: def __init__(self, k, size): self.top_of_stack = [None for _ in range(k)] self.stack_data = [None for _ in range(size)] self.next_index = [i+1 for i in range(size)] self.next_index[size-1] = None self.next_available = 0 def push(self, stack, data): if stack < 0 or stack >= len(self.top_of_stack): raise IndexError("Out of index error") if self.next_available is None: raise Exception("All stacks are full.") current_index = self.next_available self.next_available = self.next_index[current_index] self.stack_data[current_index] = data self.next_index[current_index] = self.top_of_stack[stack] self.top_of_stack[stack] = current_index def pop(self, stack): if self.top_of_stack[stack] is None: raise Exception("This stack is empty.") current_index = self.top_of_stack[stack] value = self.stack_data[current_index] self.top_of_stack[stack] = self.next_index[current_index] self.next_index[current_index] = self.next_available self.next_available = current_index return value def show_stack_values(self, stack): current_index = self.top_of_stack[stack] result = "" while current_index: result += str(self.stack_data[current_index]) + " -> " current_index = self.next_index[current_index] result += "None" return result class Test(unittest.TestCase): def setUp(self): self.stacks = StacksInArray(4, 10) self.stacks.push(0, 6) self.stacks.push(0, 7) self.stacks.push(1, 4) self.stacks.push(2, 1) self.stacks.push(0, 9) self.stacks.push(2, 5) self.stacks.push(1, 8) def test_pop(self): self.assertEqual(self.stacks.pop(0), 9) self.assertEqual(self.stacks.pop(2), 5) def test_push(self): self.stacks.push(1, 99) self.assertEqual(self.stacks.show_stack_values(1), "99 -> 8 -> 4 -> None") def test_full_exception(self): self.stacks.push(1, 5) self.stacks.push(1, 5) self.stacks.push(1, 5) self.assertRaises(Exception, self.stacks.push, 1, 5) def test_index_exception(self): self.assertRaises(IndexError, self.stacks.push, 9, 9) if __name__ == "__main__": unittest.main()
"""Minimal Tree Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height. Hints: #19 A minimal binary tree has about the same number of nodes on the left of each node as on the right. Let's focus on just the root for now. How would you ensure that about the same number of nodes are on the left of the root as on the right? #73 You could implement this by finding the "ideal" next element to add and repeatedly calling insertValue. This will be a bit inefficient, as you would have to repeatedly traverse the tree. Try recursion instead. Can you divide this problem into subproblems? #176 Think about what sort of expectations on freshness and accuracy of data is expected. Does the data always need to be 100% up to date? Is the accuracy of some products more important than others? """ import unittest class Node: def __init__(self, data=None): self.right = None self.left = None self.data = data class BinarySearchTree: def __init__(self): self.root = None def insert(self, data): if self.root: self.__insert(self.root, data) else: self.root = Node(data) def __insert(self, node, data): if node.data < data: if node.right: self.__insert(node.right, data) else: node.right = Node(data) else: if node.left: self.__insert(node.left, data) else: node.left = Node(data) def show(self): if self.root is None: return None return self.__pre_order(self.root, path=[]) def __pre_order(self, node, path): if node: path.append(node.data) self.__pre_order(node.left, path) self.__pre_order(node.right, path) return path class MinimalTree(BinarySearchTree): def make_tree(self, sorted_array): self.root = self.__make_tree(sorted_array, 0, len(sorted_array)-1) def __make_tree(self, list, start, end): if end < start: return None mid = (start + end) // 2 node = Node(list[mid]) node.left = self.__make_tree(list, start, mid-1) node.right = self.__make_tree(list, mid+1, end) return node class Test(unittest.TestCase): def setUp(self): self.bst = BinarySearchTree() self.bst.insert(5) self.bst.insert(7) self.bst.insert(3) self.bst.insert(2) self.bst.insert(8) self.bst.insert(6) self.mbst = MinimalTree() def test_bst_pre_order(self): self.assertEqual(self.bst.show(), [5, 3, 2, 7, 6, 8]) def test_minimal_tree(self): self.mbst.make_tree([2, 4, 6, 7, 8, 9]) self.assertEqual(self.mbst.show(), [6, 2, 4, 8, 7, 9]) if __name__ == "__main__": unittest.main()
"""Deck of Cards Design the data structures for a generic deck of cards. Explain how you would subclass the data structures to implement blackjack. Hints: #153 Note that a "card deck" is very broad. You might want to think about a reasonable scope to the problem. #275 How, if at all, will you handle aces? """ ''' Conditions: Core objects: Relationship: Key actions: ''' class Suit: def __init__(self): self.value = ['CLUB', 'SPADE', 'HEART', 'DIAMOND'] def get_value(self, index): return self.value[index] from abc import ABC, abstractmethod class Card(ABC): def __init__(self, face_value, suit): self.face_value = face_value self.suit = suit self.available = True @abstractmethod def value(self): pass def is_available(self): return self.available def mark_unavailable(self): self.available = False def mark_available(self): self.available = True from random import randrange class Deck: def __init__(self): self.dealt_index = 0 self.cards = None def set_deck_of_cards(self, cards): self.cards = cards def shuffle(self): for i in range(len(self.cards)-1): random_index = randrange(i+1, len(self.cards)) self.cards[i], self.cards[random_index] = self.cards[random_index], self.cards[i] def deal_hand(self, number): if self.remaining_cards() < number: return None hand = list() for i in range(number): card = self.deal_card() if card: hand[i] = card return hand def remaining_cards(self): return len(self.cards) - self.dealt_index def deal_card(self): if self.remaining_cards() == 0: return None card = self.cards[self.dealt_index] card.mark_unavailable() self.dealt_index += 1 return card class Hand: def __init__(self, cards): self.cards = cards def score(self): score = 0 for card in self.cards: score += card.value() return score def add_card(self, card): self.cards.append(card) class BlackJackCard(Card): def __init__(self, face_value, suit): super().__init__(face_value, suit) def value(self): if self.is_ace(): return 1 elif self.face_value >= 11 and self.face_value <= 13: return 10 else: return self.face_value def min_value(self): return 1 if self.is_ace() else self.value() def max_value(self): return 11 if self.is_ace() else self.value() def is_ace(self): return self.face_value == 1 def is_face(self): return self.face_value >= 11 and self.face_value <= 13 import sys class BlackJackHand(Hand): def score(self): scores = self.possible_scores() max_under = -sys.maxsize - 1 min_over = sys.maxsize for score in scores: if score > 21 and score < min_over: min_over = score elif score <= 21 and score > max_under: max_under = score return min_over if max_under == -sys.maxsize - 1 else max_under def possible_scores(self): scores = list() if self.cards and len(self.cards) > 0: scores.append(0) for card in self.cards: for i in range(len(scores)): if card.is_ace(): scores.append(scores[i]+card.max_value()) scores[i] += card.min_value() return scores def busted(self): return self.score() > 21 def is_21(self): return self.score() == 21 def is_blackjack(self): if len(self.cards) != 2: return False return (self.cards[0].is_ace() and self.cards[1].is_face()) or \ (self.cards[1].is_ace() and self.cards[0].is_face()) class BlackJackGameAutomator: HIT_UNTIL = 16 def __init__(self, number_of_players): self.deck = None self.hands = [BlackJackHand(list()) for _ in range(number_of_players)] def deal_initial(self): for hand in self.hands: card1 = self.deck.deal_card() card2 = self.deck.deal_card() if not (card1 and card2): return False hand.add_card(card1) hand.add_card(card2) return True def get_blackjack(self): winners = list() for idx, hand in enumerate(self.hands): if hand.is_blackjack(): winners.append(idx) return winners def play_hand(self, index): while self.hands[index].score() < self.HIT_UNTIL: card = self.deck.deal_card() if card is None: return False self.hands[index].add_card(card) return True def play_all_hand(self): for i in range(len(self.hands)): if not self.play_hand(i): return False return True def get_winners(self): winners = list() winning_score = 0 for i in range(len(self.hands)): if not self.hands[i].busted(): if self.hands[i].score() > winning_score: winning_score = self.hands[i].score() winners.clear() winners.append(i) elif self.hands[i].score() == winning_score: winners.append(i) return winners def initialize_deck(self): suit = Suit() cards = [BlackJackCard(i, suit.get_value(j)) for i in range(1, 14) for j in range(4)] self.deck = Deck() self.deck.set_deck_of_cards(cards) self.deck.shuffle() def print_hands_and_score(self): for idx, hand in enumerate(self.hands): print("Hand {} : ({})".format(idx, hand.score())) if __name__ == "__main__": automator = BlackJackGameAutomator(3) automator.initialize_deck() automator.deal_initial() automator.print_hands_and_score() blackjack = automator.get_blackjack() if blackjack and len(blackjack) > 0: print("Blackjack at", end=" ") for i in range(len(blackjack)-1): print(i, end=", ") print(blackjack[len(blackjack)-1]) else: if automator.play_all_hand(): print("Completed Game") automator.print_hands_and_score() winners = automator.get_winners() if len(winners) > 0: print("Winners :", end=" ") for i in range(len(winners)-1): print(i, end=", " ) print(winners[len(winners)-1]) else: print("Draw.")