text
stringlengths
37
1.41M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Solution: def removeElement(self, nums: List[int], val: int) -> int: """ 注意审题 !!! It doesn't matter what values are set beyond the returned length. !!! """ count = 0 for i in range(len(nums)): if nums[i] != val: nums[count] = nums[i] count += 1 return count
import numpy as np import random import matplotlib.pyplot as plt def print_header(): print("-------------------------------") print(" TIC TAC TOE") print("-------------------------------\n") def create_board(): return np.zeros((3,3)) def place(board, player, position): if board[position[0], position[1]] == 0: board[position[0], position[1]] = player else: print("Cannot place in that position.") return board def possibilities(board): empty = np.where(board == 0) first = empty[0].tolist() second = empty[1].tolist() return [x for x in zip(first, second)] def random_place(board, player): empty = possibilities(board) return place(board, player, random.choice(empty)) def row_win(board, player): return np.any((np.all(board == player, axis=1))) def col_win(board, player): return np.any((np.all(board==player, axis=0))) def diag_win(board, player): diag1 = np.array([board[0,0], board[1,1], board[2,2]]) diag2 = np.array([board[0,2], board[1,1], board[2,0]]) return np.all(diag1 == player) or np.all(diag2 == player) def evaluate(board, players): winner = 0 for player in players: if row_win(board, player): winner = player elif col_win(board, player): winner = player elif diag_win(board, player): winner = player if np.all(board != 0) and winner == 0: winner = -1 return winner def game_loop(): start = input("Do you want to play a game? (y/n) ") print(start) if start.lower() in ["y", "yes"]: repeat = True while repeat == True: play_game() loop = input("Do you want to play again? (y/n) ") if loop.lower() in ["y", "yes"]: repeat = True else: repeat = False print("Goodbye!") else: print("I'm sorry, I didn't understand.") game_loop() def play_game(): """ Game proper. """ board = create_board() print("Here is the board.") print(board) print() print("To place your position, indicate the row number and the column number.") print("For example, to place your position in the middle, type in 2,2 (without spaces).") print("If you want to place in the top left corner, type in 1,1 (without spaces") order = int(input("Do you want to go first or second? (1/2) ")) if order == 1: player1 = 1 player2 = 2 players = [player1, player2] else: player1 = 2 player2 = 1 players = [player2, player1] print("You are player {}:".format(order)) winner = 0 while winner == 0: for player in players: if player == order: position = input("What position do you want to place? ") print("You want to place at {} position.".format(position)) position = int(position[0])-1, int(position[2])-1 place(board, player1, position) # will break if position is not 0 (empty) print(board) else: print("My move:") random_place(board, player) print(board) winner = evaluate(board, players) if winner > 0: if winner == order: print("You win!!!") else: print("I win!!!") break elif winner == -1: print("It's a draw!") break print() return winner def main(): """ Main program for playing tictactoe. """ print_header() game_loop() if __name__ == '__main__': main()
import unittest from ... import CreditAccount class TestCreditAccount(unittest.TestCase): def setUp(self): self.account1 = CreditAccount("Иван", 12345678, "+7900-600-10-20", start_balance=300, negative_limit=-500) self.account2 = CreditAccount("Василий", 12345676, "+7900-600-10-22", start_balance=100, negative_limit=-200) def test_deposit(self): self.account1.deposit(500) self.assertEqual(self.account1.balance, 800) def test_withdraw(self): self.account1.withdraw(200) self.assertEqual(self.account1.balance, 96) # С учетом комиссии в 2% def test_withdraw_limit(self): self.account1.withdraw(400) self.assertEqual(self.account1.balance, -108) # С учетом комиссии в 2% def test_withdraw_limit_max(self): with self.assertRaises(ValueError): self.account1.withdraw(800) def test_withdraw_inc_commission_on_negative_balance(self): self.account1.withdraw(400) # уходим в -баланс. Тут 2% self.account1.withdraw(200) # снимает при -балансе. Тут 5% self.assertEqual(self.account1.balance, -318) def test_withdraw_raise(self): with self.assertRaises(ValueError): self.account1.withdraw(900) def test_transfer(self): self.account1.transfer(self.account2, 200) self.assertEqual(self.account1.balance, 96) self.assertEqual(self.account2.balance, 300) def test_to_archive(self): self.account1.to_archive() self.assertTrue(self.account1.in_archive) def test_restore_from_archive(self): self.account1.to_archive() self.account1.restore() self.assertEqual(self.account1.balance, 0) self.assertFalse(self.account1.in_archive) def test_to_archive_negative_balance(self): self.account1.withdraw(500) self.assertEqual(self.account1.balance, -210) with self.assertRaises(ValueError) as error: self.account1.to_archive() # Можно так, если нужно проверить определенный текст ошибки, но как правило так не делают # self.assertTrue('Нельзя убрать счет с отрицательным балансом в архив' in str(error.exception)) def test_full_info(self): # Проверяем наличие информации в строке, а не строгий формат self.assertIn("300", self.account1.full_info()) self.assertIn("Иван", self.account1.full_info()) self.assertIn("+7900-600-10-20", self.account1.full_info()) self.assertIn("<K>", self.account1.full_info())
import random def generateList(l,r): """generate a list of [l,r)""" ans = [] for i in range(l,r) : ans.append(i) return ans def generateRandomList(n,l,r): '''generate a n-element list where each element is in range [l,r)''' ans = [] for i in range(0,n): ans.append(random.randint(l,r)) return ans def generateTestData_1(n,r): """generate two lists of n elements where n*r of them are the same""" if r <= 0.0 : r = 0.0 if r >= 1.0 : r = 1.0 pxy = int(n * r) lx = generateRandomList(n - pxy,0,300000000) ly = generateRandomList(n - pxy,700000000,1000000000) for i in range(0,pxy): v = random.randint(300000000,700000000) lx.append(v) ly.append(v) return (lx,ly) def repeatNList(n,l): '''repeat list l n times''' ans = [] for i in range(0,n): ans+=l return ans def generateRandomString(L): s = '' for i in range(0,L): r = random.randint(32,126) s += chr(r) return s def generateRandomStringList(n,L): ret = [] for i in range(0,n): ret.append(generateRandomString(L)) return ret def mutateString(s,k): '''switch two adjacent chars in s at a time, for k times''' l = len(s) for i in range(0,k): r = random.randint(0,l-2) ns = s[0:r]+s[r+1]+s[r]+s[r+2:] s = ns return s def mutateStringList(ls,k): ret = [] l = len(ls) for s in ls: ret.append(mutateString(s,k)) return (ls,ret) def generateTest_jaccardEx(n,L,k,sim): ''' n string of length L where n*sim are mutated k times and n - n*sim are completely different ''' nsim = int(n*sim) if nsim < 0 : nsim = 0 if nsim > n : nsim = n ls,rs = mutateStringList(generateRandomStringList(nsim,L),k) ls += generateRandomStringList(n-nsim,L) rs += generateRandomStringList(n-nsim,L) return (ls,rs)
def vekksort(filename): summer = 0 liste = [] with open(filename, 'r') as file: for line in file: line = line.strip() liste.append(int(line)) test = [0] for i in range(0, len(liste)): if test[-1] <= liste[i]: test.append(liste[i]) return sum(test) print(vekksort('input-vekksort.txt'))
pos = input('Posisjon: ') bokstav = pos[0] Svart = ['a', 'c', 'e', 'g', 'A', 'C', 'E', 'G'] Hvit = ['b', 'd', 'f', 'h', 'B', 'D', 'F', 'H'] SvartT =[1, 3, 5, 7] HvitT = [2, 4, 6, 8] c = len(pos) if int(c) != 2: print('Feil input. Du må skrive akkurat to tegn') else: tall = int(pos[1]) if bokstav in Svart and tall in SvartT: print('Svart') elif bokstav in Hvit and tall in HvitT: print('Svart') elif bokstav not in Svart and bokstav not in Hvit: print('Første tegn må være en bokstav A-H eller a-h') elif tall not in SvartT and tall not in HvitT: print('Andre tegn må være et tall 1-8') else: print('Hvit')
#2a) def load_bin(filename): try: with open(filename, 'r') as file: binary_string = '' for line in file: binary_string += line.strip() print(binary_string) return binary_string except: print("Error: Could not open file " + filename) #2b) def bin_to_dec(binary): number = 0 for i in range(len(binary)): if binary[i] == '1': number += 2**(len(binary)-i-1) return number #2c) def dec_to_char(dec): alphabet = ' ,.ABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ' if dec > 31 or dec < 0: return '' return alphabet[dec] #2d) def bin_to_txt(binstring): word = '' for i in range(len(binstring)//5): value = bin_to_dec(binstring[i*5:5*(i+1)]) word += dec_to_char(value) return word #2e) def main(): print("Binary-to-text converter") b_file = input("Name of binary file to load from: ") b_string = load_bin(b_file) txt = bin_to_txt(b_string) t_file = input("Name of text file to save to: ") try: with open(t_file, 'w') as file: file.write(txt) print(f"{b_file} has been converted and saved to {t_file}") except: print(f'Error: Could not write to {t_file}') main()
#2a) def inputPerson(): name = input('Name: ') ID = input('ID: ') weight = int(input('KG: ')) size = int(input('Size: ')) numbers = [] numbers.append(name), numbers.append(ID) numbers.append(weight), numbers.append(size) return numbers #2b) def readDbFile(filename): table = [] with open(filename, 'r') as file: for line in file: line = line.strip() list_line = line.split(';') table.append(list_line) return table #2c) # def printMemberList(db): # print('NAME ' + 'ID-NR '.rjust(14) + 'VEKT kg. '.rjust(12) + 'SKJERMSTORLEIK'.rjust(4)) # for i in db: # print(f'{i[0]} {i[1].rjust(19-len(i[0]))} {i[2].rjust(5)} kg {i[3].rjust(4)} kvadratfot') db = readDbFile('members.txt') print('\n') def printMemberList(db): print('NAVN ID-NR VEKT kg. SKJERMSTØRRELSE') for line in db: s=line[0].ljust(15) s+=line[1].rjust(9) s+=str(line[2]).rjust(5)+' kg ' s+=str(line[3]).rjust(4)+' kvadratfot' print(s) #2d) def addPerson(filename): person = inputPerson() str_person = '' for i in person: str_person += str(i)+';' with open('members.txt', 'a') as file: file.write(str_person[:len(str_person)-1]) #2e) def feet2seconds(height): if height < 3000: return 0 elif height <= 4000: return (height-3000)/100 else: return 10 + (height-4000)/200
#4c) import random N = input('Antall unike tall: ') minvalue = int(input('Min value: ')) maxvalue = int(input('Max value: ')) def generate_testdata(N, minvalue, maxvalue): result = [] while len(result)<int(N): g = random.randint(minvalue, maxvalue) if g not in result: result.append(g) return result print(generate_testdata(N, minvalue, maxvalue))
def main(): facebook = [] newuser = '' print('Hello, welcome to Facebook. Add a new user by writing "given_name surname age gender relationship_status".') while newuser != 'done': newuser = input('Add new user: ') if newuser == 'done': break facebook.append(add_data(newuser)) print('Ok') searching = '' while searching != 'done': searching = input('Search for a user: ') if searching == 'done': break get_person(searching, facebook) def add_data(string): data = string.split() data[2] = int(data[2]) return data def get_person(given_name, facebook): for i in range(len(facebook)): if facebook[i][0] == given_name: user = facebook[i] if user[3].lower() == 'female': print(f'{user[0]} {user[1]} is {user[2]} years old, her relationship status is {user[4]}') elif user[3].lower() == 'male': print(f'{user[0]} {user[1]} is {user[2]} years old, his relationship status is {user[4]}') main()
import random def pick_sentence(sentences): return sentences[random.randint(0, len(sentences)-1)] questions = ['Hva gjør du', 'Hvordan går det', 'Hvorfor heter du', 'Liker du å hete', 'Føler du deg bra', 'Hva har du gjort idag', 'Hva tenker du om framtida', 'Hva gjør deg glad', 'Hva gjør deg trist'] follow_ups = ['Hvorfor sier du', 'Hva mener du med', 'Hvor lenge har du sagt', 'Hvilke tanker har du om', 'Kan du si litt mer om', 'Når tenkte du første gang på'] responses = ['Fint du sier det', 'Det skjønner jeg godt', 'Så dumt da', 'Føler meg også sånn', 'Blir trist av det du sier', 'Så bra', 'Du er jammen frekk'] def print_sentence(): no = 1 def main(): answer = 'ikke hade' name = input('Hva heter du? ') while answer != 'hade': print(f'{pick_sentence(questions)}, {name}?') answer = input('Svar: ') print(f'{pick_sentence(follow_ups)} {answer}?') input('Svar: ') print(f'{pick_sentence(responses)} {name}.') main()
#coding:utf-8 #设损失函数 loss=(w+1)^2,令w初值是常数5.反向传播就是求最优w,即求最小loss对应的w值 import tensorflow as tf #定义带优化参数w初值赋值5 w = tf.Variable(tf.constant(5,dtype=tf.float32)) #定义损失函数loss loss = tf.square(w+1) #定义反向传播 train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss) #生成会话,训练40轮 with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) for i in range(40): sess.run(train_step) w_val = sess.run(w) loss_val = sess.run(loss) print "After %s steps: w is %f, loss is %f." % (i,w_val,loss_val)
""" binary trees have at most two child nodes. binary serch trees are a special case of binary trees and they have an order where the nodes on the left are smaller than the father and the nodes on the right are grater than the father, olso elements are unique. (serching hear is very easy). en python se puede ocupar mayor e igual simbolos con strings basado en orden alfabetico. """ class BinarySearchTreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def add_child(self, data): if data == self.data: return if data < self.data: #add data in left subtree if self.left: self.left.add_child(data) else: self.left = BinarySearchTreeNode(data) else: if self.right: self.right.add_child(data) else: self.right = BinarySearchTreeNode(data)
import heapq import random class BuySell: def __init__(self): self.buy = [] self.sell = [] self.gen_rand() self.create_heap() self.work() def gen_rand(self): for i in range(10): self.buy.append(random.randint(0, 100)) self.sell.append(random.randint(0, 100)) print("Random Numbers") self.print_heap() def create_heap(self): heapq.heapify(self.buy) heapq.heapify(self.sell) print("Heapify") self.print_heap() def print_heap(self): print("buy: ", self.buy) print("sell: ", self.sell) print("") def work(self): print("Working") for i in range(len(self.buy)): self.print_heap() if self.buy[0] < self.sell[0]: heapq.heappop(self.buy) else: heapq.heappop(self.buy) heapq.heappop(self.sell) if __name__ == '__main__': BuySell()
def glosarium(huruf): #fungsi untuk memetakan huruf bisa menjadi versi alaynya if (huruf == 'a'): return '@' elif (huruf == 'i'): return '1' elif (huruf == 'o'): return '0' elif (huruf == 's'): return '$' elif (huruf == 'e'): return '3' else: return huruf word = input('Enter a word:') if len(word) > 0 and word.isalpha(): #mengecek apakah input benar2 huruf temp = word.lower() #menkonversi text masukkan ke huruf kecil l = len(temp) new = '' #list of str kosong untuk menampung kata alay for i in range(l): if (i == (l - 3) and temp[(l-3):l] == 'nya'): #untuk akhiran -nya akan dijadikan .x new = new + '.x' break elif (i % 2 == 0): #untuk huruf dengan indeks genap akan diubah sesuai fungsi glosarium new = new + glosarium(temp[i]) elif (i % 2 == 1): #untuk huruf dengan indeks ganjil akan dijadikan huruf besar new = new + temp[i].upper() else: print('empty') print(new)
def merge_ranges(meetings): # Merge meeting ranges meetings.sort() out = [meetings[0]] for i,j in meetings[1:]: # k,l stand for the start and the end times of the previous held meeting k,l = out[-1] # now we want to know of l is smaller OR equal to j, then we will have to merge if i<=l: out[-1] = (k, max(j,l)) else: out.append((i,j)) return out
import turtle as t def dotting(distance, space): for i in range(0, int(distance/space)): t.penup() t.forward(space) t.dot() t.shape('arrow') t.speed('fast') dotting(80,10) t.left(360/7) dotting(80,10) t.left(360/7) dotting(80,10) t.left(360/7) dotting(80,10) t.left(360/7) dotting(80,10) t.left(360/7) dotting(80,10) t.left(360/7) dotting(80,10) t.left(360/7) dotting(80,10)
def sort(arr, s_index): arr_t = arr if s_index == arr_t.__len__()-1: return arr_t for i in range(0, s_index): if i<s_index-1: if arr_t[i]>arr_t[i+1]: temp = arr_t[i] arr_t[i] = arr_t[i+1] arr_t[i+1] = temp return sort(arr_t, s_index+1) a = input('n개의 데이터를 공백으로 구분해서 입력하세요.\n') arr1 = a.split(' ') arr2 = [] for i in arr1: arr2.append(int(i)) print(sort(arr2, 0))
''' list methods lst.append(x) - Appends element x to the list lst. lst.clear() - Removes all elements from the list–which becomes empty. lst.copy() - Returns a copy of the list. Copies only the list, not the elements in the list (shallow copy). lst.count(x) - Counts the number of occurrences of element x in the list. lst.extend(iter) - Adds all elements of an iterable iter (e.g. another list) to the list. lst.index(x) - Returns the position (index) of the first occurrence of value x in the list. lst.insert(i, x) - Inserts element x at position (index) i in the list. lst.pop() - Removes and returns the final element of the list. lst.remove(x) - Removes and returns the first occurrence of element x in the list. lst.reverse() - Reverses the order of elements in the list. lst.sort() - Sorts the elements in the list in ascending order. ''' list = [] list.append(2) list.copy() list.count(2) list.extend([2,5,7,9,8,4]) list.index(4) list.insert(5, 1000) list.pop() list.reverse() list.sort() print(list)
""" Specification: The list.count(x) method counts the number of occurrences of the element x in the list. """ lst = [2,5,4,2,6,3,5,4,2,6,3,2] print(lst.count(2)) #output: 4 """ Return value: The method list.count(value) returns an integer value set to the number of times the argument value appears in the list. If the value does not appear in the list, the return value is 0. """ """ To summarize, the list.count(value) method counts the number of times a list element is equal to value (using the == comparison). Here’s a reference implementation: """ def count(lst, value): ''' Returns the number of times a list element is equal to value''' count = 0 for element in lst: count += element == value return count lst = [1, 1, 1, 1, 2] print(lst.count(1)) # 4 print(lst.count(2)) # 1 print(lst.count(3)) # 0
""" The list.copy() method copies all list elements into a new list. The new list is the return value of the method. """ # lst = [2,4,6,7,8,9,3] # print(lst.copy()) #[2, 4, 6, 7, 8, 9, 3] """ Python List Copy Shallow In object-oriented languages such as Python, everything is an object. The list is an object and the elements in the list are objects, too. A shallow copy of the list creates a new list object—the copy—but it doesn’t create new list elements but simply copies the references to these objects. """ # lst_1 = [7,9, [2,4,6,8], "Ronny"] # lst_2 = lst_1.copy() # lst_2[2].append(34) # print(lst_2) # [7, 9, [2, 4, 6, 8, 34], 'Ronny'] # print(lst_1) # [7, 9, [2, 4, 6, 8, 34], 'Ronny'] """ Python List Copy Deep Having understood the concept of a shallow copy, it’s now easy to understand the concept of a deep copy. A shallow copy only copies the references of the list elements. A deep copy copies the list elements themselves which can lead to a highly recursive behavior because the list elements may be lists themselves that need to be copied deeply and so on. """ import copy lst = [3, 5, [8, 9], "Nijimbere"] lst_2 = copy.deepcopy(lst) lst_2[2].append(89) print(lst[2]) #[8, 9] print(lst_2) # [3, 5, [8, 9, 89], 'Nijimbere']
__author__ = 'Moran' num_of_numbers = 100 sum_of_squares = sum(x**2 for x in xrange(1, num_of_numbers+1)) print sum_of_squares square_of_sum = sum(x for x in xrange(1, num_of_numbers+1))**2 print square_of_sum print square_of_sum - sum_of_squares
import string cadenaADNPrueba =input("Poner la cadena de ADN a Analizar las cadenas promotoras: ") solucion = [] while 'TATAAA' in cadenaADNPrueba : restoCadena = cadenaADNPrueba.partition('TATAAA')[2] cadenaPromotora=restoCadena.partition('TATAAA')[0] solucion.append('TATAAA' + cadenaPromotora + 'TATAAA') cadenaADNPrueba= restoCadena.partition('TATAAA')[2] print('Cadenas promotoras :') print(solucion)
input = [ [7, 8, 0, 4, 0, 0, 1, 2, 0], [6, 0, 0, 0, 7, 5, 0, 0, 9], [0, 0, 0, 6, 0, 1, 0, 7, 8], [0, 0, 7, 0, 4, 0, 2, 6, 0], [0, 0, 1, 0, 5, 0, 9, 3, 0], [9, 0, 4, 0, 6, 0, 0, 0, 5], [0, 7, 0, 3, 0, 0, 0, 1, 2], [1, 2, 0, 0, 0, 7, 4, 0, 0], [0, 4, 9, 2, 0, 6, 0, 0, 7] ] def printSudoku(sudoku): for i in range(len(sudoku)): print(str(sudoku[i])) print("\n") # finds and returns the indices of the next empty box of the input sudoku; returns True if sudoku is full def findNextEmpty(sudoku): for i in range(len(sudoku)): for j in range(len(sudoku[i])): if sudoku[i][j] == 0: return [i, j] return False # checks the value of a box in the input sudoku with inidces i, j and returns true if the value is valid, false if the value is not def isValidNumber(sudoku, x, y): # check row for i in range(len(sudoku[x])): if ( sudoku[x][i] == sudoku[x][y] ) and ( i != y ): return False # check column for j in range(len(sudoku)): if ( sudoku[j][y] == sudoku[x][y] ) and ( j != x ): return False # check box for i in range( ( x // 3 ) * 3 , (( x // 3) * 3) + 3 ): for j in range(( y // 3 ) * 3 , (( y // 3) * 3) + 3): if ( sudoku[i][j] == sudoku[x][y] ) and ( ( i != x ) and ( j != y ) ): return False return True # recursive backtracking sudoku solving algorithm: returns true if sudoku is solved, false if there is no solution def bt_SudokuSolver(sudoku): # find the next empty box box = findNextEmpty(sudoku) # if no next empty box, return True ( i.e. sudoku is sovled ) if box == False: return True # try all values from 1 to 9 in box for i in range(1, 10): sudoku[box[0]][box[1]] = i # if the value is valid, recursively call the solver function to act on the next empty box if isValidNumber(sudoku, box[0], box[1]) == True: if bt_SudokuSolver(sudoku): return True sudoku[box[0]][box[1]] = 0 return False
#creation of Bank account import random,os class Data_base: def __init__(self): self.current_users={} class New_user(Data_base): def create_user(self,user_name,initial_deposit): self.new_password=random.randint(10000,99999) self.initial_deposit=initial_deposit self.user_name=user_name print(f"Congratulations {self.user_name} your account has been created successfully") print(f"Please remember this password for future use : {self.new_password}") print("..............................................................") self.current_users[self.user_name]=[self.initial_deposit,self.new_password] class Existing_user(New_user): def check_user(self,user_name,user_password,user_choice): self.user_name=user_name self.user_password=user_password self.user_choice=user_choice if self.user_name in self.current_users: print("User name identified") if self.user_password==self.current_users[self.user_name][1]: print("User password verified ") if self.user_choice==1: self.withdraw_amount=int(input("Enter the amount to withdraw : ")) if self.withdraw_amount>self.current_users[self.user_name][0]: print("Sorry insufficient balance") else: print("Transaction completed !") self.current_users[self.user_name][0]-=(self.withdraw_amount) print(f"Remaining balance : {self.current_users[self.user_name][0]}") elif self.user_choice==2: self.deposit_amount=int(input("Enter the amount to be deposited : ")) print(f"Transaction completed !") self.current_users[self.user_name][0]+=+(self.deposit_amount) print(f"Remaining balance : {self.current_users[self.user_name][0]}") else: print(f"Remaining account balance : {self.current_users[self.user_name][0]}") else: print("Please verify your password") else: print(f"user name : {self.user_name} is not identified") print("............................................................") if __name__=="__main__": cal=Existing_user() print("Simulation of Bank administration \n") while True: user_input=int(input("Enter 1-New User 2-Existing User 3-Clear Screen 4-Exit : ")) if user_input == 1: new_user_name=input("Enter your name : ") new_deposit=int(input("Enter your initial deposit : ")) cal.create_user(new_user_name,new_deposit) elif user_input == 2: existing_user_name=input("Enter your name : ") password=int(input("Enter your password : ")) user_choice=int(input("Enter 1-Withdraw amount 2-Deposit amount 3-Check Balance : ")) if user_choice == 1: final=1 elif user_choice == 2: final=2 elif user_choice == 3: final=3 else: print("Invalid Choice") cal.check_user(existing_user_name,password,final) elif user_input==3: os.system("cls") elif user_input==4: break else: print("Invalid Choice")
import pyttsx3 #import pyaudio import speech_recognition as sr import os import datetime name='' phno='' r=sr.Recognizer() c="is it correct?" def say(command): speaker=pyttsx3.init() speaker.say(command) speaker.runAndWait() def speak(): while(1): try: with sr.Microphone() as source: r.adjust_for_ambient_noise(source,duration=0.1) audio2=r.listen(source) text=r.recognize_google(audio2) print(text) return text except sr.RequestError as e: print("cannot identify the voice:{0}".format(e)) except sr.UnknownValueError: return "try again" while(1): q1="tell me your name" say(q1) name=speak() say(c) txt=speak() if (txt=='yes'): break else: continue while(1): q2="tell me your phone number?" say(q2) phno=speak() say(c) txt=speak() if (txt=='yes'): break else: continue y=datetime.datetime.now().strftime("%Y") m=datetime.datetime.now().strftime("%m") d=datetime.datetime.now().strftime("%d") file1=y+"_"+m+"_"+d+".txt" print(file1) f=open(file1,'a',encoding="utf-8") f.write("\n"+name+"\t"+phno) f.close()
#Challenge Code # Add support for abbreviations you commonly use or search the internet for some. #Allow the user to enter a complete tweet (160 characters or less) as a single line of text. # Search the resulting string for abbreviations and print a list of each abbreviation along with its decoded meaning. tweet = str(input('Enter tweet:\n')) tweet = tweet.upper() tweet_length = len(tweet) if (tweet_length < 161): if 'LOL' in tweet: print('LOL = laughing out loud') if 'BTW' in tweet: print('BTW = by the way') if 'BFN' in tweet: print('BFN = bye for now') if 'FTW' in tweet: print('FTW = for the win') if 'IRL' in tweet: print('IRL = in real life') if 'IDK' in tweet: print("IDK = I don't know") if 'TY' in tweet: print('TY = thank you') if 'YW' in tweet: print("YW = you're welcome") if 'RN' in tweet: print('RN = right now') if ('LOL' not in tweet) and ('BTW' not in tweet) and ('BFN' not in tweet) and ('FTW' not in tweet) and ('IRL' not in tweet) and ('IDK' not in tweet) and ('TY' not in tweet) and ('YW' not in tweet) and ('RN' not in tweet): print("Sorry, don't know that one") else: print('Tweet cannot be longer than 160 characters')
num = int(input()) factorial=1 if num<0: print("no negative values") elif num==0: print("factorial is 1") else: for i in range(1,num+1): factorial=factorial*i print(factorial)
def length(num): leng=0 while num!=0: leng+=1 num=num//10 return leng num=int(input("enter a number:")) temp=num rem=sum=0 len=length(num) while num>0: rem=num%10 sum=sum+int(rem**len) num=num//10 len-=1 if sum==temp: print("it is a disarium number") else: print("no it is not a disarium no.")
def NumberCheck(a): if a>0: print("number is positive.") elif a<0: print("number is negative.") else: print("number is zero.") a= float(input("enter a value: ")) NumberCheck(a)
class Solution: #@param n: Given a decimal number that is passed in as a string #@return: A string def binaryRepresentation(self, n): # write you code here arr = n.split(".") left = 0 right = 0 try: left = int(arr[0]) right = float("0." + arr[1]) except ValueError: return "ERROR" # get left part res = str("{0:b}".format(left)) # get right part # since we have one bit for [.] bits = 32 - len(res) base = 1.0 if right == 0: res return res else: rightBits = "" print bits for i in range (16): base /= 2 if right >= base: right -= base rightBits += "1" else: rightBits += "0" if right == 0: break # print base," ",right," ",rightBits print right if right == 0: return res + "." + rightBits else: return "ERROR" sol = Solution() print sol.binaryRepresentation("17817287.6418609619140625")
class LRU_cache: class d_link_list_node: def __init__(self, val): self.value = val self.pre = None self.next = None # this is node -1 def __init__(self): self.cache = self.d_link_list_node(0) self.hash_map = {} def print_list (self): pointer = self.cache while pointer is not None: print pointer.value,"->", pointer = pointer.next print "None" def get_val(self, key): # check element in hash_map (see if the element in cache) tmp = self.hash_map.get(key) if tmp is not None: # element exist tmp.pre.next = tmp.next if tmp.next is not None: tmp.next.pre = tmp.pre tmp.next = self.cache.next tmp.pre = self.cache self.cache.next.pre = tmp self.cache.next = tmp return tmp.value else: # woops, we dont have the element self.print_list() return -1 def set_val(self, key, val): tmp = self.hash_map.get(key) if tmp is not None: tmp.value = val tmp.pre.next = tmp.next if tmp.next is not None: tmp.next.pre = tmp.pre tmp.next = self.cache.next tmp.pre = self.cache self.cache.next.pre = tmp self.cache.next = tmp else: # create new node, append at front, # add to hash_map new_node = self.d_link_list_node(val) new_node.next = self.cache.next new_node.pre = self.cache if new_node.next is not None: new_node.next.pre = new_node self.cache.next = new_node self.hash_map[key] = new_node self.print_list() lru = LRU_cache() lru.set_val(0,"CHENYI") lru.set_val(1,"JIBEI") print lru.get_val(0) lru.set_val(2,"BOB") print lru.get_val(2) lru.set_val(3,"DREAM") lru.set_val(2,"HAHA") print lru.get_val(1) print lru.get_val(5)
# Round 1 question 1 # a robot can move 1,2 or 3 steps determine how much steps we need to go to not def ways_of_moving(n): if n == 0: return 0 if n == 1: return 1 if n == 2: return 2 if n == 3: return 4 dp = [0] * (n + 1) dp [0:4] = [0,1,2,4] for i in xrange(4,n + 1): dp[i] = dp[i-3] + dp[i-2] + dp[i-1] # print dp return dp[-1] # test print ways_of_moving(5) # question 2 # implement LRU class d_linked_list_node: def __init__(self,val): self.val = val self.next = None self.prev = None class last_recent_used: def __init__(self, max_size): self.head = d_linked_list_node(0) self.tail = d_linked_list_node(0) self.head.next = self.tail self.tail.prev = self.head self.data_map = {} self.max_size = max_size self.current_size = 0 def get(self, key): tmp = self.data_map.get(key) if tmp is None: return None tmp.prev.next = tmp.next tmp.next.prev = tmp.prev tmp.next = self.head.next self.head.next.prev = tmp tmp.prev = self.head self.head.next = tmp return tmp.val def put(self, key, val): tmp = self.data_map.get(key) if tmp is not None: tmp.val = val self.get(key) return if self.current_size == self.max_size: tmp = self.tail self.tail = self.tail.prev self.tail.next = None new_node = d_linked_list_node(val) new_node.next = self.head.next new_node.prev = self.head self.head.next = new_node new_node.next.prev = new_node # Round 2 question 1 # give a visitor list [5,7,9,2,11] represent which level that visitor want to go class min_stack_node: def __init__(self, val): self.val = val def __cmp__(self,b): return self.val - b.val class max_stack_node: def __init__(self, val): self.val = val def __cmp__(self,b): return b.val - self.val def min_clam(visitors, N): import heapq # record bigger Value min_stack = [] # record smaller value max_stack = [] min_sum = 0 cur_sum = 0 for val in visitors: heapq.heappush(min_stack, min_stack_node(val)) cur_sum += val - 1 min_sum = cur_sum for index in xrange(1,N): cur_sum -= len(min_stack) cur_sum += len(max_stack) if index == min_stack[0].val: heapq.heappop(min_stack) heapq.heappush(max_stack, max_stack_node(index)) if cur_sum < min_sum: min_sum = cur_sum if len(max_stack) == 0: break return min_sum # Round 4 question 1 implement a candidate_manage system # functions : get, add, delete, get_first_10 # similar to LRU class candidate_manage: # double list + hashmap pass
# implement a union find set class union_find(): self.father = [] def __init__(self, arr): self.arr = arr self.father = [ 0 for i in range(len(arr) + 1)] def find(self, val): if father[x] == 0: return x father[x] = find(father[x]) return father[x] def union(self, a,b): root_a = self.find(a) root_b = self.find(b) if root_a != root_b: father[root_a] = root_b
import urllib from BeautifulSoup import * url = raw_input ("Enter url or use 1 for Sample Problem, 2 for Actual Problem:") position = (int(raw_input("Enter position of URL :"))) - 1 count = (int(raw_input("Enter count of execution :"))) - 1 if url == '1': url = 'https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.html' if url == '2': url = 'https://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Zahira.html' html = urllib.urlopen(url).read() soap = BeautifulSoup(html) tags = soap('a') listwithUrls = list() print "Retrieving :" + url for i in tags: temp = i.get('href', None) listwithUrls.append(temp) for t in range(count): urlfromlist = urllib.urlopen(listwithUrls[position]) print "Retrieving :" + listwithUrls[position] del listwithUrls[:] soap2 = BeautifulSoup(urlfromlist) tags2 = soap2('a') for i in tags2: temp2 = i.get('href', None) listwithUrls.append(temp2) print "Last URL is :" + listwithUrls[position] #print listwithUrls
''' 9.4 Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer. ''' read_file = raw_input('Enter file name:') if len(read_file) < 1: read_file = 'mbox-short.txt' opfl = open(read_file) lst = list() for i in opfl: if i.startswith("From "): temp = i.split() lst.append(temp[1]) dct = dict() for t in lst: dct[t] = dct.get(t, 0) + 1 maxkee = None maxval = None for kee, val in dct.items(): if maxval == None or maxval < val: maxkee = kee maxval = val print maxkee, maxval
def add(number1,number2): return number1+ number2 def sub(number1,number2): return number1 - number2 def multi(number1,number2): return number1 * number2 def div(number1,number2): return number1 / number2 def factorial(number): fact=1 for i in range(1,number+1): fact=fact*i return fact def prime(number): if number > 1: for i in range(2,number//2): if (number % 2) == 0: print("number is not prime") break else: print("number is prime") else: print("number is not prime") return(number) def palinum(number): temp=number rev=0 while temp!=0: rev=(rev*10)+(temp%10) temp=temp//10 if rev==number: print(number,"Is Palindrome") else: print(number,"Is Not Palindrome") def palistr(string): l=string rev=l[::-1] if rev==l: print(string,"Is Palindrome") else: print(string,"Is Not Palindrome") def pangram(string): l=[] for i in range(97,123): c=chr(i) l.append(c) s=set(l) if s==string: print("String Is Pangram") else: print("String Is Not Pangram") def fibonacci(number): number1,number2=0,1 counter=0 if number <= 0: print("Please Enter Positive Number") while(counter<number): print(number1) number3=number1+number2 number1 = number2 number2 = number3 counter += 1 print("----------Calculator--------------") for i in range(1000): print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") print("5.Factorial") print("6.Prime") print("7.Palindrome Number") print("8.Palindrome String") print("9.Pangram") print("10.Fibonacci") print("11.Exit") choice=int(input("Enter Your Choice-")) if(choice==1): number1=float(input("Enter The 1st Number-")) number2=float(input("Enter The 2nd Number-")) print(number1,'+',number2,'=',add(number1,number2)) elif(choice==2): number1=float(input("Enter The 1st Number-")) number2=float(input("Enter The 2nd Number-")) print(number1,'-',number2,'=',sub(number1,number2)) elif(choice==3): number1=float(input("Enter The 1st Number-")) number2=float(input("Enter The 2nd Number-")) print(number1,'*',number2,'=',multi(number1,number2)) elif(choice==4): number1=float(input("Enter The 1st Number-")) number2=float(input("Enter The 2nd Number-")) print(number1,'/',number2,'=',div(number1,number2)) elif(choice==5): number=int(input("Enter The Number-")) print("Factorial Of",number,"Is-",factorial(number)) elif(choice==6): number=int(input("Enter The Number-")) prime(number) elif(choice==7): number=int(input("Enter The Number-")) palinum(number) elif(choice==8): string=input("Enter The String-") palistr(string) elif(choice==9): string=set(input("Enter The String-").lower()) pangram(string) elif(choice==10): number=int(input("Enter The Number-")) fibonacci(number) elif(choice==11): exit() else: print("Please Enter Valid Input")
import matplotlib.pyplot as plt import numpy as np x = np.load('x_train.npy') y = np.load('y_train.npy') # loding data w = np.zeros((len(x[0]))) lr = 1 iteration = 700 accum_square_grad = np.zeros((len(x[0]))) iter = [] loss_func = [] #print(w, accum_square_grad) #train for i in range(iteration): socre = np.dot(x, w) loss = y - socre grad = np.dot(x.transpose(),loss)*(-2) #Loss = (y-yhat)**2 accum_square_grad += grad**2 ada = np.sqrt(accum_square_grad) w = w - lr*grad/ada iter.append(i) loss_func.append(np.sqrt((loss**2).sum())) #iter = np.array(iter, float) #loss_func = np.array(loss_func, float) #print(loss_func.shape) #plot plt.plot(iter, loss_func) plt.xlim(0, iteration) plt.ylim(0, 1000) plt.xlabel("iteration") plt.ylabel("Loss funciotn") plt.title("Loss function vs iteration") plt.show() #經實驗測試 loss function在 550 iterations之後穩定的收斂
word = str(input("Please enter a word: ")) revsword = word[::-1] print(revsword) if word == revsword: print ('It is a palindrome') else: print ('It is not a palindrome')
# File - New File - Writing... - run module(Hot key : F5) print("#20180702","Made by joohongkeem",sep=' ',end='#\n') print("--------------------------------------") print("Hello Python") print("--------------------------------------") a="Hello" print("a="+a) print("a*3="+a*3) print("--------------------------------------") a=5 b=2 print("a =",a,",b =",b) print("a + b ="+str(a+b)) print("a - b ="+str(a-b)) print("a * b ="+str(a*b)) print("a / b ="+str(a/b)) print("a % b =",(a%b)) print("a // b =",(a//b)) print("a ** b =",(a**b)) print("--------------------------------------") var1 = "aaa" var2 = "aaa" print("var1="+var1,"var2="+var2) print("var1==var2 ->",var1==var2) print("var1 is var2 ->",var1 is var2) print("var1 is not var2 ->",var1 is not var2) print("id(var1)=",id(var1),"id(var2)=",id(var2)) print("--------------------------------------") a=3 print("a="+str(a)) if(a>0): #Identation !! (recommend : space 4 times) print("Positive Num") elif(a==0): print("Zero Num") else: print("Negative Num") print("--------------------------------------") type(2+3j) # <class 'complex'> var1=1+3j var2=var1.conjugate() print("var1=",var1,"var2=",var2) print("var1*var2=",var1*var2) print("--------------------------------------") int(3.5) # 3 2e3 # 2000.0 float("1.6") # 1.6 float("inf") # inf float("-inf") # -inf bool(0) # False. 숫자에서 0만 False임, bool(-1) # True bool("False") # True a = None # a는 None a is None # a가 None 이므로 True print("--------------------------------------")
#改变浏览器窗口的位置 #driver.get_window_position()/不支持谷歌浏览器 import time from selenium import webdriver driver=webdriver.Firefox() url="http://www.baidu.com" driver.get(url) time.sleep(5) #获取当前浏览器在屏幕上的位置,返回的是字典对象 position=driver.get_window_position() print("当前浏览器所在位置的横坐标:",position['x']) print("当前浏览器所在位置的纵坐标:",position['y']) #设置当前浏览器在屏幕上的位置 print(driver.set_window_rect(y=200,x=400)) #设置浏览器位置后,再次获取浏览器的 位置信息 driver.get_window_position() driver.maximize_window() driver.close()
# A year is a leap year if it is divisible by 4, unless it is the first year of a century and it is not divisible by 400. # # For example: # # 1956 is a leap year because 1956 is divisible by 4. # 1957 is not a leap year, because it is not divisible by 4. # 1900 is not a leap year, despite the fact that it is divisible by 4, because 1900 is the first year of a century and 1900 is not divisible by 400. # 1600 is a leap year, because 1600 is divisible by 4 and 1600 (although it is the first year of a century) is divisible by 400 # Write a function is_leap that takes a year as a parameter and returns True if the year is a leap year, False otherwise. def is_leap(year): if year % 10 == 0 and year % 400 == 0: return True elif year % 10 == 0 and year % 400 != 0: return False elif year % 4 == 0: return True else: return False # assert is_leap(1944) == True # assert is_leap(2011) == False # assert is_leap(1986) == False
import unittest from mergesort import mergesort from insertionsort import insertionsort class TestSort(unittest.TestCase): def test_mergesort(self): data = [1, 4, 3, 9, 6, 12, 7, 4, 8] dataS = data mergesort(data, 0, len(data) - 1) dataS.sort() self.assertEqual(data, dataS) def test_insertionsort(self): data = [1, 4, 3, 9, 6, 12, 7, 4, 8] dataS = data insertionsort(data) dataS.sort() self.assertEqual(data, dataS) if __name__ == "__main__": unittest.main()
import math def mergesort(array, p, r): if p < r: q = math.floor((p + r)/2) mergesort(array, p, q) mergesort(array, q + 1, r) merge(array, p, q, r) def merge(array, p, q, r): n1 = q - p + 1 n2 = r - q L = [] R = [] for i in range(n1): L.append(array[p+i]) for j in range(n2): R.append(array[q+j+1]) L.append(math.inf) R.append(math.inf) i, j = 0, 0 for k in range(p, r + 1): if L[i] <= R[j]: array[k] = L[i] i += 1 else: array[k] = R[j] j += 1
from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf # load the data # image size 28x28 px, output 1 int # 60,000 training data, 10,000 test data mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) # let there be model x = tf.placeholder(tf.float32, [None, 784]) y_true = tf.placeholder(tf.float32, [None, 10]) w = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y_pred = tf.nn.softmax(tf.matmul(x, w) + b) # define criteria cross_entropy = -tf.reduce_mean(y_true * tf.log(y_pred)) * 1000.0 correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y_true, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # train train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) for i in range(2000): batch_xs, batch_ys = mnist.train.next_batch(500) if i%100 == 0: train_accuracy = accuracy.eval(session=sess,feed_dict={x:batch_xs, y_true: batch_ys}) print("step %d, training accuracy %.3f"%(i, train_accuracy)) sess.run(train_step, feed_dict={x: batch_xs, y_true: batch_ys}) # evaluate print("test accuracy %g"%accuracy.eval(session=sess,feed_dict={x: mnist.test.images, y_true: mnist.test.labels}))
""" PkPy: Package to develop a first order ODE Solver and Visualizer for PK in Python Version1: Just solve one equation typed in interactively by user. No GUI yet! Author: Sudin Bhattacharya 7/28/16 """ from sympy import * from math import * import parser import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint # Function to enter and parse diff. eq. def diff_eqs(): """Reads in equation from user and returns variables and RHS expressions""" var_list = [] expr_list = [] eq_string = input("Type in the diff. eq. in the form x' = f(x): ") # Parse the equation string var_string = eq_string.split("=")[0].split("'")[0].strip() rhs_string = eq_string.split("=")[1].strip() # Assign variable symbol to variable name to process with sympy var = symbols(var_string) exec(var_string + " = symbols('" + var_string + "')") # Evaluate RHS of entered diff. eq. rhs_expr = sympify(rhs_string) rhs_expr = expand(rhs_expr) # Append variables and expressions to list var_list.append(var) expr_list.append(rhs_expr) return (var_list, expr_list) # Function to enter initial condition def init_conds(): """Reads in and returns initial conditions for variables""" ic_list = [] ic_string = input("Enter initial value of variable: ") ic_val = float(ic_string) ic_list.append(ic_val) return ic_list # Function to enter stop time and time increment def time_params(): """Reads in and returns stop time and time increment""" stop_time = float(input("Enter stop time: ")) time_inc = float(input("Enter time increment: ")) return (stop_time, time_inc) # Function to return derivatives def f_derivs(varList, varVals, exprList, t): """Returns derivatives evaluated at time t""" derivVals = [] numVars = len(varVals) for i in range(numVars): derivVal = exprList[i].subs(varList[i], varVals[i]) derivVals.append(derivVal) return derivVals # --- Main code block --- # Call function diff_eqs() varList, exprList = diff_eqs() # Call function init_conds() icList = init_conds() # Call function time_params() stopTime, timeInc = time_params() # Set up time array for ODE solver t = np.arange(0., stopTime, timeInc) # Bundle parameters for ODE solver params = []
#!/usr/bin/env python import RPi.GPIO as GPIO import zx import time LED_RED = 22 LED_YELLOW = 23 LED_GREEN = 24 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(LED_RED, GPIO.OUT) print(""" This example will recognise left/right swipes and toggle GPIO pin 22 on and off. You should also see the gesture names printed as they are recognised. """) while True: if zx.gesture_available(): gesture = zx.get_gesture() gesture_name = zx.gesture_name(gesture) speed = zx.get_speed() print("Gesture: {} {}: {}".format(gesture, speed, gesture_name)) if gesture == zx.SWIPE_LEFT: GPIO.output(LED_RED, GPIO.HIGH) if gesture == zx.SWIPE_RIGHT: GPIO.output(LED_RED, GPIO.LOW) time.sleep(0.01)
#print("Fuck you Keegan") #Daryn = "Big Poppa" #print("Hey " + Daryn + " I Love You!") #print(f'Hey {Daryn} {69 * 420}') import math CalcFunctions = ["1. Addition", "2. Subtraction", "3. Multiplication", "4. Division", "5. Squared", "6. Cubed", "7. Square Root"] CalcSymbols = ["+", "-", "*", "/", "²", "³", "√"] def ask1(): global n1 n1 = input("Please enter a whole number.") if not n1.isdigit(): return ask1() def ask2(): global Method print("Please choose a function by entering the corresponding number.") print(*CalcFunctions, sep = "\n") Method = input() if not Method.isdigit(): return ask2() def ask3(): global n2 n2 = input("Please enter a second whole number.") if not n2.isdigit(): return ask3() ask1() ask2() if Method == "5": solve = int(n1) ** 2 print(n1, CalcSymbols[int(Method) - 1]) print("Your answer is:") print(solve) quit() if Method == "6": solve = int(n1) ** 3 print(n1, CalcSymbols[int(Method) - 1]) print("Your answer is:") print(solve) quit() if Method == "7": print(n1, CalcSymbols[int(Method) - 1]) print("Your answer is:") print(math.sqrt(int(n1))) quit() ask3() if Method == "1": solve = int(n1) + int(n2) elif Method == "2": solve = int(n1) - int(n2) elif Method == "3": solve = int(n1) * int(n2) else: solve = int(n1) / int(n2) print(n1, CalcSymbols[int(Method) - 1], n2) print("Your answer is:") print(solve)
#nomenclature to bed format import re import os print("Covert nomenclature to bed") end = '' for line in iter(input, end): lo = re.search(r'(.*)\s(\d{1,2}|\w)(.*)[(](\d*)[_](\d*)[)](x|\s)(.*)', line) chromelo = lo.group(2) start=lo.group(4) end=lo.group(5) print("chr" + chromelo + "\t" + start + "\t" + end)
#!/usr/bin/env python # coding: utf-8 import sys # メイン関数 def main(): a, b = set(), set() with open(sys.argv[1]) as file: for line in file: w = line.rstrip('\n') a.add(w) with open(sys.argv[2]) as file: for line in file: w = line.rstrip('\n') b.add(w) c = a & b with open(sys.argv[3], 'w') as file: for w in sorted(c): file.write('%s\n' % w) # エントリポイント if __name__ == '__main__': main()
#The Canny edge detector is an edge detection operator that uses a multi-stage algorithm to detect a wide range of edges in images. It was developed by John F. Canny in 1986. wikipedia #The Canny edge detection algorithm is composed of 5 steps: # 1. Noise reduction # 2. Gradient calculation # 3. Non-maximum suppression # 4. Double threshold # 5. Edge Tracking by Hysteresis import cv2 import numpy as np from matplotlib import pyplot as plt img=cv2.imread ("messi5.jpg", cv2.IMREAD_GRAYSCALE) canny = cv2.Canny(img,100,200) titles=[' image ','canny'] images=[img,canny] for i in range (2): plt.subplot (1, 2, i + 1) ,plt. imshow (images [i], 'gray') plt.title (titles[i]) plt.xticks ([]),plt.yticks ([]) plt.show()
class BankAccount: interest_rate = 0.01 accounts = [] def __init__(self, balance = 0): self.balance = balance def deposit(self, credit): self.balance += credit return self.balance def withdraw(self, debits): self.balance -= debits return self.balance def __repr__(self): return f'{self.balance}' @classmethod def create(cls): new_account = BankAccount() cls.accounts.append(new_account) return new_account @classmethod def total_funds(cls): return sum(account.balance for account in cls.accounts) # use the cls for calling callmethod level and .instance for referencing the intance method @classmethod def interest_time(cls): for account in cls.accounts: account.balance = account.balance * (1 + cls.interest_rate) return account.balance # my_account = BankAccount.create() # your_account = BankAccount.create() my_account = BankAccount.create() your_account = BankAccount.create() print(my_account.balance) # 0 print(BankAccount.total_funds()) # 0 my_account.deposit(200) your_account.deposit(1000) print(my_account.balance) # 200 print(your_account.balance) # 1000 print(BankAccount.total_funds()) # 1200 BankAccount.interest_time() print(my_account.balance) # 202.0 print(your_account.balance) # 1010.0 print(BankAccount.total_funds()) # 1212.0 my_account.withdraw(50) print(my_account.balance) # 152.0 print(BankAccount.total_funds()) # 1162.0
#Decimal to Binary from challenge #You are given a decimal (base 10) number, print its binary representation. #Yan Zverev #2015 def convertToBinary(number): counter = 2 binaryNumber = '' while counter*2 <=number: counter = counter *2 while counter > 0: if(number-counter) >= 0: binaryNumber+="1" number = number - counter counter = int(counter/2) else: binaryNumber+="0" counter = int(counter/2) return binaryNumber binString = convertToBinary(20) print(binString,":") if binString[2] == binString[3]: print("true") else: print("false")
def main(): program = [] with open('input.txt', 'r') as f: for line in f: program.append(line.strip()) # print(program) # print(counter) # Part 1 code, acc = computer(program) print(f'Part 1: Code: {code} Accumulator: {acc}') # Part 2 for index, instruction in enumerate(program): parsed = parse_instruction(instruction) if parsed[0] == 'nop': parsed[0] = 'jmp' elif parsed[0] == 'jmp': parsed[0] = 'nop' new_ins = create_instruction(parsed) program[index] = new_ins print(f'{instruction} -> {new_ins}') # execute the new code code, acc = computer(program) if code == -1: program[index] = instruction # restore the original instruction elif code == 0: print(f'Part 2: Code: {code} Accumulator: {acc}') break def computer(program): pc = 0 accumulator = 0 counter = [] for i in range(len(program)): counter.append(0) while pc < len(program) and counter[pc] < 1: counter[pc] += 1 ins = parse_instruction(program[pc]) if ins[0] == 'acc': if ins[1] == '+': accumulator += ins[2] else: accumulator -= ins[2] pc += 1 if ins[0] == 'jmp': if ins[1] == '+': pc += ins[2] else: pc -= ins[2] if ins[0] == 'nop': pc += 1 if pc < len(program): return [-1, accumulator] else: return [0, accumulator] def parse_instruction(ins): parts = ins.partition(' ') plus_minus = parts[2][:1] number = parts[2][1:] return [parts[0], plus_minus, int(number)] def create_instruction(parts): return parts[0] + ' ' + parts[1] + str(parts[2]) if __name__ == '__main__': main()
num1 = input("Enter your first number: ") num2 = input("Enter your second number: ") result = float(num1) + float(num2) print(f"The result of your 2 number combine is {str(result)}") data = 0 data += 1 print(data) theA = int(2304) print(theA)
# if you run lambda code in this kind of type the system will transform to a function # because lambda is normally used when you need variable instead of function and 1 time use so just store variable instead function # this will create a function that add 10 # add10 = lambda x: x+10 # so lambda then the input argument then ":" then the output # mult = lambda x,y: x*y points2d = [(1, 2), (14, 2), (3, 4), (5, -2)] # this add function key inside using lamda to sort this specific list by the index 1 or y value def sorty_by_y(x): return x[1] # this function is the same with the lambda points2d_sorted_by_y = sorted(points2d, key=lambda x: x[1]) points2d_sorted_by_x = sorted(points2d, key=lambda x: x[0]) points2d_sorted_by_sum = sorted(points2d, key=lambda x: x[0] + x[1]) print(points2d) print(points2d_sorted_by_y) print(points2d_sorted_by_x) print(points2d_sorted_by_sum)
# Linear Regression # Import Libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt # Load Dataset dataset = pd.read_csv('./dataset/Salary_Data.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:,-1].values # Split Dataset into training set and test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0) # Fit and Predict Linear Regression Model from scikit learn from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) y_pred = regressor.predict(X_test) # Visualizing the Training Set plt.scatter(X_train, y_train, color='r') plt.plot(X_train, regressor.predict(X_train), color='b') plt.xlabel('Year Experience') plt.ylabel('Salary') plt.title('Salary vs. Experience (Training Set)') plt.show() # Visualizing the Test Set plt.scatter(X_test, y_test, color='r') plt.plot(X_train, regressor.predict(X_train), color='b') plt.xlabel('Year Experience') plt.ylabel('Salary') plt.title('Salary vs. Experience (Test Set)') plt.show()
# ライブラリのインポート import numpy as np import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import MinMaxScaler # データセットの読み込み df = pd.read_csv("Social_Network_Ads.csv") # ラベルエンコーディング処理 le=LabelEncoder() df['Gender']=le.fit(df['Gender']).transform(df['Gender']) # 正規化 scaler = MinMaxScaler() df.loc[:,:] = scaler.fit_transform(df) df.head() # 特徴量と目的変数の選定 X = df[["Gender","Age", "EstimatedSalary"]] y = df["Purchased"] # テストデータ分割 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # KNNのインスタンス定義 knn = KNeighborsClassifier(n_neighbors=6) # モデルfit knn.fit(X,y) #スコア計算 score = format(knn.score(X_test, y_test)) print('正解率:', score)
# 8.7 Calling a Method on a Parent Class class A: def spam(self): print('A.spam') class B(A): def spam(self): print('B.spam') super().spam() # Call parent spam() #b = B() #b.spam() # Output: # B.spam # A.spam # super() is the handling of the __init__() method to make sure that # parents are properly initialized. class A: def __init__(self): self.x = 0 class B(A): def __init__(self): super().__init__() self.y = 0 b = B() #print(b.x, b.y) # 0 0 # Mutiple inheritance class Base: def __init__(self): print('Base.__init__()') class A(Base): def __init__(self): super().__init__() print('A.__init__()') class B(Base): def __init__(self): super().__init__() print('B.__init__()') class C(A,B): def __init__(self): super().__init__() print('C.__init__()') c = C() # Base.__init__() # B.__init__() # A.__init__() # C.__init__()
# 1.9 Finding Commonalities in Two Dictionaries a = { 'x': 1, 'y': 2, 'z': 3 } b = { 'w': 10, 'x': 11, 'y': 2 } # Find keys in common key_comm = a.keys() & b.keys() # Find keys in a that are not in b key_diff = a.keys() - b.keys() # Find (key, value) pairs in common item_comm = a.items() & b.items() print(key_comm) # {'x', 'y'} print(key_diff) # {'z'} print(item_comm) # {('y', 2)}
# Class and Objects class MyClass: name = "pingsoli" def print_info(self): print("this is a message inside the class.") myobj = MyClass() #myobj.print_info() # Exercise class Vehicle: name = "" kind = "car" color = "" value = 100.00 def description(self): desc_str = "%s is a %s %s worth $%.2f" % ( self.name, self.color, self.kind, self.value) return desc_str car1 = Vehicle() car1.name = "Fer" car1.color = "red" car1.value = 60000.00 car2 = Vehicle() car2.name = "Jump" car2.color = "blue" car2.value = 10000.00 #print(car1.description()) #print(car2.description()) # Fer is a red car worth $60000.00 # Jump is a blue car worth $10000.00 # @staticmethod and @classmethod difference class Date: def __init__(self, year, month, day): self.year = year self.month = month self.day = day @classmethod def from_string(cls, date_as_string): year, month, day = map(int, date_as_string.split('-')) date1 = cls(year, month, day) return date1 @staticmethod def is_valid_date(date_as_string): year, month, day = map(int, date_as_string.split('-')) return day <= 31 and month <= 12 and year <= 3999 date2 = Date.from_string('2018-01-02') print(Date.is_valid_date('2018-01-02')) # True
# List class ListNode: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self, head=None): self.head = head # Add an element in the tail of linked list def add_tail(self, node): head = self.head prev = None while head: prev = head head = head.next # Empty linked list if not prev: self.head = node else: prev.next = node # Add an element in the head of linked list def add(self, node): if not self.head: self.head = node else: node.next = self.head self.head = node def search(self, value): head = self.head while head: if head.value == value: return head head = head.next return None def reverse(self): prev = None head = self.head while head: temp = head.next head.next = prev prev = head head = temp self.head = prev def remove(self, value): # If delete head if self.head.value == value: tmp = self.head self.head = self.head.next del tmp return True prv = self.head nxt = self.head.next while nxt: if nxt.value == value: prv.next = nxt.next del nxt return True prv = nxt nxt = nxt.next return False def traverse(self): next_node = self.head while next_node: print('{} -> '.format(next_node.value), end='') next_node = next_node.next print('None') #n1 = ListNode(1) n2 = ListNode(2) n3 = ListNode(3) l = LinkedList() #l.add(n1) l.add(n2) l.add(n3) # l.traverse() # l.reverse() # l.traverse() if l.remove(4): l.traverse() else: print('Not Found element')
# __init__, __new__, __del__ methods # __new__ used rarely, and not so much useful, when a object is created, # __new__ method is frist to be called. # __init__ is very useful to initialize a object. # __del__ is used to comtome your own deleter. from os.path import join class FileObject: def __init__(self, filepath='.', filename='sample.txt'): # open a file filename in filepath in read and write mode self.file = open(join(filepath, filename), 'r+') def __del__(self): self.file.close() del self.file test = FileObject()
# 4.5 Iterating in Reverse a = [1, 2, 3, 4, 5] for x in reversed(a): print(x) # Output: # 5 # 4 # 3 # 2 # 1 # Implementing __reversed__. class Countdown: def __init__(self, start): self.start = start # Forward interator def __iter__(self): n = self.start while n > 0: yield n n -= 1 # Reverse iterator def __reversed__(self): n = 1 while n <= self.start: yield n n += 1
# 13.6 Executing an External Command and Getting Its Output import subprocess out_bytes = subprocess.check_output(['ls', '-a']) out_text = out_bytes.decode('utf-8') #print(out_text) # . # .. # 01.py # 02.py # 03.py # 04.py # 05.py # 06.py # .06.py.swp # Example of catching errors and getting the output created along with # exit code. # try: # out_bytes = subprocess.check_output(['cmd', 'arg1', 'arg2']) # except subprocess.CalledProcessError as e: # out_bytes = e.output # code = e.returncode #out_bytes = subprocess.check_output('grep python | wc > out', shell=True) # use subprocess.check_output is the easiest way to call external command. # But we can use subprocess.Popen for high performance. text = b''' hello world this is test goodbye ''' # Launch a command with pipes p = subprocess.Popen(['wc'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) # Send the data and get the output stdout, stderr = p.communicate(text) # To interpret as text, decode out = stdout.decode('utf-8') #err = stderr.decode('utf-8') print(out) # 4 6 34
# 2.8 Writing a Regular Expression for Multiline Patterns import re comment = re.compile(r'/\*(.*?)\*/') text1 = '/* this is a comment */' text2 = '''/* this is multiline comment */ ''' #print(comment.findall(text1)) # [' this is a comment '] #print(comment.findall(text2)) # [] comment = re.compile(r'/\*((?:.|\n)*?)\*/') # [' this is\n multiline comment '] #print(comment.findall(text2)) # Another approach comment = re.compile(r'/\*(.*?)\*/', re.DOTALL) # [' this is\n multiline comment '] print(comment.findall(text2)) # re.DOTALL works fine here, but not be suitable for # complicated situation. We should define own regular # expression instead.
# 2.14 Combining and Concatenating Strings parts = ['Is', 'Chicago', 'Not', 'Chicago?'] #print(' '.join(parts)) # Is Chicago Not Chicago? a = 'Is Chicago' b = 'Not Chicago?' #print('{} {}'.format(a, b)) # Is Chicago Not Chicago? #print(a + ' ' + b) # Is Chicago Not Chicago? # no + operator #a = 'hello' 'world' #print(a) # helloworld # NOTE: + operator is grossly inefficient due to memory and garbage collection data = ['ACME', 50, 91.1] #print(','.join(str(d) for d in data)) # ACME,50,91.1 #print(a + ':' + b + ':' + c) # Ugly #print(':'.join([a, b, c])) # Still ugly #print(a, b, c, sep=':') # Better
# 7.10 Carrying Extra State with Callback Functions # callback functions, (event handles, completion callback, etc.) # asynchronous processing. def apply_async(func, args, *, callback): # Compute the result result = func(*args) # Invoke the callback with the result callback(result) def print_result(result): print('Got: ', result) def add(x, y): return x + y #apply_async(add, (2, 3), callback=print_result) # Got: 5 # class ResultHandler: # def __init__(self): # self.sequence = 0 # # def handler(self, result): # self.sequence += 1 # print('[{}] Got: {}'.format(self.sequence, result)) # # r = ResultHandler() #apply_async(add, (2, 3), callback=r.handler) # [1] Got: 5 #apply_async(add, ('hello', 'world'), callback=r.handler) # [2] Got: helloworld # Using closure def make_handler(): sequence = 0 def handler(result): nonlocal sequence sequence += 1 print('[{}] Got: {}'.format(sequence, result)) return handler #handler = make_handler() #apply_async(add, (1, 2), callback=handler) #apply_async(add, ('hello', 'world'), callback=handler) # [1] Got: 3 # [2] Got: helloworld class SequenceNo: def __init__(self): self.sequence = 0 def handler(result, seq): seq.sequence += 1 print('[{}] Got: {}'.format(seq.sequence, result)) seq = SequenceNo() from functools import partial apply_async(add, (2, 3), callback=partial(handler, seq=seq)) apply_async(add, ('hello', 'world'), callback=partial(handler, seq=seq)) # [1] Got: 5 # [2] Got: helloworld
# Lambda Expression Learning # Map, Filter, Reduce # Basic usage f = lambda x, y : x + y #print(f(1, 1)) # 2 # Map # map(function_to_apply, list_of_inputs) items = [1, 2, 3, 4, 5] squared = list(map(lambda x: x ** 2, items)) #print(squared) # [1, 4, 9, 16, 25] def multiply(x): return (x*x) def add(x): return (x+x) # funcs = [multiply, add] # for i in range(5): # value = list(map(lambda x: x(i), funcs)) # print(value) # Output: # [0, 0] # [1, 2] # [4, 4] # [9, 6] # [16, 8] # Filter number_list = range(-5, 5) less_than_zero = list(filter(lambda x: x < 0, number_list)) #print(less_than_zero) # [-5, -4, -3, -2, -1] # Reduce product = 1 list = [1, 2, 3, 4] for num in list: product = product * num from functools import reduce product = reduce((lambda x, y: x * y), [1, 2, 3, 4]) print(product) # 24
# 12.2 Determining If a Thread Has Started from threading import Thread, Event import time def countdown(n, started_event): print('countdown starting') started_event.set() while n > 0: print('T-minus', n) n -= 1 time.sleep(2) # Create the event object that will be used to signal startup started_event = Event() # Lanuch the thread and pass the startup event #print('Lanuching countdown') #t = Thread(target=countdown, args=(10, started_event)) #t.start() # Wait for the thread to start #started_event.wait() #print('countdown is running') import threading import time class PeriodicTimer: def __init__(self, interval): self._interval = interval self._flag = 0 self._cv = threading.Condition() def start(self): t = threading.Thread(target=self.run) t.daemon = True t.start() def run(self): while True: time.sleep(self._interval) with self._cv: self._flag ^= 1 self._cv.notify_all() def wait_for_tick(self): with self._cv: last_flag = self._flag while last_flag == self._flag: self._cv.wait() # Example use of the timer ptimer = PeriodicTimer(5) ptimer.start() def countdown(nticks): while nticks > 0: ptimer.wait_for_tick() print('T-miuns', nticks) nticks -= 1 def countup(last): n = 0 while n < last: ptimer.wait_for_tick() print('Counting', n) n += 1 threading.Thread(target=countdown, args=(10,)).start() threading.Thread(target=countup, args=(5,)).start()
# 2.2 Matching Text at the Start or End of a String # usage: filename extensions, URL schemes and so on. # str.startswith() and str.endswith() filename = 'sample.txt' #print(filename.endswith('.txt')) # True url = 'http://www.python.org' #print(url.startswith('http:')) # True # Check multiple choice import os filenames = os.listdir('.') filter_filenames = [name for name in filenames if name.endswith(('.c', '.h'))] contains_py = any(name.endswith('.py') for name in filenames) #print(filter_filenames) # [] #print(contains_py) # True choices = ['http:', 'ftp:'] url = 'http://www.python.org' # url.startswith(choices) # Error Message: # Traceback (most recent call last): # File "02.py", line 24, in <module> # url.startswith(choices) # TypeError: startswith first arg must be str or a tuple of str, not list # Correct way uses tuple to wrap up. #print(url.startswith(tuple(choices))) # True # The behind code can achieve this too, but the former is more elegant. filename = 'sample.txt' #print(filename[-4:] == '.txt') # True url = 'https://www.google.com' #print(url[:5] == 'http:' or url[:6] == 'https:' or url[:4] == 'ftp:') # True
# 11.4 Generating a Range of IP Addresses from a CIDR Address import ipaddress net = ipaddress.ip_network('123.45.67.64/27') # for a in net: # print(a) # 123.45.67.64 # 123.45.67.65 # 123.45.67.66 # ... # 123.45.67.94 # 123.45.67.95 # Show all available ip address number #print(net.num_addresses) # 32 net6 = ipaddress.ip_network('12:3456:78:90ab:cd:ef01:23:30/125') # for a in net6: # print(a) # 12:3456:78:90ab:cd:ef01:23:30 # 12:3456:78:90ab:cd:ef01:23:31 # 12:3456:78:90ab:cd:ef01:23:32 # 12:3456:78:90ab:cd:ef01:23:33 # 12:3456:78:90ab:cd:ef01:23:34 # 12:3456:78:90ab:cd:ef01:23:35 # 12:3456:78:90ab:cd:ef01:23:36 # 12:3456:78:90ab:cd:ef01:23:37 # Show all available ipv6 ip address number #print(net6.num_addresses) # 8
# 1.16 Filtering Sequence Elements mylist = [1, 4, -5, 10, -7, 2, 3, -1] # [1, 4, 10, 2, 3] #print([n for n in mylist if n > 0]) pos = (n for n in mylist if n > 0) for x in pos: print(x) # Output: # 1 # 4 # 10 # 2 # 3 # Exception handling values = ['1', '2', '-3', '-', '4', 'N/A', '5'] def is_int(val): try: x = int(val) return True except ValueError: return False ivals = list(filter(is_int, values)) #print(ivals) # ['1', '2', '-3', '4', '5'] mylist = [1, 4, -5, 10, -7, 2, 3, -1] import math newlist = [math.sqrt(n) for n in mylist if n > 0] # [1.0, 2.0, 3.1622776601683795, 1.4142135623730951, 1.7320508075688772] # print(newlist) clip_neg = [n if n > 0 else 0 for n in mylist] #print(clip_neg) # [1, 4, 0, 10, 0, 2, 3, 0] addresses = [ '5412 N CLARK', '5148 N CLARK', '5800 E 58TH', '2122 N CLARK' '5645 N RAVENSWOOD', '1060 W ADDISON', '4801 N BROADWAY', '1039 W GRANVILLE', ] # compress() function picks out the items corresponding to True values. # Like filter(), compress() normally return an iterator. Thus, we need to # use list() to turn the result into a list if desired. counts = [ 0, 3, 10, 4, 1, 7, 6, 1 ] from itertools import compress more5 = [n > 5 for n in counts] filter_addr = list(compress(addresses, more5)) # ['5800 E 58TH', '4801 N BROADWAY', '1039 W GRANVILLE'] print(filter_addr)
# Generators, a bit difficult to understand. import random def lottery(): # return 6 numbers between 1 and 40 for i in range(6): yield random.randint(1, 40) # returns a 7th number between 1 and 45 yield random.randint(1, 45) #for random_number in lottery(): # print("And the next number is: %d" %(random_number)) # Exercise # Fabonacci, only use two variables def fib(): a, b = 1, 2 while True: yield a a, b = b, a + b import types if type(fib()) == types.GeneratorType: print("Good, The fib function is a generator") counter = 0 for n in fib(): print(n) counter += 1 if counter == 10: break
# 12.1 Starting and Stopping Threads # thread library can be used execute any Python callable in its own # thread. # Code to execute in an indepentdent thread import time def countdown(n): while n > 0: print('T-minus', n) n -= 1 time.sleep(5) # Create and lanuch a thread from threading import Thread t = Thread(target=countdown, args=(10,)) t.start() # t.is_alive() # t.join()
"""Helper functions for several calculation tasks (such as integration).""" import numpy as np from ase.units import kB from scipy import integrate import mpmath as mp def integrate_values_on_spacing(values, spacing, method, axis=0): """ Integrate values assuming a uniform grid with a provided spacing. Different integration methods are available. Parameters ---------- values : numpy.array Values to be integrated. spacing : int Spacing of the grid on which the integration is performed. method : string Integration method to be used. Currently supported: - "trapz" for trapezoid method - "simps" for Simpson method. axis : int Axis along which the integration is performed. Returns ------- integral_values : float The value of the integral. """ if method == "trapz": return integrate.trapz(values, dx=spacing, axis=axis) elif method == "simps": return integrate.simps(values, dx=spacing, axis=axis) else: raise Exception("Unknown integration method.") def fermi_function(energy, fermi_energy, temperature_K, energy_units="eV"): """ Calculate the Fermi function f(E) = 1 / (1 + e^((E-E_F)/(k_B*T))). Parameters ---------- energy : float or numpy.array Energy for which the Fermi function is supposed to be calculated in energy_units. fermi_energy : float Fermi energy level in energy_units. temperature_K : float Temperature in K. energy_units : string Currently supported: - eV Returns ------- fermi_val : float Value of the Fermi function. """ if energy_units == "eV": return fermi_function_eV(energy, fermi_energy, temperature_K) def entropy_multiplicator(energy, fermi_energy, temperature_K, energy_units="eV"): """ Calculate the multiplicator function for the entropy integral. Entropy integral is f(E)*log(f(E))+(1-f(E)*log(1-f(E)) Parameters ---------- energy : float or numpy.array Energy for which the Fermi function is supposed to be calculated in energy_units. fermi_energy : float Fermi energy level in energy_units. temperature_K : float Temperature in K. energy_units : string Currently supported: - eV Returns ------- multiplicator_val : float Value of the multiplicator function. """ if len(np.shape(energy)) > 0: dim = np.shape(energy)[0] multiplicator = np.zeros(dim, dtype=np.float64) for i in range(0, np.shape(energy)[0]): fermi_val = fermi_function(energy[i], fermi_energy, temperature_K, energy_units=energy_units) if fermi_val == 1.0: secondterm = 0.0 else: secondterm = (1 - fermi_val) * np.log(1 - fermi_val) if fermi_val == 0.0: firsterm = 0.0 else: firsterm = fermi_val * np.log(fermi_val) multiplicator[i] = firsterm + secondterm else: fermi_val = fermi_function(energy, fermi_energy, temperature_K, energy_units=energy_units) if fermi_val == 1.0: secondterm = 0.0 else: secondterm = (1 - fermi_val) * np.log(1 - fermi_val) if fermi_val == 0.0: firsterm = 0.0 else: firsterm = fermi_val * np.log(fermi_val) multiplicator = firsterm + secondterm return multiplicator def fermi_function_eV(energy_ev, fermi_energy_ev, temperature_K): """ Calculate the Fermi function f(E) = 1 / (1 + e^((E-E_F)/(k_B*T))). Parameters ---------- energy_ev : float Energy in eV. fermi_energy_ev : float Fermi energy level in eV. temperature_K : float Temperature in K. Returns ------- fermi_val : float Value of the Fermi function. """ return 1.0 / (1.0 + np.exp((energy_ev - fermi_energy_ev) / (kB * temperature_K))) def get_beta(temperature_K): """ Calculate beta = 1 / (k_B * T). Parameters ---------- temperature_K : float Temperature in K Returns ------- beta : float Thermodynamic beta. """ return 1 / (kB * temperature_K) def get_f0_value(x, beta): """ Get the F0 value for the analytic integration formula. Parameters ---------- x : float x value for function. beta : float Thermodynamic beta. Returns ------- function_value : float F0 value. """ results = (x+mp.polylog(1, -1.0*mp.exp(x)))/beta return results def get_f1_value(x, beta): """ Get the F1 value for the analytic integration formula. Parameters ---------- x : float x value for function. beta : float Thermodynamic beta. Returns ------- function_value : float F1 value. """ results = ((x*x)/2+x*mp.polylog(1, -1.0*mp.exp(x)) - mp.polylog(2, -1.0*mp.exp(x))) / (beta*beta) return results def get_f2_value(x, beta): """ Get the F2 value for the analytic integration formula. Parameters ---------- x : float x value for function. beta : float Thermodynamic beta. Returns ------- function_value : float F2 value. """ results = ((x*x*x)/3+x*x*mp.polylog(1, -1.0*mp.exp(x)) - 2*x*mp.polylog(2, -1.0*mp.exp(x)) + 2*mp.polylog(3, -1.0*mp.exp(x))) / (beta*beta*beta) return results def get_s0_value(x, beta): """ Get the S0 value for the analytic integration formula. Parameters ---------- x : float x value for function. beta : float Thermodynamic beta. Returns ------- function_value : float S0 value. """ results = (-1.0*x*mp.polylog(1, -1.0*mp.exp(x)) + 2.0*mp.polylog(2, -1.0*mp.exp(x))) / (beta*beta) return results def get_s1_value(x, beta): """ Get the S1 value for the analytic integration formula. Parameters ---------- x : float x value for function. beta : float Thermodynamic beta. Returns ------- function_value : float S1 value. """ results = (-1.0*x*x*mp.polylog(1, -1.0*mp.exp(x)) + 3*x*mp.polylog(2, -1.0*mp.exp(x)) - 3*mp.polylog(3, -1.0*mp.exp(x))) / (beta*beta*beta) return results def analytical_integration(D, I0, I1, fermi_energy_ev, energy_grid, temperature_k): """ Perform analytical integration following the outline given by [1]. More specifically, this function solves Eq. 32, by constructing the weights itself. Parameters ---------- D : numpy.array or float Either LDOS or DOS data. I0 : string I_0 from Eq. 33. The user only needs to provide which function should be used. Arguments are: - F0 - F1 - F2 - S0 - S1 I1 : string I_1 from Eq. 33. The user only needs to provide which function should be used. Arguments are: - F0 - F1 - F2 - S0 - S1 fermi_energy_ev : float The fermi energy in eV. energy_grid : numpy.array Energy grid on which the integration should be performed. temperature_k : float Temperature in K. Returns ------- integration_value : numpy.array or float Value of the integral. """ # Mappings for the functions further down. function_mappings = { "F0": get_f0_value, "F1": get_f1_value, "F2": get_f2_value, "S0": get_s0_value, "S1": get_s1_value, } # Check if everything makes sense. if I0 not in list(function_mappings.keys()) or I1 not in\ list(function_mappings.keys()): raise Exception("Could not calculate analytical intergal, " "wrong choice of auxiliary functions.") # Construct the weight vector. weights_vector = np.zeros(energy_grid.shape, dtype=np.float64) gridsize = energy_grid.shape[0] energy_grid_edges = np.zeros(energy_grid.shape[0]+2, dtype=np.float64) energy_grid_edges[1:-1] = energy_grid spacing = (energy_grid[1]-energy_grid[0]) energy_grid_edges[0] = energy_grid[0] - spacing energy_grid_edges[-1] = energy_grid[-1] + spacing if len(D.shape) > 1: real_space_grid = D.shape[0] integral_value = np.zeros(real_space_grid, dtype=np.float64) else: real_space_grid = 1 integral_value = 0 # Calculate the weights. for i in range(0, gridsize): # Calculate beta and x beta = 1 / (kB * temperature_k) x = beta*(energy_grid_edges[i]-fermi_energy_ev) x_plus = beta*(energy_grid_edges[i+1]-fermi_energy_ev) x_minus = beta*(energy_grid_edges[i-1]-fermi_energy_ev) # Calculate the I0 value i0 = function_mappings[I0](x, beta) i0_plus = function_mappings[I0](x_plus, beta) i0_minus = function_mappings[I0](x_minus, beta) # Calculate the I1 value i1 = function_mappings[I1](x, beta) i1_plus = function_mappings[I1](x_plus, beta) i1_minus = function_mappings[I1](x_minus, beta) # Some aliases for readibility ei = energy_grid_edges[i] ei_plus = energy_grid_edges[i+1] ei_minus = energy_grid_edges[i-1] weights_vector[i] = (i0_plus-i0)*(1 + ((ei-fermi_energy_ev)/(ei_plus-ei)))\ + (i0-i0_minus)*(1-((ei-fermi_energy_ev)/(ei-ei_minus))) - \ ((i1_plus-i1) / (ei_plus-ei)) + ((i1 - i1_minus) / (ei - ei_minus)) if real_space_grid == 1: integral_value += weights_vector[i] * D[i] else: for j in range(0, real_space_grid): integral_value[j] += weights_vector[i] * D[j, i] return integral_value
from Objects import * # Validate a user’s password by passing the username and password, both strings. # The program should clearly report # - Success # - Failure: no such user # - Failure: bad password def authenticate(user, password): if any(x for x in allUsers if x.name == user): for i in allUsers: if (i.name == user): if(i.password == password): print(":::successfully authenticated") else: print(":::Bad Password") else: print(":::Bad User")
import tkinter as tk Large_Font = ("Verdana",12) class seaoapp(tk.Tk): #this will alwase run when you start your class #like when you start computer there are programmes shoud be run # args any number of variable to the functions #kwargs to pass adictionary thro the function def __init__ (self,*args,**kwargs): ''' this is a basic programme to have multi screen on tkinter ''' # to initilaize tk tk.Tk.__init__(self,*args,**kwargs) #to make a contanier for your programme container = tk.Frame(self) container.pack(side='top',fill="both",expand=True) container.grid_rowconfigure(0,weight=1) container.grid_columnconfigure(0,weight=1) self.frames={} frame = StartPage(container,self) self.frames[StartPage] = frame #we will use grid #sticky = north south est west to stritch every thing to the size of the window frame.grid(row=0,column=0,sticky="nsew") self.show_frame(StartPage) def show_frame(self,cont): frame = self.frames[cont] frame.tkraise() class StartPage(tk.Frame): def __init__(self,parent,controller): tk.Frame.__init__(self,parent) label = tk.Label(self,text="START Page",font =Large_Font) label.pack(pady=10,padx=10) app = seaoapp() app.mainloop()
def RFcheck(RF): while (RF<1 or RF>3): RF = raw_input("Please enter a valid reading frame "); print RF; print "success!"
#!/usr/bin/env python def modify_string(original): original += " that has been modified" def modify_string_return(original): original += " that has been actually modified" return original test_string = "This is my test string" modify_string(test_string) print(test_string) test_string = modify_string_return(test_string) print(test_string)
#!/usr/bin/env python hello_str="Hello World" # Creating variables hello_int = 123 hello_bool = True hello_tuple = (12,21,44) hello_list = ["Hello",'this','is',"a",'list'] print(hello_list) # Another way of creating a list hello_list = list() hello_list.append("HEllo") hello_list.append("this") hello_list.append('is') hello_list.append('a') hello_list.append('string') print(hello_list) # Dictionary hello_dict = {"first_name": 'YMK', "last_name":'G', 'eye_color':'black'} print(hello_dict) # playing with list and dict print(hello_list[1]) print(hello_list[0]+"-WhatHappensNow") print(hello_list) hello_list[4] += "!!!" print(hello_list) print(hello_tuple) print(hello_tuple[0]) print(hello_tuple[1]) print(hello_tuple[2]) print(str(hello_tuple)) print("{0} {1} has {2} eyes...".format(hello_dict['first_name'], hello_dict['last_name'], hello_dict['eye_color']))
import sqlite3 # connect to database def connect_to_db(db_name): return sqlite3.connect(db_name) # insert to database def insert(list_data): conn = connect_to_db('home_test_db.sql') c = conn.cursor() try: c.execute( """ CREATE TABLE IF NOT EXISTS downloaded_tree_data ( id INTEGER PRIMARY KEY ,tree_name TEXT NOT NULL,tree_data INTEGER NOT NULL); """) except sqlite3.Error as e: print(e) insert_data = [] for data in list_data: insert_data.append((data['name'], data['size'])) c.executemany('INSERT INTO downloaded_tree_data(tree_name,tree_data) VALUES (?,?)', insert_data) conn.commit() conn.close() # delete all from table def delete_all(): conn = connect_to_db('home_test_db.sql') c = conn.cursor() c.execute("DELETE FROM downloaded_tree_data") conn.commit() conn.close() # select all from database def select_all(): conn = connect_to_db('home_test_db.sql') c = conn.cursor() c.execute("SELECT tree_name,tree_data FROM downloaded_tree_data") rows = c.fetchall() conn.close() tree_data = [] for row in rows: tree_data.append({'name': row[0], 'size': row[1]}) return tree_data # get searched node def get_node(node_name, node_size): conn = connect_to_db('home_test_db.sql') c = conn.cursor() if node_size == 'NaN': c.execute("SELECT tree_name,tree_data FROM downloaded_tree_data WHERE tree_name LIKE?", ('%' + node_name + '%',)) else: c.execute("SELECT tree_name,tree_data FROM downloaded_tree_data WHERE tree_name LIKE? AND tree_data=?", ('%' + node_name + '%', node_size)) rows = c.fetchall() conn.close() tree_data = [] for row in rows: tree_data.append({'name': row[0], 'size': row[1]}) return tree_data
# LISTA # LISTA GERALMENTE SÃO MUTAVEIS # ELEMENTOS HOMOGENEOS # append -> final da lista # extend: # insert: inserir um item em determinnada posição # remove: removve o valor do ittem que é iguaal ao parametro # pop: remomve o ultimo item da lista ou o da posição especifficada # clear: limpa a lissta # count: conta o numero de vezes que determinado valor aparece # del remomve o valaor da listat sem retorna-lo/ocaasionalmente limpa a lista # from collections import # squares = [x+1 for x in range(4,14)] # # Struct # lis = [] # dic = {} -> PODE SER SET # tup = () # # print(type(lis)) # print(type(dic)) # print(type(tup)) #pega o valor do for # Criando listas que armazenam o valor de x na itteração # squares = [x**2 for x in range(10)] # insere o valor no for # iteranndo e comparando se os vallores são iguais # print( [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]) # SEM PARENTESES PEGAA O VALOR DDO FOR(NAO É REGRA) # reSul = [x*2 for x in var] # COM PARENTESES # ESCREVE LISTAS COM TUPLAS DE DOIS VALORES # v = [(x, x**2) for x in range(1, 5)] # print(type(v[0]))
import itertools import random class Mapa(): def __init__(self): self.dicionario = {} self.inicio = (0, 0) self.fim = (0, 0) def reset(self): self.dicionario = {} self.inicio = (0, 0) self.fim = (0, 0) def gerarDicionario(self, numero_de_linhas: int): rows = range(numero_de_linhas) def rect(*sides): return {j-i*1j for i, j in itertools.product(*sides)} def coord(z): return (int(z.real), -int(z.imag)) def pick(iterable): return random.choice(list(iterable)) maze, seen, reseen = dict.fromkeys( rect(rows, rows), 'wall'), set(), set() pos = pick(maze) maze[pos] = 'start' while ...: ways = {d for d in (1, 1j, -1, -1j) if all(maze.get(pos+d*t) == 'wall' for t in rect({-1, 0, 1}, {1, 2}) - {1})} if ways: pos += pick(ways) seen.add(pos) if maze[pos] == 'wall': maze[pos] = 'free' elif seen: pos = seen.pop() reseen.add(pos) else: if len(reseen or seen) == 0: return self.gerarDicionario(numero_de_linhas) else: break maze[pick(reseen or seen)] = 'end' for posicao, tipo in maze.items(): if tipo == 'start': self.inicio = coord(posicao) elif tipo == 'end': self.fim = coord(posicao) self.dicionario[coord(posicao)] = tipo
def solution(bridge_length, weight, truck_weights): answer = 1 bridge = [0]*bridge_length cur = 0 while cur > 0 or len(truck_weights) > 0: cur -= bridge.pop(0) answer += 1 if len(truck_weights) > 0 and weight >= cur + truck_weights[0]: cur += truck_weights[0] bridge.append(truck_weights.pop(0)) else: bridge.append(0) if cur==0: answer -= 1 return answer
#%% # MODELO DE SIMULACION DE LIGA Y OPTIMIZACION DE MERCADO DE PASES DE LA PREMIER LEAGUE # TP Final Investigación Operativa - Juan Martín Lucioni y Matías Ayerza # SOBRE EL CODIGO #El código está dividido en dos partes, en primer lugar hay una celda (esta) que se encarga de armar y cargar a la consola la lógica detrás de la simulación y la optimización #Al final del código se encuentra la segunda celda, que funciona a manera de panel de control para el usuario, donde se pueden tocar y cambiar las variables deseadas para correr el modelo #Despues de definir las variables deseadas, correr la celda #Los datos provienen de https://fbref.com/en/comps/9/Premier-League-Stats # LINK AL GITHUB # https://github.com/MatuAyerza/tpfinalio2021 #Imports #Librerias import picos import pandas as pd import numpy as np import math import matplotlib.pyplot as plt import os from matplotlib.patches import Arc #Data team_stats_skills = pd.read_csv('league-stats-skill.csv') # new_team_stats_skills = pd.read_csv('new-league-stats-skill.csv') pl_players_stats_skills = pd.read_csv('pl-players-stats-skills.csv') bundes_player_stats = pd.read_csv('bundesliga-players-stats.csv') #Funciones de Graficos #Dibujo de Cancha con jugadores #Source: https://fcpython.com/visualisation/drawing-pitchmap-adding-lines-circles-matplotlib def createPitch(playernames,d,m,ma,f): #Create figure fig = plt.figure() ax = fig.add_subplot(1, 1, 1) #Pitch Outline & Centre Line plt.plot([0, 0], [0, 90], color="black") plt.plot([0, 130], [90, 90], color="black") plt.plot([130, 130], [90, 0], color="black") plt.plot([130, 0], [0, 0], color="black") plt.plot([65, 65], [0, 90], color="black") #Left Penalty Area plt.plot([16.5, 16.5], [65, 25], color="black") plt.plot([0, 16.5], [65, 65], color="black") plt.plot([16.5, 0], [25, 25], color="black") #Right Penalty Area plt.plot([130, 113.5], [65, 65], color="black") plt.plot([113.5, 113.5], [65, 25], color="black") plt.plot([113.5, 130], [25, 25], color="black") #Left 6-yard Box plt.plot([0, 5.5], [54, 54], color="black") plt.plot([5.5, 5.5], [54, 36], color="black") plt.plot([5.5, 0.5], [36, 36], color="black") #Right 6-yard Box plt.plot([130, 124.5], [54, 54], color="black") plt.plot([124.5, 124.5], [54, 36], color="black") plt.plot([124.5, 130], [36, 36], color="black") #Prepare Circles centreCircle = plt.Circle((65, 45), 9.15, color="black", fill=False) centreSpot = plt.Circle((65, 45), 0.8, color="black") leftPenSpot = plt.Circle((11, 45), 0.8, color="black") rightPenSpot = plt.Circle((119, 45), 0.8, color="black") #Draw Circles ax.add_patch(centreCircle) ax.add_patch(centreSpot) ax.add_patch(leftPenSpot) ax.add_patch(rightPenSpot) #Prepare Arcs leftArc = Arc((11, 45), height=18.3, width=18.3, angle=0, theta1=310, theta2=50, color="black") rightArc = Arc((119, 45), height=18.3, width=18.3, angle=0, theta1=130, theta2=230, color="black") # #Draw Arcs ax.add_patch(leftArc) ax.add_patch(rightArc) #Tidy Axes plt.axis('off') #Players playername = [] tempName = [] for i in range(len(playernames)): tempName.append(playernames[i].partition("\\")[2]) if tempName[i].find('-') == -1: playername.append(tempName[i]) else: playername.append(tempName[i].partition("-")[2]) if playername[i].find('-') != -1: playername[i] = playername[i].replace('-', " ") if d == 4 and m == 3 and ma == 1 and f == 2 : print('Formacion 4312') player0 = plt.Circle((10, 45), 3, edgecolor="black", facecolor='orange', fill=True, label=playername[0]) plt.text(3, 33, playername[10]) ax.add_patch(player0) player1 = plt.Circle((37, 15), 3, edgecolor="black", facecolor='yellow', fill=True, label=playername[1]) plt.text(30, 5, playername[9]) ax.add_patch(player1) player2 = plt.Circle((37, 75), 3, edgecolor="black", facecolor='yellow', fill=True, label=playername[2]) plt.text(30, 65, playername[8]) ax.add_patch(player2) player3 = plt.Circle((30, 55), 3, edgecolor="black", facecolor='yellow', fill=True, label=playername[3]) plt.text(23, 45, playername[7]) ax.add_patch(player3) player6 = plt.Circle((30, 35), 3, edgecolor="black", facecolor="yellow", fill=True, label=playername[6]) plt.text(23, 25, playername[6]) player4 = plt.Circle((70, 25), 3, edgecolor="black", facecolor="green", fill=True, label=playername[4]) plt.text(65, 15, playername[4]) ax.add_patch(player4) player5 = plt.Circle((55, 45), 3, edgecolor="black", facecolor="green", fill=True, label=playername[5]) plt.text(45, 35, playername[5]) ax.add_patch(player5) ax.add_patch(player6) player7 = plt.Circle((70, 65), 3, edgecolor="black", facecolor="green", fill=True, label=playername[7]) plt.text(65, 55, playername[3]) ax.add_patch(player7) player8 = plt.Circle((90, 45), 3, edgecolor="black", facecolor="blue", fill=True, label=playername[8]) plt.text(83, 35, playername[2]) ax.add_patch(player8) player9 = plt.Circle((107, 60), 3, edgecolor="black", facecolor="blue", fill=True, label=playername[9]) plt.text(100, 50, playername[1]) ax.add_patch(player9) player10 = plt.Circle((107, 30), 3, edgecolor="black", facecolor="blue", fill=True, label=playername[10]) plt.text(100, 20, playername[0]) ax.add_patch(player10) #Display Pitch plt.show() elif d == 4 and m == 2 and ma == 3 and f == 1: print('Formacion 4231') player0 = plt.Circle((10, 45), 3, edgecolor="black", facecolor='orange', fill=True, label=playername[0]) plt.text(3, 33, playername[10]) ax.add_patch(player0) player1 = plt.Circle((37, 15), 3, edgecolor="black", facecolor='yellow', fill=True, label=playername[1]) plt.text(30, 5, playername[9]) ax.add_patch(player1) player2 = plt.Circle((37, 75), 3, edgecolor="black", facecolor='yellow', fill=True, label=playername[2]) plt.text(30, 65, playername[8]) ax.add_patch(player2) player3 = plt.Circle((30, 55), 3, edgecolor="black", facecolor='yellow', fill=True, label=playername[3]) plt.text(23, 45, playername[7]) ax.add_patch(player3) player6 = plt.Circle((30, 35), 3, edgecolor="black", facecolor="yellow", fill=True, label=playername[6]) plt.text(23, 25, playername[6]) ax.add_patch(player6) player4 = plt.Circle((55, 35), 3, edgecolor="black", facecolor="green", fill=True, label=playername[4]) plt.text(50, 25, playername[4]) ax.add_patch(player4) player5 = plt.Circle((55, 55), 3, edgecolor="black", facecolor="green", fill=True, label=playername[5]) plt.text(45, 45, playername[5]) ax.add_patch(player5) player7 = plt.Circle((85, 45), 3, edgecolor="black", facecolor="green", fill=True, label=playername[7]) plt.text(76, 35, playername[3]) ax.add_patch(player7) player8 = plt.Circle((85, 75), 3, edgecolor="black", facecolor="green", fill=True, label=playername[8]) plt.text(80, 65, playername[2]) ax.add_patch(player8) player9 = plt.Circle((85, 15), 3, edgecolor="black", facecolor="green", fill=True, label=playername[9]) plt.text(80, 5, playername[1]) ax.add_patch(player9) player10 = plt.Circle((107, 45), 3, edgecolor="black", facecolor="blue", fill=True, label=playername[10]) plt.text(100, 35, playername[0]) ax.add_patch(player10) #Display Pitch plt.show() elif d == 4 and m == 3 and ma == 0 and f == 3: print('Formacion 4303') player0 = plt.Circle((10, 45), 3, edgecolor="black", facecolor='orange', fill=True, label=playername[0]) plt.text(3, 33, playername[10]) ax.add_patch(player0) player1 = plt.Circle((37, 15), 3, edgecolor="black", facecolor='yellow', fill=True, label=playername[1]) plt.text(30, 5, playername[6]) ax.add_patch(player1) player2 = plt.Circle((37, 75), 3, edgecolor="black", facecolor='yellow', fill=True, label=playername[2]) plt.text(30, 65, playername[9]) ax.add_patch(player2) player3 = plt.Circle((30, 55), 3, edgecolor="black", facecolor='yellow', fill=True, label=playername[3]) plt.text(23, 45, playername[7]) ax.add_patch(player3) player6 = plt.Circle((30, 35), 3, edgecolor="black", facecolor="yellow", fill=True, label=playername[6]) plt.text(23, 25, playername[8]) player4 = plt.Circle((70, 25), 3, edgecolor="black", facecolor="green", fill=True, label=playername[4]) plt.text(65, 15, playername[4]) ax.add_patch(player4) player5 = plt.Circle((55, 45), 3, edgecolor="black", facecolor="green", fill=True, label=playername[5]) plt.text(45, 35, playername[5]) ax.add_patch(player5) ax.add_patch(player6) player7 = plt.Circle((70, 65), 3, edgecolor="black", facecolor="green", fill=True, label=playername[7]) plt.text(65, 55, playername[3]) ax.add_patch(player7) player8 = plt.Circle((105, 15), 3, edgecolor="black", facecolor="blue", fill=True, label=playername[8]) plt.text(98, 5, playername[2]) ax.add_patch(player8) player9 = plt.Circle((105, 75), 3, edgecolor="black", facecolor="blue", fill=True, label=playername[9]) plt.text(98, 65, playername[1]) ax.add_patch(player9) player10 = plt.Circle((107, 45), 3, edgecolor="black", facecolor="blue", fill=True, label=playername[10]) plt.text(100, 35, playername[0]) ax.add_patch(player10) #Display Pitch plt.show() # TODO - Funciones de graficos # Graficos def scatter_xG(stats): fig, ax = plt.subplots() #Set plot size fig.set_size_inches(7, 5) Atk = [] Dfc = [] for i in range(len(stats)): plt.plot(stats[i][2], stats[i][3], "o",label=stats[i][0]) Atk.append(stats[i][2]) Dfc.append(stats[i][3]) if stats[i][1] < 6: plt.text(stats[i][2], stats[i][3]+1,stats[i][0]) #Cross plt.plot([sum(Atk)/len(Atk),sum(Atk)/len(Atk)],[100,50],'k-', linestyle = ":", lw=1) plt.plot([50,100],[sum(Dfc)/len(Dfc),sum(Dfc)/len(Dfc)],'k-', linestyle = ":", lw=1) #Add labels to chart area ax.set_title("Skill Ranking") ax.set_xlabel("Attack") ax.set_ylabel("Defence") ax.text(49,50,"Poor attack, poor defense",color="red",size="8") ax.text(85,99,"Strong attack, strong defense",color="red",size="8") #Display the chart plt.show() #Funciones de simulacion y optimizacion #Funcion Skills Skill = [] Teams = [] def defineSkills(teamSkillSet): #RESET VARIABLES global Skill, Teams Skill = [] Teams = [] df_teams = pd.DataFrame(teamSkillSet, columns=['Rk', 'Squad', 'xG','xGA','Save%','SoT','Tkl','Blocks','Cmp%','KP','Poss']) bestXG = df_teams['xG'].max() bestXGA = df_teams['xGA'].min() bestSP = df_teams['Save%'].max() bestSoT = df_teams['SoT'].max() bestT = df_teams['Tkl'].max() bestB = df_teams['Blocks'].max() bestCP = df_teams['Cmp%'].max() bestKP = df_teams['KP'].max() for i in range(20): teamName = df_teams.at[i, 'Squad'] #atacking stats xGp = ((df_teams.at[i,'xG']/ bestXG)*50) Sotp = ((df_teams.at[i, 'SoT'] / bestSoT)*12.5) CPp = ((df_teams.at[i, 'Cmp%'] / bestCP)*12.5) KPp = ((df_teams.at[i, 'KP'] / bestKP)*25) #defensive stats xGAp = ((bestXGA / df_teams.at[i, 'xGA'])*50) Tp = ((df_teams.at[i, 'Tkl'] / bestT)*12.5) Bp = ((df_teams.at[i, 'Blocks'] / bestB)*12.5) SPp = ((df_teams.at[i, 'Save%'] / bestSP)*25) #Overall Stats atk = xGp + Sotp + KPp + CPp dfc = xGAp + Tp + Bp + SPp pos = df_teams.at[i, 'Poss'] xG = df_teams.at[i, 'xG'] Sp = df_teams.at[i, 'Save%']/3 teambyskill = [df_teams.at[i,'Squad'],df_teams.at[i,'Rk'], atk.round(), dfc.round(), pos, (xG/38).round(2),Sp.round(2)] Skill.append(teambyskill) # Teams ManchesterCity = [Skill[0], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] ManchesterUtd = [Skill[1], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] Liverpool = [Skill[2], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] Chelsea = [Skill[3], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] LeicesterCity = [Skill[4], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] WestHam = [Skill[5], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] Tottenham = [Skill[6], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] Arsenal = [Skill[7], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] LeedsUnited = [Skill[8], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] Everton = [Skill[9], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] AstonVilla = [Skill[10], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] NewcastleUtd = [Skill[11], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] Wolves = [Skill[12], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] CrystalPalace = [Skill[13], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] Southampton = [Skill[14], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] Brighton = [Skill[15], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] Burnley = [Skill[16], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] Fulham = [Skill[17], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] WestBrom = [Skill[18], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] SheffieldUtd = [Skill[19], [0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0]] Teams = [ManchesterCity, ManchesterUtd, Liverpool, Chelsea, LeicesterCity, WestHam, Tottenham, Arsenal, LeedsUnited, Everton, AstonVilla, NewcastleUtd, Wolves, CrystalPalace, Southampton, Brighton, Burnley, Fulham, WestBrom, SheffieldUtd] # Funcion para simular la liga # Goles def homeGoals(ht, at): if ht[0] != at[0]: bonusRank = (-1 * (ht[1] - at[1]))/100 bonusAtk = (ht[2] - at[3])/100 bonusPoss = (ht[4] - at[4])/100 goals = 0 # Better ATK if ht[2] > at[2]: randomFactorTemp = np.random.uniform(-0.15, 0.15) randomFactor = round(randomFactorTemp, 2) xGToTest = ht[5] * (1+bonusRank+bonusAtk+bonusPoss+randomFactor) + 0.25 xGTestRound = round(xGToTest) for i in range(xGTestRound): chanceOfGoal = np.random.random() if chanceOfGoal > at[6]/100: goals += 1 # Equal ATK if ht[2] == at[2]: randomFactorTemp = np.random.uniform(-0.15, 0.15) randomFactor = round(randomFactorTemp, 2) xGToTest = ht[5] * (1+bonusRank+bonusPoss+randomFactor) + 0.25 xGTestRound = round(xGToTest) for i in range(xGTestRound): chanceOfGoal = np.random.random() if chanceOfGoal > at[6]/100: goals += 1 # Worse ATK if ht[2] < at[2]: randomFactorTemp = np.random.uniform(-0.15, 0.15) randomFactor = round(randomFactorTemp, 2) xGToTest = ht[5] * (1+bonusRank+bonusAtk+bonusPoss+randomFactor) + 0.25 xGTestRound = round(xGToTest) for i in range(xGTestRound): chanceOfGoal = np.random.random() if chanceOfGoal > at[6]/100: goals += 1 return goals else: return 'Same Team' def awayGoals(ht, at): if ht[0] != at[0]: bonusRank = (-1 * (at[1]-ht[1]))/100 bonusAtk = (at[2] - ht[3])/100 bonusPoss = (at[4] - ht[4])/100 goals = 0 # Better ATK if at[2] > ht[2]: randomFactorTemp = np.random.uniform(-0.15, 0.15) randomFactor = round(randomFactorTemp, 2) xGToTest = at[5] * (1+bonusRank+bonusAtk+bonusPoss+randomFactor) xGTestRound = round(xGToTest) for i in range(xGTestRound): chanceOfGoal = np.random.random() if chanceOfGoal > ht[6]/100: goals += 1 # Equal ATK if at[2] == ht[2]: randomFactorTemp = np.random.uniform(-0.15, 0.15) randomFactor = round(randomFactorTemp, 2) xGToTest = at[5] * (1+bonusRank+bonusPoss+randomFactor) xGTestRound = round(xGToTest) for i in range(xGTestRound): chanceOfGoal = np.random.random() if chanceOfGoal > ht[6]/100: goals += 1 # Worse ATK if at[2] < ht[2]: randomFactorTemp = np.random.uniform(-0.15, 0.15) randomFactor = round(randomFactorTemp, 2) xGToTest = at[5] * (1+bonusRank+bonusAtk+bonusPoss+randomFactor) xGTestRound = round(xGToTest) for i in range(xGTestRound): chanceOfGoal = np.random.random() if chanceOfGoal > ht[6]/100: goals += 1 return goals else: return 'Same Team' def runLeague(dataSet, team, nSim): myTeamPosRun = np.zeros(nSim) MCPosRun = np.zeros(nSim) myTeamPointsRun = np.zeros(nSim) MCPointsRun = np.zeros(nSim) runPoints = np.zeros(shape=(nSim, 20)) runWins = np.zeros(shape=(nSim, 20)) runDraws = np.zeros(shape=(nSim, 20)) runLoses = np.zeros(shape=(nSim, 20)) runGF = np.zeros(shape=(nSim, 20)) runGA = np.zeros(shape=(nSim, 20)) runGD = np.zeros(shape=(nSim, 20)) upsets = 0 for i in range(nSim): #League Stats Points =[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] Wins = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] Draws = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] Loses = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] GF = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] GA = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] GD = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] for x in range(20): # print('=============================') # print(dataSet[x][0][0], 'Home Games') # print('=============================') for y in range(20): if dataSet[x][0] == dataSet[y][0]: pass else: homeScore = homeGoals(dataSet[x][0], dataSet[y][0]) awayScore = awayGoals(dataSet[x][0], dataSet[y][0]) chanceOfUpset = np.random.random() if chanceOfUpset < 0.03: upsets += 1 homeScoreTemp = homeScore homeScore = awayScore awayScore = homeScoreTemp # print(dataSet[x][0][0], homeScore,':', awayScore, dataSet[y][0][0]) if homeScore > awayScore: Wins[x] += 1 Loses[y] += 1 Points[x] += 3 GF[x] += homeScore GA[x] += awayScore GF[y] += awayScore GA[y] += homeScore elif homeScore < awayScore: Wins[y] += 1 Loses[x] += 1 Points[y] += 3 GF[x] += homeScore GA[x] += awayScore GF[y] += awayScore GA[y] += homeScore elif homeScore == awayScore: Draws[x] += 1 Draws[y] += 1 Points[x] += 1 Points[y] += 1 GF[x] += homeScore GA[x] += awayScore GF[y] += awayScore GA[y] += homeScore GD[x] += homeScore - awayScore GD[y] += awayScore - homeScore #Send data to average runPoints[i] = Points runWins[i] = Wins runDraws[i] = Draws runLoses[i] = Loses runGF[i] = GF runGA[i] = GA runGD[i] = GD tablePoints = runPoints.sum(axis=0)/nSim tableWins = runWins.sum(axis=0)/nSim tableDraws = runDraws.sum(axis=0)/nSim tableLoses = runLoses.sum(axis=0)/nSim tableGF = runGF.sum(axis=0)/nSim tableGA = runGA.sum(axis=0)/nSim tableGD = runGD.sum(axis=0)/nSim #Rank for z in range(20): dataSet[z][2][0]= Points[z] dataSet[z][2][1]= Wins[z] dataSet[z][2][2]= Draws[z] dataSet[z][2][3]= Loses[z] dataSet[z][2][4]= GF[z] dataSet[z][2][5]= GA[z] dataSet[z][2][7]= GD[z] sortedTeamsRun = sorted(dataSet, key=lambda x: x[2][0], reverse=True) for w in range(20): sortedTeamsRun[w][2][6]= w+1 if sortedTeamsRun[w][0][0] == team: myTeamPosRun[i] = sortedTeamsRun[w][2][6] myTeamPointsRun[i] = sortedTeamsRun[w][2][0] elif sortedTeamsRun[w][0][0] == 'Manchester City': MCPosRun[i] = sortedTeamsRun[w][2][6] MCPointsRun[i] = sortedTeamsRun[w][2][0] for x in range(20): dataSet[x][1][0]= round(tablePoints[x], 1) dataSet[x][1][1]= round(tableWins[x], 1) dataSet[x][1][2]= round(tableDraws[x], 1) dataSet[x][1][3]= round(tableLoses[x], 1) dataSet[x][1][4]= round(tableGF[x], 1) dataSet[x][1][5]= round(tableGA[x], 1) dataSet[x][1][7]= round(tableGD[x], 1) #League Table sortedTeams = sorted(dataSet, key=lambda x: x[1][0], reverse=True) print("| RANK | TEAM | POINTS | WINS | DRAWS | LOSSES | GOALS FOR | GOALS AGAINST | GOAL DIFF. |") for x in range(20): sortedTeams[x][1][6]= x+1 print("| ",x+1," "*(2 - len(str(sortedTeams[x][1][6]))),'|', sortedTeams[x][0][0]," "*(15 - len(sortedTeams[x][0][0])),'| ', sortedTeams[x][1][0]," "*(4 - len(str(sortedTeams[x][1][0]))),'| ', sortedTeams[x][1][1]," "*(4 - len(str(sortedTeams[x][1][1]))),'|', sortedTeams[x][1][2]," "*(4 - len(str(sortedTeams[x][1][2]))),'| ', sortedTeams[x][1][3]," "*(4 - len(str(sortedTeams[x][1][3]))),'| ', sortedTeams[x][1][4]," "*(5 - len(str(sortedTeams[x][1][4]))),"| ", sortedTeams[x][1][5]," "*(8 - len(str(sortedTeams[x][1][5]))),"| ", sortedTeams[x][1][7]," "*(6 - len(str(sortedTeams[x][1][7]))),"|") print('===============================') print('Probabilidad de que', team, 'quede en el Top 4 =', np.sum(myTeamPosRun < 5)/nSim) # print('Upsets por Sim =', upsets/nSim) print('===============================') if nSim > 10: print('Plots') print('===============================') # Graficos de la simulacion # Posicion vs Puntos fig, ax1 = plt.subplots() color = 'tab:green' ax1.set_xlabel('Simulations') ax1.set_ylabel('Points', color=color) ax1.plot(myTeamPointsRun, color=color) ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis color = 'tab:blue' ax2.set_ylabel('Position', color=color) # we already handled the x-label with ax1 ax2.plot(myTeamPosRun,"o",color=color) ax2.invert_yaxis() ax2.tick_params(axis='y', labelcolor=color,) fig.tight_layout() # otherwise the right y-label is slightly clipped plt.show() # Puntos acumulados Team vs Manchester City #Create the bare bones of what will be our visualisation fig, ax = plt.subplots() myTeamPointsCumulative = np.zeros(len(myTeamPointsRun)) for i in range(len(myTeamPointsRun)): myTeamPointsCumulative[i] = myTeamPointsCumulative[i-1] + myTeamPointsRun[i] MCPointsCumulative = np.zeros(len(MCPointsRun)) for i in range(len(MCPointsRun)): MCPointsCumulative[i] = MCPointsCumulative[i-1] + MCPointsRun[i] #Add our data as before, but setting colours and widths of lines plt.plot(myTeamPointsCumulative, color="#231F20", linewidth=2) plt.plot(MCPointsCumulative, color="#6CABDD", linewidth=2) #Give the axes and plot a title each plt.xlabel('Sims') plt.ylabel('Points') plt.title('Team v Man City Running Total Points') #Add a faint grey grid plt.grid() ax.xaxis.grid(color="#F8F8F8") ax.yaxis.grid(color="#F9F9F9") #Remove the margins between our lines and the axes plt.margins(x=0, y=0) #Remove the spines of the chart on the top and right sides ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) # Puntos ManCity vs Team por simulacion #Create the bare bones of what will be our visualisation fig, ax = plt.subplots() #Add our data as before, but setting colours and widths of lines plt.plot(MCPointsRun, color="#6CABDD", linewidth=2) plt.plot(myTeamPointsRun, color="#231F20", linewidth=2) #Give the axes and plot a title each plt.xlabel('Sims') plt.ylabel('Points') plt.title('Team v Man City Points Per Sim') #Add a faint grey grid plt.grid() ax.xaxis.grid(color="#F8F8F8") ax.yaxis.grid(color="#F9F9F9") #Remove the margins between our lines and the axes plt.margins(x=0, y=0) #Remove the spines of the chart on the top and right sides ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) #Funcion traer own team MyTeamPlayers = [] MyStartingXI = [] MyStartingXI_xG = 0 MyStartingXI_SoT = 0 MyStartingXI_KP = 0 MyStartingXI_CMP = 0 MyStartingXI_TKL = 0 MyStartingXI_B = 0 MyStartingXI_SP = 0 MyFWPlayers = [] MyMFFWPlayers = [] MyMFPlayers = [] MyDFPlayers = [] MyGKPlayers = [] def myTeam(teamname,d,m,ma,f): #RESET VARIABLES global MyStartingXI_xG, MyStartingXI_SoT, MyStartingXI_KP, MyStartingXI_CMP, MyStartingXI_TKL, MyStartingXI_B, MyStartingXI_SP, MyFWPlayers, MyMFFWPlayers, MyMFPlayers, MyDFPlayers, MyGKPlayers MyTeamPlayers = [] MyStartingXI = [] MyStartingXI_xG = 0 MyStartingXI_SoT = 0 MyStartingXI_KP = 0 MyStartingXI_CMP = 0 MyStartingXI_TKL = 0 MyStartingXI_B = 0 MyStartingXI_SP = 0 MyFWPlayers = [] MyMFFWPlayers = [] MyMFPlayers = [] MyDFPlayers = [] MyGKPlayers = [] #All My Players df_all_players = pd.DataFrame(pl_players_stats_skills, columns=['Player','Squad']) for i in range(532): Squad = df_all_players.at[i, 'Squad'] if Squad == teamname: MyTeamPlayers.append(df_all_players.loc[i]) #FW df_FW_players = pd.DataFrame(pl_players_stats_skills, columns=['Player','Squad', '90s', 'Pos', 'xG', 'SoT', 'Price']) for i in range(532): Posi = df_FW_players.at[i, 'Pos'] Squad = df_FW_players.at[i, 'Squad'] if Posi == 'FW' and Squad == teamname: MyFWPlayers.append(df_FW_players.loc[i]) xG_MyFW = [] SoT_MyFW = [] for i in range(len(MyFWPlayers)): xG_MyFW.append(MyFWPlayers[i][4]) for i in range(len(MyFWPlayers)): SoT_MyFW.append(MyFWPlayers[i][5]) #MFFW df_MFFW_players = pd.DataFrame(pl_players_stats_skills, columns=['Player', 'Squad', '90s', 'Pos', 'xG', 'SoT', 'KP', 'Cmp%', 'Price']) for i in range(532): Posi = df_MFFW_players.at[i, 'Pos'] Squad = df_MFFW_players.at[i, 'Squad'] if Posi == 'MFFW' and Squad == teamname: MyMFFWPlayers.append(df_MFFW_players.loc[i]) if Posi == 'FWMF' and Squad == teamname: MyMFFWPlayers.append(df_MFFW_players.loc[i]) if Posi == 'DFFW' and Squad == teamname: MyMFFWPlayers.append(df_MFFW_players.loc[i]) xG_MyMFFW = [] SoT_MyMFFW = [] KP_MyMFFW = [] CMP_MyMFFW = [] for i in range(len(MyMFFWPlayers)): KP_MyMFFW.append(MyMFFWPlayers[i][6]) for i in range(len(MyMFFWPlayers)): xG_MyMFFW.append(MyMFFWPlayers[i][4]) for i in range(len(MyMFFWPlayers)): SoT_MyMFFW.append(MyMFFWPlayers[i][5]) for i in range(len(MyMFFWPlayers)): CMP_MyMFFW.append(MyMFFWPlayers[i][7]) #MF df_MF_players = pd.DataFrame(pl_players_stats_skills, columns=['Player', 'Squad', '90s', 'Pos', 'Tkl', 'Cmp%', 'KP', 'Price']) for i in range(532): Posi = df_MF_players.at[i, 'Pos'] Squad = df_MF_players.at[i, 'Squad'] if Posi == 'MF' and Squad == teamname: MyMFPlayers.append(df_MF_players.loc[i]) if Posi == 'MFDF' and Squad == teamname: MyMFPlayers.append(df_MF_players.loc[i]) KP_MyMF = [] CMP_MyMF = [] TKL_MyMF = [] for i in range(len(MyMFPlayers)): KP_MyMF.append(MyMFPlayers[i][6]) for i in range(len(MyMFPlayers)): CMP_MyMF.append(MyMFPlayers[i][5]) for i in range(len(MyMFPlayers)): TKL_MyMF.append(MyMFPlayers[i][4]) #DF df_DF_players = pd.DataFrame(pl_players_stats_skills, columns=['Player','Squad','90s', 'Pos', 'Tkl', 'Blocks', 'Cmp%', 'Price']) for i in range(532): Posi = df_DF_players.at[i, 'Pos'] Squad = df_DF_players.at[i, 'Squad'] if Posi == 'DF' and Squad == teamname: MyDFPlayers.append(df_DF_players.loc[i]) CMP_MyDF = [] TKL_MyDF = [] B_MyDF = [] for i in range(len(MyDFPlayers)): B_MyDF.append(MyDFPlayers[i][5]) for i in range(len(MyDFPlayers)): CMP_MyDF.append(MyDFPlayers[i][6]) for i in range(len(MyDFPlayers)): TKL_MyDF.append(MyDFPlayers[i][4]) #GK df_GK_players = pd.DataFrame(pl_players_stats_skills, columns=['Player', 'Squad','90s', 'Pos', 'Save%', 'Price']) for i in range(532): Posi = df_GK_players.at[i, 'Pos'] GPi = df_GK_players.at[i, '90s'] Squad = df_GK_players.at[i, 'Squad'] if Posi == 'GK' and Squad == teamname and GPi > 10: MyGKPlayers.append(df_GK_players.loc[i]) SP_MyGK = [] for i in range(len(MyGKPlayers)): SP_MyGK.append(MyGKPlayers[i][4]) # OPTIMIZACION - Best XI #Formacion formationDF = d formationMF = m formationMFFW = ma formationFW = f # Planteamos el problema con picos # Creo el problema P = picos.Problem() # Tipo de jugadores #FW f = picos.BinaryVariable('f', len(MyFWPlayers)) #MFFW mffw = picos.BinaryVariable('mffw', len(MyMFFWPlayers)) #MF mf = picos.BinaryVariable('mf', len(MyMFPlayers)) #DF df = picos.BinaryVariable('df', len(MyDFPlayers)) #GK gk = picos.BinaryVariable('gk', len(MyGKPlayers)) #xG FW MyxGFWTemp = np.array([xG_MyFW]) MySoTFWTemp = np.array([SoT_MyFW]) #MFFW MyKPMFFWTemp = np.array([KP_MyMFFW]) MyxGMFFWTemp = np.array([xG_MyMFFW]) MySOTMFFWTemp = np.array([SoT_MyMFFW]) MyCMPMFFWTemp = np.array([CMP_MyMFFW]) #MF MyKPMFTemp = np.array([KP_MyMF]) MyCMPMFTemp = np.array([CMP_MyMF]) MyTKLMFTemp = np.array([TKL_MyMF]) #DF MyCMPDFTemp = np.array([CMP_MyDF]) MyTKLDFTemp = np.array([TKL_MyDF]) MyBDFTemp = np.array([B_MyDF]) #GK MySavePTemp = np.array([SP_MyGK]) #Defino objetivo y función objetivo P.set_objective('max', MyxGFWTemp*f*50 + MySoTFWTemp*f*12.5 + MyKPMFFWTemp*mffw*25 + (1+MyxGMFFWTemp)*mffw*50 + MySOTMFFWTemp*mffw*12.5 + MyCMPMFFWTemp * mffw * 12.5 + (1+MyKPMFTemp)*mf*25 + (1+MyTKLMFTemp)*mf*12.5 + MyCMPMFTemp*mf*12.5 + MyCMPDFTemp*df*12.5 + (1+MyTKLDFTemp)*df*12.5 + (1+MyBDFTemp)*df*12.5 + MySavePTemp*gk*25) #Constraints #Limite de FW P.add_constraint(sum(f) == formationFW) #Limite de MFFW P.add_constraint(sum(mffw) == formationMFFW) #Limite de MF P.add_constraint(sum(mf) == formationMF) #Limite de DF P.add_constraint(sum(df) == formationDF) #Limite de GK P.add_constraint(sum(gk) == 1) #Verbosity P.options.verbosity = 0 #Problema en consola # print(P) #Resuelvo P.solve(solver='glpk') #Imprimo punto óptimo # print('f*=', f, # 'mffw*=', mffw, # 'mf*=', mf, # 'df*=', df, # 'gk*=', gk) #Imprimo valor óptimo # print(P.value) # Starting XI xGToReplace = [] SoTToReplace = [] KPToReplace = [] CMPToReplace = [] TKLToReplace = [] BToReplace = [] SPToReplace = [] for i in range(len(MyFWPlayers)): currentx = round(f[i]) if currentx == 1: MyStartingXI.append(MyFWPlayers[i][0]) xGToReplace.append(MyFWPlayers[i][4]) SoTToReplace.append(MyFWPlayers[i][5]) for i in range(len(MyMFFWPlayers)): currenty = round(mffw[i]) if currenty == 1: MyStartingXI.append(MyMFFWPlayers[i][0]) xGToReplace.append(MyMFFWPlayers[i][4]) SoTToReplace.append(MyMFFWPlayers[i][5]) KPToReplace.append(MyMFFWPlayers[i][6]) CMPToReplace.append(MyMFFWPlayers[i][7]) for i in range(len(MyMFPlayers)): currentz = round(mf[i]) if currentz == 1: MyStartingXI.append(MyMFPlayers[i][0]) TKLToReplace.append(MyMFPlayers[i][4]) CMPToReplace.append(MyMFPlayers[i][5]) KPToReplace.append(MyMFPlayers[i][6]) for i in range(len(MyDFPlayers)): currentw = round(df[i]) if currentw == 1: MyStartingXI.append(MyDFPlayers[i][0]) TKLToReplace.append(MyDFPlayers[i][4]) BToReplace.append(MyDFPlayers[i][5]) CMPToReplace.append(MyDFPlayers[i][6]) for i in range(len(MyGKPlayers)): currentv = round(gk[i]) if currentv == 1: MyStartingXI.append(MyGKPlayers[i][0]) SPToReplace.append(MyGKPlayers[i][4]) print('Optimal Starting XI:', MyStartingXI) MyStartingXI_xG = sum(xGToReplace) MyStartingXI_SoT = sum(SoTToReplace) MyStartingXI_KP = sum(KPToReplace) MyStartingXI_CMP = sum(CMPToReplace)/len(CMPToReplace) MyStartingXI_TKL = sum(TKLToReplace) MyStartingXI_B = sum(BToReplace) MyStartingXI_SP = sum(SPToReplace) createPitch(MyStartingXI,d,m,ma,f) #Funcion Merge Players to buy & optimizacion # Top Players + MyPlayers FWPlayers = [] MFFWPlayers = [] MFPlayers = [] DFPlayers = [] GKPlayers = [] #My new StartingXI data MyNewStartingXI= [] MyNewPlayers_xG = 0 MyNewPlayers_SoT = 0 MyNewPlayers_KP = 0 MyNewPlayers_CMP = 0 MyNewPlayers_TKL = 0 MyNewPlayers_B = 0 MyNewPlayers_SP = 0 myTeamxG = 0 myTeamSoT = 0 myTeamKP = 0 myTeamCP = 0 myTeamxGA = 0 myTeamT = 0 myTeamB = 0 myTeamSP = 0 def myNewTeam(teamname,money,d,m,ma,f): #RESET VARIABLES global FWPlayers, MFFWPlayers, MFPlayers, DFPlayers, GKPlayers, MyNewStartingXI, MyNewPlayers_xG, MyNewPlayers_SoT, MyNewPlayers_KP, MyNewPlayers_CMP, MyNewPlayers_TKL, MyNewPlayers_B, MyNewPlayers_SP, myTeamxG, myTeamSoT, myTeamKP, myTeamCP, myTeamxGA, myTeamT, myTeamB, myTeamSP FWPlayers = [] MFFWPlayers = [] MFPlayers = [] DFPlayers = [] GKPlayers = [] MyNewStartingXI= [] MyNewPlayers_xG = 0 MyNewPlayers_SoT = 0 MyNewPlayers_KP = 0 MyNewPlayers_CMP = 0 MyNewPlayers_TKL = 0 MyNewPlayers_B = 0 MyNewPlayers_SP = 0 #TODO - esto esta por si se quiere agregar o cambiar la liga donde se compra. league_players_stats = bundes_player_stats #TODO - a la hora de filtrar podriamos agregar que filter sea mejor que los jugadores de nuestro equipo, aka que xGi sea una variable de la media de cada equipo df_FW_players = pd.DataFrame(league_players_stats, columns=['Player','Squad', '90s', 'Pos', 'xG', 'SoT', 'Price']) for i in range(505): Posi = df_FW_players.at[i, 'Pos'] GamesPlayedi = df_FW_players.at[i, '90s'] xGi = df_FW_players.at[i, 'xG'] SoTi = df_FW_players.at[i, 'SoT'] df_FW_players.at[i, 'xG'] = (xGi*2.69)/3.2 df_FW_players.at[i, 'SoT'] = (SoTi*2.69)/3.2 if Posi == 'FW' and GamesPlayedi > 20 and xGi > 8: FWPlayers.append(df_FW_players.loc[i]) # MFFW df_MFFW_players = pd.DataFrame(league_players_stats, columns=['Player','Squad', '90s', 'Pos', 'xG', 'SoT', 'KP', 'Cmp%', 'Price']) for i in range(505): Posi = df_MFFW_players.at[i, 'Pos'] GamesPlayedi = df_MFFW_players.at[i, '90s'] KPi = df_MFFW_players.at[i, 'KP'] xGi = df_MFFW_players.at[i, 'xG'] SoTi = df_MFFW_players.at[i, 'SoT'] df_MFFW_players.at[i, 'xG'] = (xGi*2.69)/3.2 df_MFFW_players.at[i, 'SoT'] = (SoTi*2.69)/3.2 df_MFFW_players.at[i, 'KP'] = (KPi*2.69)/3.2 if Posi == 'MFFW' and GamesPlayedi > 20 and KPi > 22: MFFWPlayers.append(df_MFFW_players.loc[i]) if Posi == 'FWMF' and GamesPlayedi > 20 and KPi > 22: MFFWPlayers.append(df_MFFW_players.loc[i]) # MF df_MF_players = pd.DataFrame(league_players_stats, columns=['Player','Squad', '90s', 'Pos', 'Tkl', 'Cmp%', 'KP', 'Price']) for i in range(505): Posi = df_MF_players.at[i, 'Pos'] GamesPlayedi = df_MF_players.at[i, '90s'] CMPi = df_MF_players.at[i, 'Cmp%'] KPi = df_MF_players.at[i, 'KP'] Tkli = df_MF_players.at[i, 'Tkl'] df_MF_players.at[i, 'KP'] = (KPi*2.69)/3.2 df_MF_players.at[i, 'Tkl'] = (Tkli*2.69)/3.2 if Posi == 'MF' and GamesPlayedi > 20 and CMPi > 75 and KPi > 20: MFPlayers.append(df_MF_players.loc[i]) if Posi == 'DFMF' and GamesPlayedi > 20 and CMPi > 75 and KPi > 20: MFPlayers.append(df_MF_players.loc[i]) if Posi == 'MFDF' and GamesPlayedi > 20 and CMPi > 75 and KPi > 20: MFPlayers.append(df_MF_players.loc[i]) # DF df_DF_players = pd.DataFrame(league_players_stats, columns=['Player','Squad', '90s', 'Pos', 'Tkl', 'Blocks', 'Cmp%', 'Price']) for i in range(505): Posi = df_DF_players.at[i, 'Pos'] GamesPlayedi = df_DF_players.at[i, '90s'] Blocksi = df_DF_players.at[i, 'Blocks'] Tkli = df_DF_players.at[i, 'Tkl'] df_DF_players.at[i, 'Blocks'] = (Blocksi*2.69)/3.2 df_DF_players.at[i, 'Tkl'] = (Tkli*2.69)/3.2 if Posi == 'DF' and GamesPlayedi > 20 and Blocksi > 32 and Tkli > 45: DFPlayers.append(df_DF_players.loc[i]) if Posi == 'DFFW' and GamesPlayedi > 20 and Blocksi > 32 and Tkli > 45: DFPlayers.append(df_DF_players.loc[i]) # GK df_GK_players = pd.DataFrame(league_players_stats, columns=['Player','Squad','90s', 'Pos', 'Save%', 'Price']) for i in range(505): Posi = df_GK_players.at[i, 'Pos'] GamesPlayedi = df_GK_players.at[i, '90s'] Savei = df_GK_players.at[i, 'Save%'] if Posi == 'GK' and GamesPlayedi > 20 and Savei > 70: GKPlayers.append(df_GK_players.loc[i]) #Append MyPlayers a TopPlayers for i in range(len(MyFWPlayers)): FWPlayers.append(MyFWPlayers[i]) for i in range(len(MyMFFWPlayers)): MFFWPlayers.append(MyMFFWPlayers[i]) for i in range(len(MyMFPlayers)): MFPlayers.append(MyMFPlayers[i]) for i in range(len(MyDFPlayers)): DFPlayers.append(MyDFPlayers[i]) for i in range(len(MyGKPlayers)): GKPlayers.append(MyGKPlayers[i]) #Datos de todos los jugadores #FW cFW = [] xGFW = [] SoTFW = [] for i in range(len(FWPlayers)): cFW.append(FWPlayers[i][6]) for i in range(len(FWPlayers)): xGFW.append(FWPlayers[i][4]) for i in range(len(FWPlayers)): SoTFW.append(FWPlayers[i][5]) #MFFW cMFFW = [] KPMFFW = [] xGMFFW = [] SOTMFFW = [] CMPMFFW = [] for i in range(len(MFFWPlayers)): cMFFW.append(MFFWPlayers[i][8]) for i in range(len(MFFWPlayers)): KPMFFW.append(MFFWPlayers[i][6]) for i in range(len(MFFWPlayers)): xGMFFW.append(MFFWPlayers[i][4]) for i in range(len(MFFWPlayers)): SOTMFFW.append(MFFWPlayers[i][5]) for i in range(len(MFFWPlayers)): CMPMFFW.append(MFFWPlayers[i][7]) #MF cMF = [] CMPMF = [] KPMF = [] TKLMF = [] for i in range(len(MFPlayers)): cMF.append(MFPlayers[i][7]) for i in range(len(MFPlayers)): KPMF.append(MFPlayers[i][6]) for i in range(len(MFPlayers)): CMPMF.append(MFPlayers[i][5]) for i in range(len(MFPlayers)): TKLMF.append(MFPlayers[i][4]) #DF cDF = [] CMPDF = [] TKLDF = [] BDF = [] for i in range(len(DFPlayers)): cDF.append(DFPlayers[i][7]) for i in range(len(DFPlayers)): CMPDF.append(DFPlayers[i][6]) for i in range(len(DFPlayers)): TKLDF.append(DFPlayers[i][4]) for i in range(len(DFPlayers)): BDF.append(DFPlayers[i][5]) #GK cGK = [] SavePGK = [] for i in range(len(GKPlayers)): cGK.append(GKPlayers[i][5]) for i in range(len(GKPlayers)): SavePGK.append(GKPlayers[i][4]) #%% # Problema Optimizacion #Formacion formationDF = d formationMF = m formationMFFW = ma formationFW = f # Planteamos el problema con picos import picos # Creo el problema P = picos.Problem() # Tipo de jugadores #FW x = picos.BinaryVariable('x', len(FWPlayers)) #MFFW y = picos.BinaryVariable('y', len(MFFWPlayers)) #MF z = picos.BinaryVariable('z', len(MFPlayers)) #DF w = picos.BinaryVariable('w', len(DFPlayers)) #GK v = picos.BinaryVariable('v', len(GKPlayers)) #Matriz de costos cFWTemp = np.array([cFW]) cMFFWTemp = np.array([cMFFW]) cMFTemp = np.array([cMF]) cDFTemp = np.array([cDF]) cGKTemp = np.array([cGK]) #xG FW xGFWTemp = np.array([xGFW]) SoTFWTemp = np.array([SoTFW]) #MFFW KPMFFWTemp = np.array([KPMFFW]) xGMFFWTemp = np.array([xGMFFW]) SOTMFFWTemp = np.array([SOTMFFW]) CMPMFFWTemp = np.array([CMPMFFW]) #MF KPMFTemp = np.array([KPMF]) CMPMFTemp = np.array([CMPMF]) TKLMFTemp = np.array([TKLMF]) #DF CMPDFTemp = np.array([CMPDF]) TKLDFTemp = np.array([TKLDF]) BDFTemp = np.array([BDF]) #GK SavePTemp = np.array([SavePGK]) #Defino objetivo y función objetivo P.set_objective('max', xGFWTemp*x*50 + SoTFWTemp*x*12.5 + KPMFFWTemp*y*25 + (1+xGMFFWTemp)*y*50 + SOTMFFWTemp*y*12.5 + CMPMFFWTemp*y*12.5 + (1+KPMFTemp)*z*25 + (1+TKLMFTemp)*z*12.5 + CMPMFTemp*z*12.5 + CMPDFTemp*w*12.5 + (1+TKLDFTemp)*w*12.5 + (1+BDFTemp)*w*12.5 + SavePTemp*v*25) # Interesante la funcion objetivo, tenemos que buscar la forma de darle el peso que le corresponde a cada estadistica /25? y hacerlo igual que el skill? #Constraints #Limite de dinero # P.add_constraint(sum(cFW) + sum(cMFFW) + sum(cMF) + sum(cDF) + sum(cGK) <= 150000000) P.add_constraint(sum(cFWTemp*x) + sum(cMFFWTemp*y) + sum(cMFTemp*z) + sum(cDFTemp*w) + sum(cGKTemp*v) <= money*1000000) #Limite de FW P.add_constraint(sum(x) == formationFW) #Limite de MFFW P.add_constraint(sum(y) == formationMFFW) #Limite de MF P.add_constraint(sum(z) == formationMF) #Limite de DF P.add_constraint(sum(w) == formationDF) #Limite de GK P.add_constraint(sum(v) == 1) #Verbosity P.options.verbosity = 0 #Problema en consola # print(P) #Resuelvo P.solve(solver='glpk') #Imprimo punto óptimo # print('x*=', x, # 'y*=', y, # 'z*=', z, # 'w*=', w, # 'v*=', v) #Imprimo valor óptimo # print(P.value) print('Money Spent: ', sum(cFWTemp*x) + sum(cMFFWTemp*y) + sum(cMFTemp*z) + sum(cDFTemp*w) + sum(cGKTemp*v)) #NewStartingXI MyNewStartingXI = [] xGNew = [] SoTNew = [] KPNew = [] CMPNew = [] TKLNew = [] BNew = [] SPNew = [] for i in range(len(FWPlayers)): currentx = round(x[i]) if currentx == 1: MyNewStartingXI.append(FWPlayers[i][0]) xGNew.append(FWPlayers[i][4]) SoTNew.append(FWPlayers[i][5]) for i in range(len(MFFWPlayers)): currenty = round(y[i]) if currenty == 1: MyNewStartingXI.append(MFFWPlayers[i][0]) xGNew.append(MFFWPlayers[i][4]) SoTNew.append(MFFWPlayers[i][5]) KPNew.append(MFFWPlayers[i][6]) CMPNew.append(MFFWPlayers[i][7]) for i in range(len(MFPlayers)): currentz = round(z[i]) if currentz == 1: MyNewStartingXI.append(MFPlayers[i][0]) KPNew.append(MFPlayers[i][6]) CMPNew.append(MFPlayers[i][5]) TKLNew.append(MFPlayers[i][4]) for i in range(len(DFPlayers)): currentw = round(w[i]) if currentw == 1: MyNewStartingXI.append(DFPlayers[i][0]) CMPNew.append(DFPlayers[i][6]) TKLNew.append(DFPlayers[i][4]) BNew.append(DFPlayers[i][5]) for i in range(len(GKPlayers)): currentv = round(v[i]) if currentv == 1: MyNewStartingXI.append(GKPlayers[i][0]) SPNew.append(GKPlayers[i][4]) print('New Optimal Starting XI', MyNewStartingXI) createPitch(MyNewStartingXI,d,m,ma,f) MyNewPlayers_xG = sum(xGNew) MyNewPlayers_SoT = sum(SoTNew) MyNewPlayers_KP = sum(KPNew) MyNewPlayers_CMP = sum(CMPNew) MyNewPlayers_TKL = sum(TKLNew) MyNewPlayers_B = sum(BNew) MyNewPlayers_SP = sum(SPNew) # Setear nuevo skillset del equipo df_teams = pd.DataFrame(team_stats_skills, columns=['Rk', 'Squad', 'xG','xGA','Save%','SoT','Tkl','Blocks','Cmp%','KP','Poss']) teamLocation = 0 for i in range(len(df_teams)): Teami = df_teams.at[i, 'Squad'] if Teami == teamname: teamLocation = i bestT = df_teams['Tkl'].max() bestB = df_teams['Blocks'].max() bestSP = df_teams['Save%'].max() myTeamxG = df_teams.at[teamLocation, 'xG'] myTeamSoT = df_teams.at[teamLocation, 'SoT'] myTeamKP = df_teams.at[teamLocation, 'KP'] myTeamCP = df_teams.at[teamLocation, 'Cmp%'] #Defensive Stats myTeamxGA = df_teams.at[teamLocation, 'xGA'] myTeamT = df_teams.at[teamLocation, 'Tkl'] myTeamB = df_teams.at[teamLocation, 'Blocks'] myTeamSP = df_teams.at[teamLocation, 'Save%'] myTeamDef_T = ((myTeamT / bestT)*12.5) myTeamDef_B = ((myTeamB / bestB)*12.5) myTeamDef_SP = ((myTeamSP / bestSP)*25) #atk myTeamNew_xG = myTeamxG - MyStartingXI_xG + MyNewPlayers_xG myTeamNew_SoT = myTeamSoT - MyStartingXI_SoT + MyNewPlayers_SoT myTeamNew_KP = myTeamKP - MyStartingXI_KP + MyNewPlayers_KP myTeamNew_CP = (myTeamCP*len(MyTeamPlayers) + MyNewPlayers_CMP)/(len(MyTeamPlayers)+len(CMPNew)) #dfc myTeamNew_TKL = myTeamT - MyStartingXI_TKL + MyNewPlayers_TKL myTeamNew_B = myTeamB - MyStartingXI_B + MyNewPlayers_B myTeamNew_SP = MyNewPlayers_SP #New xGA Calc Comparison_Def_Base = myTeamDef_T + myTeamDef_B + myTeamDef_SP myTeamNew_Def_T2 = ((myTeamNew_TKL/myTeamT)-1) myTeamNew_Def_B2 = ((myTeamNew_B/myTeamB)-1) myTeamNew_Def_SP2 = ((myTeamNew_SP/myTeamSP)-1) New_Def_Base = myTeamDef_T*(1+myTeamNew_Def_T2) + myTeamDef_B*(1+myTeamNew_Def_B2) + myTeamDef_SP*(1+myTeamNew_Def_SP2) #New xGA Def_Mejora = (New_Def_Base/Comparison_Def_Base)-1 myTeamxGA2 = myTeamxGA*(1-Def_Mejora) myTeamNew_xGA = myTeamxGA2 #Import Data team_stats_skills.at[teamLocation,'xG']=myTeamNew_xG team_stats_skills.at[teamLocation,'SoT']=myTeamNew_SoT team_stats_skills.at[teamLocation,'KP']=myTeamNew_KP team_stats_skills.at[teamLocation,'Cmp%']=myTeamNew_CP team_stats_skills.at[teamLocation,'xGA']=myTeamNew_xGA team_stats_skills.at[teamLocation,'Tkl']=myTeamNew_TKL team_stats_skills.at[teamLocation,'Blocks']=myTeamNew_B team_stats_skills.at[teamLocation,'Save%']=myTeamNew_SP team_stats_skills.to_csv('new-league-stats-skill.csv',index=False) team_stats_skills.at[teamLocation,'xG']=myTeamxG team_stats_skills.at[teamLocation,'SoT']=myTeamSoT team_stats_skills.at[teamLocation,'KP']=myTeamKP team_stats_skills.at[teamLocation,'Cmp%']=myTeamCP team_stats_skills.at[teamLocation,'xGA']=myTeamxGA team_stats_skills.at[teamLocation,'Tkl']=myTeamT team_stats_skills.at[teamLocation,'Blocks']=myTeamB team_stats_skills.at[teamLocation,'Save%']=myTeamSP #Combinacion Optimizaciones def runTeamImprovement(team,money,d,m,ma,f): myTeam(team,d,m,ma,f) myNewTeam(team,money,d,m,ma,f) # Funcion principal def runSimulation(new, nSim, team, budget, d, m, ma, f): if new == False: team_stats_skills = pd.read_csv('league-stats-skill.csv') defineSkills(team_stats_skills) print('===============================') print('Attack/Defense Scatter Plot') print('===============================') scatter_xG(Skill) myTeam(team,d,m,ma,f) print('===============================') print('Resultados de la Liga') print('===============================') runLeague(Teams, team, nSim) else: #Reset CSV team_stats_skills = pd.read_csv('league-stats-skill.csv') csvFile = 'new-league-stats-skill.csv' if os.path.exists(csvFile): os.remove(csvFile) print('CSV File deleted') defineSkills(team_stats_skills) print('=========================================================================================') print('Simulacion de Liga antes de comprar') print('=========================================================================================') print('Attack/Defense Scatter Plot') print('===============================') scatter_xG(Skill) print('===============================') print('Resultados de la Liga') print('===============================') runLeague(Teams, team, nSim) runTeamImprovement(team, budget, d, m, ma, f) new_team_stats_skills = pd.read_csv('new-league-stats-skill.csv') defineSkills(new_team_stats_skills) print('=========================================================================================') print('Simulacion de Liga despues de comprar') print('=========================================================================================') print('Attack/Defense Scatter Plot') print('===============================') scatter_xG(Skill) print('===============================') print('Resultados de la Liga') print('===============================') runLeague(Teams, team, nSim) #%% #PANEL DE CONTROL # COMO USAR # Reemplazar los valores de las variables con el modo, numero de simulaciones, equipo, presupuesto y formacion # MODO #False = Corre la liga sin cambios #True = Corre la liga sin cambios, despues optimiza la compra de nuevos jugadores y vuelve a correr la liga con los cambios GetNewTeam = True # NUMERO DE SIMULACIONES nSim = 10000 # EQUIPO MyTeam = 'Leicester City' # PRESUPUESTO (en millones) Budget = 39.5 # FORMACION # Disponible: (4,2,3,1 // 4,3,0,3 // 4,3,1,2) Defenders = 4 Midfielders = 2 MidAttackers = 3 Forwards = 1 runSimulation(GetNewTeam, nSim, MyTeam, Budget, Defenders, Midfielders, MidAttackers, Forwards)
# coding=utf-8 # https://github.com/Show-Me-the-Code/show-me-the-code # **第 0004 题:**任一个英文的纯文本文件,统计其中的单词出现的个数。 # 打开文件 # 利用正则去匹配 # 把结果存到字典里面去 import re file_path = r"./log.txt" with open(file_path, encoding="utf-8") as f: text = f.read() # print(words) words = re.findall("\w+", text) print("words type is {}".format(type(words))) print("words length is {}".format(len(words))) # print(words) # 单词全部小写 words = [w.lower() for w in words] mapping = dict() # 将单词数量作为键值存入到字典里. for word in words: mapping[word] = mapping.get(word, 0) + 1 print("mapping is : {}".format(mapping)) print("mapping.items():{}".format(mapping.items())) # 按着单词出现的次数高低排序. sorted_result = sorted(mapping.items(), key=lambda item: item[1], reverse=True) for i in sorted_result: print(i)
import numpy as np def CreateInitialPopulation(CostFunction, nindividuals, dim, domain, initial_domain): lower_bound, upper_bound = domain initial_lower_bound, initial_upper_bound = initial_domain if initial_lower_bound != None and initial_upper_bound != None: lower_bound = initial_lower_bound upper_bound = initial_upper_bound # Create the N individuals with random positions in the search space population = np.random.uniform(lower_bound, upper_bound, nindividuals*dim).reshape(nindividuals, dim) population_fitness = np.apply_along_axis(CostFunction, 1, population) # Reorder the population, best individuals first # order = np.argsort(population_fitness) # population_fitness = population_fitness[order] # population = population[order] # We return a second population and fitness as the current history of best position for each individual return population, population_fitness, population, population_fitness
from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: """ Initial thoughts: We move a first pointer k positions forward and save a reference to the node. Then we create another pointer at head and move it forward in sync with the first pointer while the first pointer hasn't hit the end of the linked list. When the first pointer hits the end, the second pointer is at the second node that needs to be swapped. Then we swap. Time complexity: O(n) Space complexity: O(1) """ def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: first = dummy_head = ListNode(0, head) for _ in range(k): first = first.next left_node = first second = dummy_head while first: first, second = first.next, second.next left_node.val, second.val = second.val, left_node.val return head
# https://leetcode.com/problems/longest-substring-without-repeating-characters/ # Related Topics: Hash Table, Two Pointers, String, Sliding Window # Difficulty: Medium class Solution: # Time complexity: O(n) where n is the length of the input string # Space complexity: O(1) since the dictionary has never more than 26 elements # Note: This is an optimized version of the further down algorithm # Since it does only one pass def lengthOfLongestSubstring(self, s: str) -> int: max_sub = 0 left = 0 have = dict() for right, el in enumerate(s): if el in have: left = max(left, have[el]+1) max_sub = max(max_sub, right - left + 1) have[el] = right return max_sub # Time complexity: O(n) where n is the length of the input string # Space complexity: O(1) since the set has never more than 26 elements def lengthOfLongestSubstring2(self, s: str) -> int: max_sub = 0 left = 0 have = set() for right, el in enumerate(s): while el in have: have.remove(s[left]) left += 1 have.add(el) max_sub = max(max_sub, right - left + 1) return max_sub # Initial Thoughts: # Using a Set and two pointers we are going to create a sliding window # that stores all its values in the Set. # Initially we start by advancing the right pointer and add the chars to # the set. Each time we calculate the distance between the two pointers as # the max substring without recurring chars and store it. # Whenever we encounter a duplicate value, we remove the char that the left # pointer is pointing to from the Set and move it forward until there is # no duplicate. We repeat this until the left's distance to the end is no more # than the max substring that we already found. # Time complexity O(n) where n == len(s) # Space complexity O(min(n,m)) where n == len(s) and m == len(charactersInAlphabet) # We could also argue that the space complexity is constant since the number of characters # in the alphabet is constant and well defined class Solution2: def lengthOfLongestSubstring(self, s: str) -> int: mySet = set() max = 0 left = right = 0 while left < len(s)-max: if not s[right] in mySet: mySet.add(s[right]) right += 1 max = right - left if right - left > max else max else: mySet.remove(s[left]) left += 1 return max
from typing import List class Solution: # Time complexity: O(m * n) where m and n are the sides of the grid # Space complexity: O(1) def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: R, C = len(grid), len(grid[0]) k = k % (R * C) res = [[0]*C for _ in range(R)] for (r, c) in ((r, c) for c in range(C) for r in range(R)): res[(r+(c+k)//C) % R][(c+k) % C] = grid[r][c] return res
from typing import List class Solution: # Time complexity: O(n) # Space complexity: O(1) def validMountainArray(self, arr: List[int]) -> bool: if len(arr) < 3: return False found_peak = False for i in range(1, len(arr)-1): if not found_peak: if arr[i] <= arr[i-1]: return False if arr[i] == arr[i+1]: return False if arr[i] > arr[i+1]: found_peak = True else: if arr[i] <= arr[i+1]: return False return found_peak
# https://leetcode.com/problems/smallest-string-starting-from-leaf/ # Related Topics: Tree, DFS # Difficulty: Medium # Initial thoughts: # Using a DFS approach, we are going to log each path from root to leaf. # Whenever we encounter a leaf, we are going to reverse the built path and # compare it to the answer that we have until then and update it if this string # is lexicographically smaller. # Time complexity: O(n * log n) where n === the number of nodes in the tree. # The idea is # that we have to visit each node in a DFS algorithm and for each possible leaf at the end # of the tree we have to compare the built string to the current answer. String comparison # takes O(l) where l equals the length of the shorter string in a comparison. In a ballanced # tree the length of the strings will equal the depth of the tree with is log(n), and the number # of leaf nodes will be roughly n/2 (half of the nodes in a ballanced binary tree are at the deepest level). # This will translate into (n/2 * log(n)) comparisons plus n for the DFS traversal => (n/2 * log(n)) + n, # which becomes O(n * log n) in big O notation. # Please note that in a perfectly unballanced binary tree that looks like a linked list, our strings will be # of length n (instead of log n) but since we are dealing with just one comparison, the end result will have a # lesser time complexity than the previous calculation, namely n (for DFS traversal) and n (for one comparison) => # n + n => O(n), so we stick with the first calculation, as it shows us the upper bound. # Space complexity: O(n) where n === the number of nodes in the tree (that's a worst case where # the binary tree is fully unballanced and looks like a linked list) # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self) -> None: self.answer = "~" def smallestFromLeaf(self, root: TreeNode) -> str: self.traverse(root, []) return self.answer def traverse(self, root: TreeNode, currPath: List[str]) -> None: if root == None: return currPath.append(self.getChar(root.val)) if root.left == None and root.right == None: self.answer = min(self.answer, "".join(reversed(currPath))) self.traverse(root.left, currPath) self.traverse(root.right, currPath) currPath.pop() def getChar(self, num: int) -> str: return chr(num + ord('a'))
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next import random class Solution: def __init__(self, head: Optional[ListNode]): self.data = [] while head: self.data.append(head.val) head = head.next self.length = len(self.data) def getRandom(self) -> int: return self.data[random.randint(0, self.length-1)]
# https://leetcode.com/problems/range-sum-query-immutable/ # Related Topics: Dynamic Programming # Difficulty: Easy # Initial thoughts: # The naive approach is to look at each and every element every time # and sum them. This would have a Time Complexity of O(n) and a Space Complexity of O(1) # Optimization: # Using a Dynamic Programming approach, we can create an array where array[k] holds the sum # of all the elements from nums[0] to nums[k]. # Looking from the sum between i and j (where i <= j) we are going to take array[j] that holds # the sum from nums[0] to nums[j] and subtract array[i] from it (which holds the sum from nums[0] to nums[i]) # If we do the preprocessing wisely, it won't take more than O(n) and the lookup time for the consequent sums # is constant. # Please note that this trade wouldn't have made sense if it wasn't specifically stated that the sum of different # ranges will be called repeatedly. # Time complexity: O(n) where n is the number of element in nums # Space complexity: O(n) where n is the number of elements in nums from typing import List class NumArray: def __init__(self, nums: List[int]): self._nums = nums self._dp = self.preprocess() def sumRange(self, i: int, j: int) -> int: return self._dp[j+1] - self._dp[i] def preprocess(self) -> List[int]: dp = [0 for i in range(len(self._nums)+1)] for i in range(len(self._nums)): dp[i+1] = dp[i] + self._nums[i] return dp def sumRangeNaive(self, i: int, j: int) -> int: sum = 0 for k in range(i, j+1): sum += self._nums[k] return sum # Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # param_1 = obj.sumRange(i,j)
# https://leetcode.com/problems/minimum-path-sum/ # Related Topics: Array, Dynamic Programming # Difficulty: Medium # Initial thoughts: # We can look at the problem as a tree where each cell is a node in the tree # that is connected to two other cells (one to its right and one to its bottom) # We are looking for the minimum path sum that lead to a leaf node (all the leaf # nodes are the bottom right cell in our matrix) # In other words, we have to look at all the possible sums that lead to the bottom # right cell and return the minimum. # Since this problem has an overlapping substructure, we can avoid redundant calculations # by using memoization. At each state if the data is available we are going to retrieve it, # otherwise we are going to fill it. # Time complexity: O(n) where n == number of cells in the grid # Space complexity: O(n) where n == number of cells in the grid. In a worst case scenario, # where our grid has only one row or one column, the recursive stack's depth will equal # the number of cells in the grid. In addition, our memoization grid needs to havev as much # cells as the original grid. class Solution: def minPathSum(self, grid: List[List[int]]) -> int: if not grid or not len(grid) or not len(grid[0]): return 0 R, C = len(grid), len(grid[0]) dp = [[None] * C for _ in range(R)] def dfs(row: int, col: int) -> int: if row == R-1 and col == C-1: return grid[row][col] if dp[row][col]: return dp[row][col] right = down = float('inf') if col < C-1: right = dfs(row, col+1) if row < R-1: down = dfs(row+1, col) dp[row][col] = grid[row][col]+min(right, down) return dp[row][col] return dfs(0, 0) # Optimization: # Using a dynamic programming approach, we can fill the grid in a tabular way always looking # for how to reach the next cell with minimum costs and build on that calculation for calculating # the minimum cost for reaching the next cell. # Time complexity: O(n) where n == number of cells in the grid # Space complexity: O(1) class Solution: def minPathSum(self, grid: List[List[int]]) -> int: if not grid or not len(grid) or not len(grid[0]): return 0 R, C = len(grid), len(grid[0]) for i in range(1, C): grid[0][i] += grid[0][i-1] for i in range(1, R): grid[i][0] += grid[i-1][0] for i in range(1, R): for j in range(1, C): grid[i][j] += min(grid[i-1][j], grid[i][j-1]) return grid[-1][-1]
from typing import List class Solution: # bottom up itetrative solution # Time complexity: R * C^2 where R is the number of rows and C the number of columns of the grid # Space complexity: C^2 (we only need to look back one row) def cherryPickup(self, grid: List[List[int]]) -> int: R, C = len(grid), len(grid[0]) dp = [[grid[-1][i] if i == j else grid[-1][i] + grid[-1][j] for i in range(C)] for j in range(C)] for r in range(R-2, -1, -1): new_dp = [[0]*C for _ in range(C)] for i, j in ((i, j) for i in range(C) for j in range(C)): new_dp[i][j] = max(dp[ni][nj] for ni, nj in ((i+ii, j+jj) for ii in range(-1,2) for jj in range(-1,2)) if 0 <= ni < C and 0 <= nj < C) new_dp[i][j] += grid[r][i] if i == j else (grid[r][i] + grid[r][j]) dp = new_dp return dp[0][C-1] # Top down recursive solution # Time complexity: O(r * c^2) where r is the number of rows and c the number of columns of the grid # Space complexity: O(r * c^2) def cherryPickup2(self, grid: List[List[int]]) -> int: R, C = len(grid), len(grid[0]) def dfs(r, c1, c2, memo): if r >= R: return 0 if not(0 <= c1 < C) or not(0 <= c2 < C): return float("-inf") if (r, c1, c2) in memo: return memo[(r, c1, c2)] memo[(r, c1, c2)] = ( max(dfs(r+1, c1+i, c2+j, memo) for i in range(-1, 2) for j in range(-1, 2)) + (grid[r][c1] if c1 == c2 else grid[r][c1] + grid[r][c2]) ) return memo[(r, c1, c2)] return dfs(0, 0, len(grid[0])-1, {})
from typing import List class Solution: # Time complexity: O(n) # Space complexity: O(n) def gameOfLife(self, board: List[List[int]]) -> None: """ Do not return anything, modify board in-place instead. """ R, C = len(board), len(board[0]) temp = [row[:] for row in board] def number_of_living_neighs(r, c): return sum(temp[r+rr][c+cc] if 0 <= r+rr < R and 0 <= c+cc < C and (rr != 0 or cc != 0) else 0 for rr in range(-1, 2) for cc in range(-1, 2)) for r in range(R): for c in range(C): num_living = number_of_living_neighs(r, c) if board[r][c]: # is alive if 2 <= num_living <= 3: continue board[r][c] = 0 else: # dead if num_living == 3: board[r][c] = 1
# https://leetcode.com/problems/path-sum/ # Related Topics: Tree, DFS # Difficulty: Easy # Initial thoughts: # Using a DFS algorithm we are going to check every path from root to its leafs # and subtracts the the nodes values from the given sum. If at the end sum turns # out to be zero, we have a path with the given sum. # One thing to be aware of is that we need to check that we are at a leaf. The condition # for that is the both its left and right children are null. It is not enough to check that # the node itself is null because the null node could be the child from partent node that # has its other child not null. # Time complexity: O(n) where n === the number of nodes in the tree # Space complexity: O(n) where n === the number of nodes in the tree (in the worst case when # we are dealing with a tree that is full unballanced and looks like a linked list) # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def hasPathSum(self, root: TreeNode, sum: int) -> bool: if root == None: return False if root.left == None and root.right == None: return sum - root.val == 0 return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
# https://leetcode.com/problems/add-two-numbers/ # Related Topics: Linked List, Math # Difficulty: Easy # Initial thoughts: # Creating a new linked list, we need to loop over the given # linked lists, adding their values and moving any remaining # carry to the next digit. # Keep in mind that some carry may remain after both the linked list # are completed. We need to add the remaining carry to the result if need be. # Time complexity: O(Max(n,m)) where n === len(l1) and m === len(l2) # Space complexity: O(Max(n,m)) where n === len(l1) and m === len(l2) # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode(None) curr = head carry = 0 while l1 or l2: if l1: carry += l1.val l1 = l1.next if l2: carry += l2.val l2 = l2.next curr.next = ListNode(carry % 10) carry //= 10 curr = curr.next if carry: curr.next = ListNode(carry) return head.next