blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
87a93fa069a3d6e9f4a839ae98d0a5e805f7210b
arod0214/python_intro_projects
/Rolling Two Dice.py
231
4.125
4
# Write a program that simulates rolling two 6-sided dice and tells the user the results of the two rolls and their sum. rollFirst = int(input("Roll 1:")) rollSecond = int(input("Roll 2:")) print("Sum:",(rollFirst + rollSecond))
ce97fd23900c559f4244f93268126610cfbc1519
MadSkittles/leetcode
/129.py
615
3.578125
4
from common import TreeNode class Solution: def sumNumbers(self, root): self.result = 0 if root: self.f(root, root.val) return self.result def f(self, node, num): if node.left is None and node.right is None: self.result += num return if node.left: self.f(node.left, num * 10 + node.left.val) if node.right: self.f(node.right, num * 10 + node.right.val) if __name__ == '__main__': solution = Solution() print(solution.sumNumbers(TreeNode.list2Tree([1, None, 3])))
679eb24f7b03de63264ca8c8b4ebd99afbc6a78a
ChromeUniverse/preparatorio-obi
/Aulas/5/comandos.py
894
3.796875
4
# coding: utf-8 linhas = ['ana', 'beatriz', 'clara'] linhas # lista de strings >>> string ' '.join(linhas) '--'.join(linhas) s = ''.join(linhas) s s = ' '.join(linhas) # string >>> lista de strings s.split() s = '--'.join(linhas) s s.split() s.split('--') s = '1 2 3 4' l = s.split() l [1, 2, 3, 4] nums = [] l for num in l: print( int(num) ) for num in l: print( int(num) + 1 ) l for num in l: print( num + 1 ) nums = [] for num in l: n = int(num) nums.append(n) nums nums = [int(num) for num in l] s list(s) s = 'cão' list(s) l = list(s) l l[2] = 'a' l ''.join(l) l = [1, 2, 2] l.remove(2) l l.remove(2) l l.remove(2) s = 'ola' for c in s: # c = 'a' print(c) l = [1,2, 3, ] l l.index(3) d = {} # dict() d d['a'] = 1 d d['b'] = 1 d d['a'] d['b'] {} # dict get_ipython().magic('save comandos.py ~0/')
f8f709c4095527c249906ea206e1db851f6fd7f4
6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion
/CH02/EX2.18.py
637
4.34375
4
# (Current time) Listing 2.7, ShowCurrentTime.py, gives a program that displays the # current time in GMT. Revise the program so that it prompts the user to enter the # time zone in hours away from (offset to) GMT and displays the time in the specified # time zone. import time tzo = eval(input("Enter the time zone offset to GMT:")) currentTime = time.time() totalSeconds = int(currentTime) currentSecond = totalSeconds % 60 totalMinutes = totalSeconds // 60 currentMintute = totalMinutes % 60 totalHours = totalMinutes // 60 currentHour = totalHours % 24 currentHour += tzo print(currentHour, ":", currentMintute, ":", currentSecond)
b13ddef541bdaac4c0cc3b2b4923edd2bdc7bc6b
tteearu/learning_code
/Python/Codeclub/calculator/calculator_original.py
1,502
3.765625
4
class Calculator: def calculate(self, input_string): tehe = [] operators = ['+','-','*','/'] result = 0 temp = "" special = ['*','/'] for x in input_string: if x in operators: try: tehe.append(float(temp)) except ValueError: pass tehe.append(x) temp = "" else: temp += x tehe.append(float(temp)) multiplications = tehe.count('*') divisions = tehe.count('/') while multiplications > 0: position = tehe.index('*') if tehe[position-2] not in special: korrutis = tehe[position-1] * tehe[position+1] del tehe[position-1:position+2] tehe.insert(position-1,korrutis) multiplications -= 1 else: position = tehe.index('/') if tehe[position-2] not in special: jagatis = tehe[position-1] / tehe[position+1] del tehe[position-1:position+2] tehe.insert(position-1,jagatis) divisions -= 1 while divisions > 0: position = tehe.index('/') if tehe[position-2] not in special: jagatis = tehe[position-1] / tehe[position+1] del tehe[position-1:position+2] tehe.insert(position-1,jagatis) divisions -= 1 else: pass while len(tehe) > 0: for x in tehe: if x not in operators: position = tehe.index(x) if position == 0: result += x del tehe[0] elif tehe[position-1] == "+": result += x del tehe[position-1:position+1] elif tehe[position-1] == "-": result -= x del tehe[position-1:position+1] return result
44455b2adc666ee595188a6561999faaa322d4c6
tejas77/codechef-python
/Beginner/FLOW004/main.py
115
3.546875
4
t = int(input()) while t > 0: number = list(input()) print(int(number[0]) + int(number[-1])) t = t - 1
e7cb6140348156333a2c3f553c83909c1fa4031e
MohamadShafeah/python
/Day1/02Formatting/O004formattingBasics.py
339
3.65625
4
# 1 classical printf emulate frm_str = "Hello Mr.%s %s talented Guy" val_info = ('Scahin', "Super") print(frm_str % val_info) val_info = ('Scahin', 1000) # 1000 convered as string print(frm_str % val_info) frm_str = "Hello Mr.%s %.3f talented Guy" val_info = ('Scahin', 1000) # 1000 taken as float print(frm_str % val_info)
551df71fa265ec0a82acbb1cad6ea1b40d8327c6
manish1822510059/Python-1000-Programs
/List/3_Traverse_list_using_loop.py
129
3.984375
4
myList = ["iphone",'Mi','Vivo','Oneplus','Samsang','Oppo'] print("All items of the List") for item in myList: print(item)
996d9d4b9475e1778a821214d2a47511cbb90104
AdamZhouSE/pythonHomework
/Code/CodeRecords/2465/60708/302131.py
328
3.65625
4
def find(list): for i in list: sum=0 for j in list: if j>=i: sum=sum+1 if sum<=i: return sum if __name__ == '__main__': temp=input() for i,j in enumerate(temp): if j=='[': break list=eval(temp[i:len(temp)]) print(find(list))
85875bb767ccda41f1f04c97686d1ce9b1152b35
willscarvalho/Jogo_da_Velha
/src/funcoes.py
6,727
4.1875
4
def criar_tabuleiro(): """ Função que cria o tabuleiro das posições do jogo. Return: retorno uma listas contendo outra 3 listas respectivamente com os valores vazio do tabuleiro -> representação de matriz em python. """ tabuleiro = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] return tabuleiro def definir_ganhador(ganhador, jogador1, jogador2): """ Função para definir quem ganhou o jogo, caso não há ganhador retorna velha. ganhador: Variável do loop que identifica se o ganhador e X ou Y antes das 9 jogadas. jogador1: variável jo primeiro jogador jogador2: variavel do segundo jogador: Obs: exibi a menssagem de acordo com o ganhador ou empate. """ print('{}'.format(ganhador)) if ganhador == jogador1: print('O Jogador1 = {}, GANHOU!'.format(ganhador)) else: if ganhador == jogador2: print('O Jogador2 = {}, GANHOU!'.format(ganhador)) else: print('Deu VELHA!') def definir_posicao_jogada(): """ Função para definir as entradas da linha e coluna no tabuleiro. return: retornará os inteiros da linah e coluna para as variáveis que chamam a função. """ linha = int(input('Linha: ')) coluna = int(input('Coluna: ')) return linha, coluna def efetuar_jogada(jogador, tabuleiro): """ Função para efetuar a jogada no tabuleiro. jogador = jogador atual da rodada. tabuleiro = tabuleiro do jogo a cada jogada. return: tabuleiro atualizado com a jogada na posição. """ linha = coluna = validar = 0 while True: linha, coluna = definir_posicao_jogada() validar = verificar_jogada(linha, coluna, tabuleiro) if validar == 1: tabuleiro[linha][coluna] = jogador log_jogada(jogador, linha, coluna) mostrar_tabuleiro(tabuleiro) break return tabuleiro def escolher_jogador(): """ Função para escolher qual variável cada jogador irá jogar. return: as variáveis dos jogadores respectivamente para a variáveis que chamam essa função. """ while True: jog1 = ' ' jog2 = ' ' print('1° Jogador, Ecolhe X ou O : ') opcao = str(input('')).strip().upper()[0] if opcao in 'xX' or opcao in 'oO': if opcao in 'xX': jog1 = opcao jog2 = 'O' elif opcao in 'oO': jog1 = opcao jog2 = 'X' print('Jogador 1 = {}.'.format(jog1)) print('Jogador 2 = {}.'.format(jog2)) break else: print('Entrada inválida.') return jog1, jog2 def inicio(): """ Função para exibir na tela o início do jogo. """ print('{}{}{}'.format('.', '-'*40, '.')) print('{:<15}JOGO DA VELHA{:>14}'.format('|', '|')) print('{}{}{}'.format("'", '-'*40, "'")) def jogo_loop(tabuleiro, jogador1, jogador2, ganhador): """ Função que fará o loop das 9 jogadas possíveis no tabuleiro. tabuleiro = tabuleiro do jogo. jogador1 = primeiro jogador coma variável definida. jogador2 = segundo jgoador com a variável definida. ganhador = ganhado em branco, para receber a função de verificação do ganhador. Obs: Essa função chamam as demais funções do jogo. """ for i in range(1, 10): print('{}{}{}'.format('.', '-'*40, '.')) print('{}{:>17}° Jogada{:>16}'.format('|', i, '|')) print('{}{}{}'.format("'", '-'*40, "'")) if i % 2 == 1: tabuleiro = efetuar_jogada(jogador1, tabuleiro) jogador = jogador1 elif i % 2 == 0: tabuleiro = efetuar_jogada(jogador2, tabuleiro) jogador = jogador2 if i >= 5: ganhador = verificar_ganhador(tabuleiro, jogador) if ganhador == 'X' or ganhador == 'O': break definir_ganhador(ganhador, jogador1, jogador2) def log_jogada(jogador, linha, coluna): """ Função para exibir as jogadas de cada jogador. jogador = jogador respectivamente da jogada atual. linha = linha escolhida do tabuleiro. coluna = escolhida do tabuleiro. """ print('O jogador {} realizou a jogada.'.format(jogador)) print('Na linha {} e Coluna {}.'.format(linha, coluna)) def mostrar_tabuleiro(tab): """ Função para exibir o tabuleiro atualizado. tab = tabuleiro atual no momento que chamar a função. """ print('\n') print('\t {} | {} | {} '.format(tab[0][0], tab[0][1], tab[0][2])) print('\t-----|-----|-----') print('\t {} | {} | {} '.format(tab[1][0], tab[1][1], tab[1][2])) print('\t-----|-----|-----') print('\t {} | {} | {} '.format(tab[2][0], tab[2][1], tab[2][2])) print('\n') def mostrar_tabuleiro_inicial(): """ Função para exibir o tabuleiro inicial com as numerações de linha e coluna respectivamente de cada posição. """ print('\n') print('\t {} | {} | {} '.format('00', '01', '02')) print('\t------|------|------') print('\t {} | {} | {} '.format('10', '11', '12')) print('\t------|------|------') print('\t {} | {} | {} '.format('20', '21', '22')) print('\n') def verificar_jogada(linha, coluna, tabuleiro): """ Função para verificar se a jogada é possível. linha = linha da jogada. coluna = coluna da jogada. tabuleiro = do jogo. return a permissão da jogada, 0 não permitida e 1 para permitida. """ permissao = 0 if tabuleiro[linha][coluna] in 'xX' or tabuleiro[linha][coluna] in 'oO': print('Jogada não permitida.') else: permissao = 1 return permissao def verificar_ganhador(t, jog): """ Função para verificar o ganhador. t = tabuleiro do jogo. jogador = jogado da rodada. return o ganhador, caso há. """ ganhador = '' # Verificando Colunas: if (t[0][0] == jog and t[1][0] == jog and t[2][0] == jog) \ or (t[0][1] == jog and t[1][1] == jog and t[2][1] == jog) \ or (t[0][2] == jog and t[1][2] == jog and t[2][2] == jog): ganhador = jog # Verificando Linhas: elif (t[0][0] == jog and t[0][1] == jog and t[0][2] == jog) \ or (t[1][0] == jog and t[1][1] == jog and t[1][2] == jog) \ or (t[2][0] == jog and t[2][1] == jog and t[2][2] == jog): ganhador = jog # Verificando Diagonais: elif (t[0][0] == jog and t[1][1] == jog and t[2][2] == jog) \ or (t[2][0] == jog and t[1][1] == jog and t[0][2] == jog): ganhador = jog else: ganhador = 'NaN' return ganhador.upper()
cd1c4c92cd56ad9df1457e6fc9c774029ff3c9ea
Musawir-Ahmed/OOP
/WEEK-3/PRODUCT-LIST-(OOP).py
2,780
3.609375
4
import os # DECLARING A OST TO STORE PRODUCT DATA productrecord = [] # DECLARING CLASS class productinfo: ProductId = 0 Name = "" Price = 0 Category = "" Brandname = "" Country = "" # HEADER FUNCTION def header(): print("**************************************************************************\n") print(" PRODUCT RECORD \n") print("**************************************************************************\n") print("--------------------------------------------------------------------------\n") # OPTIONS DISPLAYING FUNCTION def displayoptions(): print("1.ADD PRODUCT") print("2.SHOW PRODUCT") print("3.TOTAL STORE WORTH") print("4.EXIT") # ADD PRODUCT FUNCTON def addproduct(): product = productinfo() product.ProductId = int(input("ENTER PRODUCT ID =")) product.Name = input("ENTER NAME OF TJE PRODUCT =") product.Price = int(input("ENTER PRICE OF THE PRODUCT =")) product.Category = input("ENTER CATEGORY OF THE PRODUCT =") product.Brandname = input("ENTER BRAND NAME OF THE PRODUCT =") product.Country = input("ENTER NAME THE COUNTRY WHER PRODUCT PRODUCED =") return product # CLEAR SCREEN FUNCTION def clearscreen(): os.system('cls' if os.name == 'nt' else 'clear') # PRESS KEY TO CONTINUE FUNCTION def presskey(): input("PRESS ENTER TO CONTINUE.............") # FUCNTION TO SHOW ALL THE PRODUCTS SAVED def showproduct(productrecord): print("NAME\t ID \tPRICE\tCATEGORY\tBRAND\tCOUNTRY") for field in productrecord: print(field.ProductId, "\t", field.Name, "\t", field.Price, "\t", field.Category, "\t", field.Brandname, "\t", field.Country, "\n") # PROGRSM TO SHOW PRODUCTS STORE def totalworth(productrecord): totalworth = 0 for field in productrecord: field.Price = int(field.Price) totalworth = totalworth+field.Price return totalworth program_running = True counter = 0 # MAIN LOOP while program_running == True: clearscreen() header() displayoptions() option = int(input("ENTER OPTION NUMBER =")) # OPTION 1 TO ADD PRODUCT if option == 1: clearscreen() record = addproduct() productrecord.append(record) # OPTION 2 TO SHOW PRODUCTS if(option == 2): clearscreen() header() showproduct(productrecord) presskey() # TO CALCULAYE TOTAL WORTH if(option == 3): worth = totalworth(productrecord) print("TOTAL WORTH OF THE STORE IS =", worth) presskey() # TO TERMINATE PROGRAM if(option == 4): program_running = False
1f9e52e3c321e66142c3b8ea0ff638a816b091d2
Holarctic/Python-programming-exercises-master
/Answears/question3.py
120
3.640625
4
n = int(raw_input()) d = dict() for i in range(1, n + 1): d[i] = i*i #for i in range(1, n + 1): # d[i] = i*i*i print d
150355d299dd9523f597aa1fd68b0a8bb2f81972
yodeng/sw-algorithms
/pythonic/tree/binary_tree.py
2,473
3.859375
4
#!/usr/bin/env python # encoding: utf-8 """ @author: swensun @github:https://github.com/yunshuipiao @software: python @file: binary_tree.py @desc: 二叉树的构造 @hint: 对左右子树分别插入 """ class Node: def __init__(self, data): self.data = data self.left_child = None self.right_child = None def create_tree(): node_list = [] for i in range(10): node_list.append(Node(i)) node_list[0].left_child = node_list[1] node_list[0].right_child = node_list[2] node_list[1].left_child = node_list[3] node_list[2].left_child = node_list[4] node_list[2].right_child = node_list[5] node_list[3].right_child = node_list[7] node_list[4].right_child = node_list[9] node_list[5].left_child = node_list[6] node_list[7].left_child = node_list[8] return node_list[0] #return tree root node def create_symmetric_tree(): node_list = [Node(0), Node(1), Node(1), Node(2), Node(2), Node(3), Node(3), Node(4), Node(4), Node(5), Node(5)] node_list[0].left_child = node_list[1] node_list[0].right_child = node_list[2] node_list[1].left_child = node_list[3] node_list[1].right_child = node_list[5] node_list[2].left_child = node_list[6] node_list[2].right_child = node_list[4] node_list[5].right_child = node_list[7] node_list[6].left_child = node_list[8] node_list[7].left_child = node_list[9] node_list[8].right_child = node_list[10] return node_list[0] #return tree root node def create_bst(): node_list = [Node(0), Node(1), Node(2), Node(3), Node(4), Node(5), Node(6), Node(7), Node(8), Node(9), Node(10)] node_list[1].left_child = node_list[0] node_list[1].right_child = node_list[2] node_list[3].left_child = node_list[1] node_list[3].right_child = node_list[4] node_list[5].left_child = node_list[3] node_list[5].right_child = node_list[8] node_list[8].left_child = node_list[6] node_list[8].right_child = node_list[10] node_list[6].right_child = node_list[7] node_list[10].left_child = node_list[9] return node_list[5] #return tree root node class BinaryTree: def __init__(self): # self.treeNode = Node() self.root = create_tree() def create_symmetric_tree(self): self.root = create_symmetric_tree() def create_bst(self): self.root = create_bst() if __name__ == '__main__': tree = BinaryTree() print(tree.root.data)
5e1586b64218a125f588e9ef8f07f1774dfe2151
code-evince/CipherSchools_Assignment
/Assignment-2/Print All Possible Combination Mobile.py
942
3.859375
4
hashTable = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] def printWordsUtil(number, curr, output, n): if(curr == n): ans ='' for i in output: ans+=i print(ans,end=' ') return for i in range(len(hashTable[number[curr]])): output.append(hashTable[number[curr]][i]) printWordsUtil(number, curr + 1, output, n) output.pop() if(number[curr] == 0 or number[curr] == 1): return; def possibleWords(a,N): printWordsUtil(a, 0, [], N) import math def main(): print("Enter no of test cases :" ) T=int(input()) while(T>0): print("Enter no of buttons : ") N=int(input()) print("Enter the numbers separated by spaces: ") a=[int(x) for x in input().strip().split()] possibleWords(a,N) print() T-=1 if __name__=="__main__": main()
13376868f0514f690adeb0ce2a21637acddb5fee
zc-cris/python_demo01
/primary02/demo14_计算连续数字的方法2.py
322
3.859375
4
# _Author: zc-cris string = "232jj2kj2" for i in string: if i.isalpha(): string = string.replace(i, " ") print(string) # 232 2 2 string = string.split() # If sep is not specified or is None, any # whitespace string is a separator and empty strings are # removed from the result print(len(string)) # 3
5602a41cc004b3074a2b2d88059ec2328579b2c6
kambizmir/MLND-Capstone-Micromouse
/robot.py
35,780
4.28125
4
import numpy as np from maze import Maze import turtle import sys from collections import deque from random import randint import time class Robot(object): def __init__(self, maze_dim): ''' Use the initialization function to set up attributes that your robot will use to learn and navigate the maze. Some initial attributes are provided based on common information, including the size of the maze the robot is placed in. ''' self.discoveryDone = False self.shortestPathSearchStarted = False self.shortestPathSearchDone = False self.shortestPath = [] self.location = [0, 0] self.heading = 'up' self.maze_dim = maze_dim self.allBordersData = {} self.allWalls = {} self.bordersStack = [] self.cellsStack = [] self.passedBorders = {} self.visitedCells = {} self.steps = 0 self.sq_size = 0 self.origin = 0 self.wally = None self.buildAllBordersData() self.cellsGraph = {} self.currentShortestPathIndex = 1 window = turtle.Screen() self.wally = turtle.Turtle() self.wally.color("grey") self.wally.speed(0) self.wally.hideturtle() self.wally.penup() self.sq_size = 20 self.origin = self.maze_dim * self.sq_size / -2 def next_move(self, sensors): ''' Use this function to determine the next move the robot should make, based on the input from the sensors after its previous move. Sensor inputs are a list of three distances from the robot's left, front, and right-facing sensors, in that order. Outputs should be a tuple of two values. The first value indicates robot rotation (if any), as a number: 0 for no rotation, +90 for a 90-degree rotation clockwise, and -90 for a 90-degree rotation counterclockwise. Other values will result in no rotation. The second value indicates robot movement, and the robot will attempt to move the number of indicated squares: a positive number indicates forwards movement, while a negative number indicates backwards movement. The robot may move a maximum of three units per turn. Any excess movement is ignored. If the robot wants to end a run (e.g. during the first training run in the maze) then returing the tuple ('Reset', 'Reset') will indicate to the tester to end the run and return the robot to the start. ''' rotation =0 movement = 0 #time.sleep(.01) self.steps += 1 if self.discoveryDone == True and self.shortestPathSearchStarted == False: #print len(self.allBordersData) , self.allWalls.keys() , len(self.allWalls.keys()) self.shortestPathSearchStarted = True self.heading = "up" self.location = (0,0) self.wally.penup() self.wally.setpos(self.origin + self.sq_size * self.location[0] + self.sq_size/2, self.origin + self.sq_size * (self.location[1]) + self.sq_size/2) self.buildGraph() self.findShortestPath() self.shortestPathSearchDone = True return ('Reset', 'Reset') if self.shortestPathSearchDone == True: self.wally.width(3) self.wally.pendown() time.sleep(1) self.wally.color("blue") self.wally.setpos(self.origin + self.sq_size * self.location[0] + self.sq_size/2, self.origin + self.sq_size * (self.location[1]) + self.sq_size/2) self.wally.dot() #print self.location currentCellCode = self.shortestPath[self.currentShortestPathIndex] x1 = int(currentCellCode[0:2]) y1 = int(currentCellCode[2:4]) previousCellCode = self.shortestPath[self.currentShortestPathIndex-1] x0 = int(previousCellCode[0:2]) y0 = int(previousCellCode[2:4]) ydif = 0 xdif = 0 if x1 == x0: ydif = y1 - y0 elif y1 == y0: xdif = x1 - x0 #print "DIFFS = " , xdif , ydif # go based on xdif and y dif if self.heading == 'up': if ydif != 0 : rotation = 0 movement = ydif self.heading = 'up' self.location = (x1,y1) elif xdif > 0: rotation = 90 movement = xdif self.heading = 'right' self.location = (x1,y1) elif xdif < 0: rotation = -90 movement = -xdif self.heading = 'left' self.location = (x1,y1) elif self.heading == 'down': if ydif != 0 : rotation = 0 movement = -ydif self.heading = 'down' self.location = (x1,y1) elif xdif > 0: rotation = -90 movement = xdif self.heading = 'right' self.location = (x1,y1) elif xdif < 0: rotation = 90 movement = -xdif self.heading = 'left' self.location = (x1,y1) elif self.heading == 'right': if xdif != 0 : rotation = 0 movement = xdif self.heading = 'right' self.location = (x1,y1) elif ydif > 0: rotation = -90 movement = ydif self.heading = 'up' self.location = (x1,y1) elif ydif < 0: rotation = 90 movement = -ydif self.heading = 'down' self.location = (x1,y1) elif self.heading == 'left': if xdif != 0 : rotation = 0 movement = -xdif self.heading = 'left' self.location = (x1,y1) elif ydif > 0: rotation = 90 movement = ydif self.heading = 'up' self.location = (x1,y1) elif ydif < 0: rotation = -90 movement = -ydif self.heading = 'down' self.location = (x1,y1) #print rotation, movement, self.heading,self.location self.currentShortestPathIndex += 1 if self.currentShortestPathIndex == len(self.shortestPath) : time.sleep(1) self.location =( int(self.shortestPath[-1][0:2]) , int(self.shortestPath[-1][2:4]) ) self.wally.setpos(self.origin + self.sq_size * self.location[0] + self.sq_size/2, self.origin + self.sq_size * (self.location[1]) + self.sq_size/2) turtle.Screen().exitonclick() return (rotation,movement) leftOpen = sensors[0] frontOpen = sensors[1] rightOpen = sensors[2] locationX = self.location[0] locationY = self.location[1] ''' print "\n" print "steps = ",self.steps print "location = " , locationX, locationY print "heading = " , self.heading print "left open = ",leftOpen print "front open = ",frontOpen print "right open = ", rightOpen ''' self.wally.setpos(self.origin + self.sq_size * locationX + self.sq_size/2, self.origin + self.sq_size * (locationY) + self.sq_size/2) self.wally.dot() self.drawDiscoveredBorders(sensors) nextForwardMoves = [] leftCellCode = "" frontCellCode = "" rightCellCode = "" leftBorderCode = "" frontBorderCode = "" rightBorderCode = "" if self.heading == "up": leftCellCode = str(locationX-1).zfill(2) + str(locationY).zfill(2) leftBorderCode = str(locationX).zfill(2) + str(locationY).zfill(2) + str(locationX-1).zfill(2) + str(locationY).zfill(2) frontCellCode = str(locationX).zfill(2) + str(locationY+1).zfill(2) frontBorderCode = str(locationX).zfill(2) + str(locationY).zfill(2) + str(locationX).zfill(2) + str(locationY+1).zfill(2) rightCellCode = str(locationX+1).zfill(2) + str(locationY).zfill(2) rightBorderCode = str(locationX).zfill(2) + str(locationY).zfill(2) + str(locationX+1).zfill(2) + str(locationY).zfill(2) elif self.heading == "right": leftCellCode = str(locationX).zfill(2) + str(locationY+1).zfill(2) leftBorderCode = str(locationX).zfill(2) + str(locationY).zfill(2) + str(locationX).zfill(2) + str(locationY+1).zfill(2) frontCellCode = str(locationX+1).zfill(2) + str(locationY).zfill(2) frontBorderCode = str(locationX).zfill(2) + str(locationY).zfill(2) + str(locationX+1).zfill(2)+ str(locationY).zfill(2) rightCellCode = str(locationX).zfill(2) + str(locationY-1).zfill(2) rightBorderCode = str(locationX).zfill(2) + str(locationY).zfill(2) + str(locationX).zfill(2) + str(locationY-1).zfill(2) elif self.heading == "left": leftCellCode = str(locationX).zfill(2) + str(locationY-1).zfill(2) leftBorderCode = str(locationX).zfill(2) + str(locationY).zfill(2) + str(locationX).zfill(2) + str(locationY-1).zfill(2) frontCellCode = str(locationX-1).zfill(2) + str(locationY).zfill(2) frontBorderCode = str(locationX).zfill(2) + str(locationY).zfill(2) + str(locationX-1).zfill(2) + str(locationY).zfill(2) rightCellCode = str(locationX).zfill(2) + str(locationY+1).zfill(2) rightBorderCode = str(locationX).zfill(2) + str(locationY).zfill(2) + str(locationX).zfill(2) + str(locationY+1).zfill(2) elif self.heading == "down": leftCellCode = str(locationX+1).zfill(2) + str(locationY).zfill(2) leftBorderCode = str(locationX).zfill(2) + str(locationY).zfill(2) + str(locationX+1).zfill(2) + str(locationY).zfill(2) frontCellCode = str(locationX).zfill(2) + str(locationY-1).zfill(2) frontBorderCode = str(locationX).zfill(2) + str(locationY).zfill(2) + str(locationX).zfill(2) + str(locationY-1).zfill(2) rightCellCode = str(locationX-1).zfill(2) + str(locationY).zfill(2) rightBorderCode = str(locationX).zfill(2) + str(locationY).zfill(2) + str(locationX-1).zfill(2) + str(locationY).zfill(2) if leftOpen>0 and (not leftCellCode in self.visitedCells): nextForwardMoves.append("left") if frontOpen>0 and (not frontCellCode in self.visitedCells): nextForwardMoves.append("front") if rightOpen>0 and (not rightCellCode in self.visitedCells): nextForwardMoves.append("right") #print nextForwardMoves if len(nextForwardMoves) >0: nextMove = nextForwardMoves[randint(0, len(nextForwardMoves) -1 )] # Make it random if nextMove == "left": rotation = -90 movement = 1 self.passedBorders[leftBorderCode] = leftBorderCode self.visitedCells[leftCellCode] = leftCellCode self.cellsStack.append(leftCellCode) if self.heading == "up": self.heading = "left" self.location = (locationX-1,locationY) elif self.heading == "left": self.heading = "down" self.location = (locationX,locationY-1) elif self.heading == "right": self.heading = "up" self.location = (locationX,locationY+1) elif self.heading == "down": self.heading = "right" self.location = (locationX+1,locationY) elif nextMove == "front": rotation = 0 movement = 1 self.passedBorders[frontBorderCode] = frontBorderCode self.visitedCells[frontCellCode] = frontCellCode self.cellsStack.append(frontCellCode) if self.heading == "up": self.heading = "up" self.location = (locationX,locationY+1) elif self.heading == "left": self.heading = "left" self.location = (locationX-1,locationY) elif self.heading == "right": self.heading = "right" self.location = (locationX+1,locationY) elif self.heading == "down": self.heading = "down" self.location = (locationX,locationY-1) elif nextMove == "right": rotation = 90 movement = 1 self.passedBorders[rightBorderCode] = rightBorderCode self.visitedCells[rightCellCode] = rightCellCode self.cellsStack.append(rightCellCode) if self.heading == "up": self.heading = "right" self.location = (locationX+1,locationY) elif self.heading == "left": self.heading = "up" self.location = (locationX,locationY+1) elif self.heading == "right": self.heading = "down" self.location = (locationX,locationY-1) elif self.heading == "down": self.heading = "left" self.location = (locationX-1,locationY) else: currentCellCode = self.cellsStack[-1] returnCellCode = self.cellsStack[-2] currentLocation = (int(currentCellCode[0:2]) , int(currentCellCode[2:4]) ) returnLocation = (int(returnCellCode[0:2]) , int(returnCellCode[2:4]) ) #print currentLocation, returnLocation if currentLocation[0] == returnLocation[0]: if currentLocation[1]>returnLocation[1]: if self.heading == "down": rotation = 0 movement = 1 self.heading = "down" self.location = (locationX, locationY-1) self.passedBorders[frontBorderCode] = frontBorderCode self.cellsStack.pop() elif self.heading == "left": rotation = -90 movement = 1 self.heading = "down" self.location = (locationX, locationY-1) self.passedBorders[leftBorderCode] = leftBorderCode self.cellsStack.pop() elif self.heading == "right": rotation = 90 movement = 1 self.heading = "down" self.location = (locationX, locationY-1) self.passedBorders[rightBorderCode] = rightBorderCode self.cellsStack.pop() elif self.heading == "up": rotation = 90 movement = 0 self.heading = "right" self.location = (locationX, locationY) else: #currentLocation[1]<returnLocation[1] if self.heading == "up": rotation = 0 movement = 1 self.heading = "up" self.location = (locationX, locationY+1) self.passedBorders[frontBorderCode] = frontBorderCode self.cellsStack.pop() elif self.heading == "left": rotation = 90 movement = 1 self.heading = "up" self.location = (locationX, locationY+1) self.passedBorders[rightBorderCode] = rightBorderCode self.cellsStack.pop() elif self.heading == "right": rotation = -90 movement = 1 self.heading = "up" self.location = (locationX, locationY+1) self.passedBorders[leftBorderCode] = leftBorderCode self.cellsStack.pop() elif self.heading == "down": rotation = 90 movement = 0 self.heading = "left" self.location = (locationX, locationY) elif currentLocation[1] == returnLocation[1]: if currentLocation[0]>returnLocation[0]: if self.heading == "left": rotation = 0 movement = 1 self.heading = "left" self.location = (locationX-1, locationY) self.passedBorders[frontBorderCode] = frontBorderCode self.cellsStack.pop() elif self.heading == "up": rotation = -90 movement = 1 self.heading = "left" self.location = (locationX-1, locationY) self.passedBorders[leftBorderCode] = leftBorderCode self.cellsStack.pop() elif self.heading == "down": rotation = 90 movement = 1 self.heading = "left" self.location = (locationX-1, locationY) self.passedBorders[rightBorderCode] = rightBorderCode self.cellsStack.pop() elif self.heading == "right": rotation = 90 movement = 0 self.heading = "down" self.location = (locationX, locationY) else: #currentLocation[0]<returnLocation[0] if self.heading == "right": rotation = 0 movement = 1 self.heading = "right" self.location = (locationX+1, locationY) self.passedBorders[frontBorderCode] = frontBorderCode self.cellsStack.pop() elif self.heading == "down": rotation = -90 movement = 1 self.heading = "right" self.location = (locationX+1, locationY) self.passedBorders[leftBorderCode] = leftBorderCode self.cellsStack.pop() elif self.heading == "up": rotation = 90 movement = 1 self.heading = "right" self.location = (locationX+1, locationY) self.passedBorders[rightBorderCode] = rightBorderCode self.cellsStack.pop() elif self.heading == "left": rotation = 90 movement = 0 self.heading = "up" self.location = (locationX, locationY) return rotation, movement def buildAllBordersData(self): for x in range(self.maze_dim - 1): for y in range(self.maze_dim ): borderCode = str(x).zfill(2) + str(y).zfill(2) + str(x+1).zfill(2) + str(y).zfill(2) self.allBordersData[borderCode] = borderCode for y in range(self.maze_dim - 1): for x in range(self.maze_dim ): borderCode = str(x).zfill(2) + str(y).zfill(2) + str(x).zfill(2) + str(y+1).zfill(2) self.allBordersData[borderCode] = borderCode #print self.allBordersData.keys() , len(self.allBordersData) def drawDiscoveredBorders(self,sensors): self.wally.color("red") leftOpen = sensors[0] frontOpen = sensors[1] rightOpen = sensors[2] locationX = self.location[0] locationY = self.location[1] #print locationX,locationY,leftOpen,frontOpen,rightOpen, self.heading #print(self.wally.position()) temp = self.wally.position() self.wally.hideturtle() if self.heading == "up": self.wally.penup() self.wally.setpos(temp[0]-self.sq_size/2, temp[1] + (frontOpen) * self.sq_size + self.sq_size/2 ) self.wally.pendown() self.wally.setpos(temp[0]+self.sq_size/2, temp[1] + (frontOpen) * self.sq_size + self.sq_size/2 ) self.wally.penup() self.wally.goto(temp[0]+ (rightOpen) * self.sq_size + self.sq_size/2 , temp[1] + self.sq_size/2 ) self.wally.pendown() self.wally.goto(temp[0]+ (rightOpen) * self.sq_size + self.sq_size/2 , temp[1] - self.sq_size/2 ) self.wally.penup() self.wally.goto(temp[0]- (leftOpen) * self.sq_size - self.sq_size/2 , temp[1] + self.sq_size/2 ) self.wally.pendown() self.wally.goto(temp[0]- (leftOpen) * self.sq_size - self.sq_size/2 , temp[1] - self.sq_size/2 ) self.wally.penup() self.wally.goto(temp) for x in range(leftOpen+1): b = str(locationX - x - 1).zfill(2) + str(locationY).zfill(2) + str(locationX - x ).zfill(2) + str(locationY).zfill(2) self.allBordersData.pop(b, None) if x == leftOpen and locationX - leftOpen >0: self.allWalls[b] = b for x in range(rightOpen+1): b = str(locationX + x ).zfill(2) + str(locationY).zfill(2) + str(locationX + x + 1).zfill(2) + str(locationY).zfill(2) self.allBordersData.pop(b, None) if x == rightOpen and locationX + rightOpen < self.maze_dim - 1 : self.allWalls[b] = b for y in range(frontOpen+1): b = str(locationX).zfill(2) + str(locationY + y).zfill(2) + str(locationX).zfill(2) + str(locationY + y + 1).zfill(2) self.allBordersData.pop(b, None) if y == frontOpen and locationY + frontOpen < self.maze_dim - 1: self.allWalls[b] = b elif self.heading == "right": self.wally.penup() self.wally.goto(temp[0]+ (frontOpen) * self.sq_size + self.sq_size/2 , temp[1] + self.sq_size/2 ) self.wally.pendown() self.wally.goto(temp[0]+ (frontOpen) * self.sq_size + self.sq_size/2 , temp[1] - self.sq_size/2 ) self.wally.penup() self.wally.setpos(temp[0]-self.sq_size/2, temp[1] - (rightOpen) * self.sq_size - self.sq_size/2 ) self.wally.pendown() self.wally.setpos(temp[0]+self.sq_size/2, temp[1] - (rightOpen) * self.sq_size - self.sq_size/2 ) self.wally.penup() self.wally.setpos(temp[0]-self.sq_size/2, temp[1] + (leftOpen) * self.sq_size + self.sq_size/2 ) self.wally.pendown() self.wally.setpos(temp[0]+self.sq_size/2, temp[1] + (leftOpen) * self.sq_size + self.sq_size/2 ) self.wally.penup() self.wally.goto(temp) for y in range(leftOpen+1): b = str(locationX).zfill(2) + str(locationY + y).zfill(2) + str(locationX).zfill(2) + str(locationY + y + 1).zfill(2) self.allBordersData.pop(b, None) if y == leftOpen and locationY + leftOpen < self.maze_dim-1: self.allWalls[b] = b for y in range(rightOpen+1): b = str(locationX).zfill(2) + str(locationY - y -1).zfill(2) + str(locationX).zfill(2) + str(locationY - y).zfill(2) self.allBordersData.pop(b, None) if y == rightOpen and locationY - rightOpen > 0 : self.allWalls[b] = b for x in range(frontOpen+1): b = str(locationX + x ).zfill(2) + str(locationY).zfill(2) + str(locationX + x + 1).zfill(2) + str(locationY).zfill(2) self.allBordersData.pop(b, None) if x == frontOpen and locationX + frontOpen < self.maze_dim - 1: self.allWalls[b] = b elif self.heading == "down": self.wally.penup() self.wally.setpos(temp[0]-self.sq_size/2, temp[1] - (frontOpen) * self.sq_size - self.sq_size/2 ) self.wally.pendown() self.wally.setpos(temp[0]+self.sq_size/2, temp[1] - (frontOpen) * self.sq_size - self.sq_size/2 ) self.wally.penup() self.wally.goto(temp[0]- (rightOpen) * self.sq_size - self.sq_size/2 , temp[1] + self.sq_size/2 ) self.wally.pendown() self.wally.goto(temp[0]- (rightOpen) * self.sq_size - self.sq_size/2 , temp[1] - self.sq_size/2 ) self.wally.penup() self.wally.goto(temp[0]+ (leftOpen) * self.sq_size + self.sq_size/2 , temp[1] + self.sq_size/2 ) self.wally.pendown() self.wally.goto(temp[0]+ (leftOpen) * self.sq_size + self.sq_size/2 , temp[1] - self.sq_size/2 ) self.wally.penup() self.wally.goto(temp) for x in range(leftOpen+1): b = str(locationX + x).zfill(2) + str(locationY).zfill(2) + str(locationX + x + 1).zfill(2) + str(locationY).zfill(2) self.allBordersData.pop(b, None) if x == leftOpen and locationX + leftOpen < self.maze_dim - 1: self.allWalls[b] = b for x in range(rightOpen+1): b = str(locationX - x -1).zfill(2) + str(locationY).zfill(2) + str(locationX - x).zfill(2) + str(locationY).zfill(2) self.allBordersData.pop(b, None) if x == rightOpen and locationX - rightOpen > 0: self.allWalls[b] = b for y in range(frontOpen+1): b = str(locationX).zfill(2) + str(locationY - y - 1).zfill(2) + str(locationX).zfill(2) + str(locationY - y).zfill(2) self.allBordersData.pop(b, None) if y == frontOpen and locationY - frontOpen > 0 : self.allWalls[b] = b elif self.heading == "left": self.wally.penup() self.wally.goto(temp[0]- (frontOpen) * self.sq_size - self.sq_size/2 , temp[1] + self.sq_size/2 ) self.wally.pendown() self.wally.goto(temp[0]- (frontOpen) * self.sq_size - self.sq_size/2 , temp[1] - self.sq_size/2 ) self.wally.penup() self.wally.setpos(temp[0]-self.sq_size/2, temp[1] + (rightOpen) * self.sq_size + self.sq_size/2 ) self.wally.pendown() self.wally.setpos(temp[0]+self.sq_size/2, temp[1] + (rightOpen) * self.sq_size + self.sq_size/2 ) self.wally.penup() self.wally.setpos(temp[0]-self.sq_size/2, temp[1] - (leftOpen) * self.sq_size - self.sq_size/2 ) self.wally.pendown() self.wally.setpos(temp[0]+self.sq_size/2, temp[1] - (leftOpen) * self.sq_size - self.sq_size/2 ) self.wally.penup() self.wally.goto(temp) for y in range(leftOpen+1): b = str(locationX).zfill(2) + str(locationY - y - 1).zfill(2) + str(locationX).zfill(2) + str(locationY - y).zfill(2) self.allBordersData.pop(b, None) if y == leftOpen and locationY - leftOpen > 0 : self.allWalls[b] = b for y in range(rightOpen+1): b = str(locationX).zfill(2) + str(locationY + y).zfill(2) + str(locationX).zfill(2) + str(locationY +y + 1).zfill(2) self.allBordersData.pop(b, None) if y == rightOpen and locationY + rightOpen < self.maze_dim - 1: self.allWalls[b] = b for x in range(frontOpen+1): b = str(locationX - x - 1).zfill(2) + str(locationY).zfill(2) + str(locationX - x ).zfill(2) + str(locationY).zfill(2) self.allBordersData.pop(b, None) if x == frontOpen and locationX - frontOpen > 0: self.allWalls[b] = b if len(self.allBordersData) == 0: self.discoveryDone = True self.wally.pendown() self.wally.showturtle() self.wally.color("grey") def buildGraph(self): print "BUILD THE SHORTEST PATH NOW ..." for x in range(self.maze_dim): for y in range(self.maze_dim): cellCode = str(x).zfill(2) + str(y).zfill(2) self.cellsGraph[cellCode] = {} for rc in self.findRightCells(cellCode): self.cellsGraph[cellCode][rc] = rc for lc in self.findLeftCells(cellCode): self.cellsGraph[cellCode][lc] = lc for uc in self.findUpCells(cellCode): self.cellsGraph[cellCode][uc] = uc for dc in self.findDownCells(cellCode): self.cellsGraph[cellCode][dc] = dc def findRightCells(self,cellCode): result = [] x = int(cellCode[0:2]) y= int(cellCode[2:4]) c1 = str(x+1).zfill(2) + str(y).zfill(2) c2 = str(x+2).zfill(2) + str(y).zfill(2) c3 = str(x+3).zfill(2) + str(y).zfill(2) b1 = cellCode + c1 b2 = c1 + c2 b3 = c2 + c3 if b1 not in self.allWalls and x<self.maze_dim-1: result.append(c1) if b2 not in self.allWalls and x<self.maze_dim-2: result.append(c2) if b3 not in self.allWalls and x<self.maze_dim-3: result.append(c3) return result def findLeftCells(self,cellCode): result = [] x = int(cellCode[0:2]) y= int(cellCode[2:4]) c1 = str(x-1).zfill(2) + str(y).zfill(2) c2 = str(x-2).zfill(2) + str(y).zfill(2) c3 = str(x-3).zfill(2) + str(y).zfill(2) b1 = c1 + cellCode b2 = c2 + c1 b3 = c3 + c2 if b1 not in self.allWalls and x>0: result.append(c1) if b2 not in self.allWalls and x>1: result.append(c2) if b3 not in self.allWalls and x>2: result.append(c3) return result def findUpCells(self,cellCode): result = [] x = int(cellCode[0:2]) y= int(cellCode[2:4]) c1 = str(x).zfill(2) + str(y+1).zfill(2) c2 = str(x).zfill(2) + str(y+2).zfill(2) c3 = str(x).zfill(2) + str(y+3).zfill(2) b1 = cellCode + c1 b2 = c1 + c2 b3 = c2 + c3 if b1 not in self.allWalls and y<self.maze_dim-1: result.append(c1) if b2 not in self.allWalls and y<self.maze_dim-2: result.append(c2) if b3 not in self.allWalls and y<self.maze_dim-3: result.append(c3) return result def findDownCells(self,cellCode): result = [] x = int(cellCode[0:2]) y= int(cellCode[2:4]) c1 = str(x).zfill(2) + str(y-1).zfill(2) c2 = str(x).zfill(2) + str(y-2).zfill(2) c3 = str(x).zfill(2) + str(y-3).zfill(2) b1 = c1 + cellCode b2 = c2 + c1 b3 = c3 + c2 if b1 not in self.allWalls and y>0: result.append(c1) if b2 not in self.allWalls and y>1: result.append(c2) if b3 not in self.allWalls and y>2: result.append(c3) return result def findShortestPath(self): x1 = self.maze_dim/2 x2 = x1 - 1 center1 = str(x1).zfill(2) + str(x1).zfill(2) center2 = str(x1).zfill(2) + str(x2).zfill(2) center3 = str(x2).zfill(2) + str(x2).zfill(2) center4 = str(x2).zfill(2) + str(x1).zfill(2) centers = [center1,center2,center3,center4] bfsSearchDone = False target = None bfsVisitedCells = {} bfsDistances = {} q = deque([]) for x in self.cellsGraph: bfsVisitedCells[x] = False bfsDistances[x] =10000 q.append('0000') bfsVisitedCells ['0000'] = True bfsDistances ['0000'] = 0 while len(q)>0: if bfsSearchDone ==True: break x = q.popleft() currentDistance = bfsDistances[x] neighbors = self.cellsGraph[x] for n in neighbors: if bfsVisitedCells[n] == False: bfsVisitedCells[n] = True bfsDistances[n] = currentDistance + 1 q.append(n) if n in centers: bfsSearchDone = True target = n break self.shortestPath =[target] currntNode = target while True: if currntNode == '0000': break neighbors = self.cellsGraph[currntNode] for n in neighbors: if bfsDistances[n] == bfsDistances[currntNode] - 1: currntNode = n self.shortestPath.append(currntNode) break self.shortestPath.reverse() #print "GRAPH = " , self.cellsGraph #print "CENTERS = ", center1,center2,center3,center4 #print "VISITED CELLS = ", bfsVisitedCells #print "DISTANCES = ", bfsDistances #print "QUEUE = ", q #print "Target = ", target print "SHORTEST PATH = " , self.shortestPath
f67907a2b696d950b0501b829d52f144ab1fc86d
fdas3213/Leetcode
/540-single-element-in-a-sorted-array/540-single-element-in-a-sorted-array.py
756
3.59375
4
class Solution: def singleNonDuplicate(self, nums: List[int]) -> int: left, right = 0, len(nums)-1 while left<right: mid = left+(right-left)//2 right_even = (right-mid)%2==0 if nums[mid]==nums[mid+1]: if right_even: #after removing nums[mid+1], right side is not even anymore, so should move left pointer to the right of mid+1 left = mid +2 else: right = mid -1 elif nums[mid]==nums[mid-1]: if right_even: right = mid-2 else: left = mid+1 else: return nums[mid] return nums[left]
15120915bb131571dfa7186d017d8f9c78587e20
Camomilaa/Python-Curso-em-Video
/ex025.py
115
3.59375
4
nome = str(input('Digite seu nome completo: ')).strip() print('Seu nome possui silva: {}'.format(' Silva' in nome))
ae0a4ed4d5dc90f4ce82758977ba43375d4e32a7
adamelid/PythonVerk
/Assignment13/pullingLeversForCoins.py
3,696
4.0625
4
#Algorithm is as follows: #While not at final tile. #----Show possible directions. #----Player chooses direction. #----Check if direction is valid. #----Move to chosen tile if valid. #Print victory result. #Set static variables. # - x, y, walls(west, north, east, south), lever. Tile1 = 1,1,1,0,1,1,0 Tile2 = 2,1,1,0,1,1,0 Tile3 = 3,1,1,0,1,1,0 Tile4 = 1,2,1,0,0,0,1 Tile5 = 2,2,0,1,1,0,1 Tile6 = 3,2,1,0,1,0,1 Tile7 = 1,3,1,1,0,0,0 Tile8 = 2,3,0,1,0,1,1 Tile9 = 3,3,0,1,1,0,0 currentTile = Tile1 x = currentTile[0] y = currentTile[1] hasNotRun = True totalCoins = 0 def pull_lever(totalCoins): leverChoice = input("Pull a lever (y/n): ").lower() if leverChoice == "y": totalCoins += 1 print("You received 1 coins, your total is now " + str(totalCoins) + ".") return totalCoins #Finds out which directions player can choose from. def possible_directions(currentTile,hasNotRun): #Set variables that need to be reset every call. howManyDirections = 0 travelPossibilities = "" #If there are no walls, add that direction to possible directions. if hasNotRun: if not currentTile[3]: travelPossibilities += "(N)orth" howManyDirections += 1 if not currentTile[4]: if howManyDirections > 0: travelPossibilities += " or (E)ast" else: travelPossibilities += "(E)ast" howManyDirections += 1 if not currentTile[5]: if howManyDirections > 0: travelPossibilities += " or (S)outh" else: travelPossibilities += "(S)outh" howManyDirections += 1 if not currentTile[2]: if howManyDirections > 0: travelPossibilities += " or (W)est" else: travelPossibilities += "(W)est" howManyDirections += 1 #Print out travel options. print("You can travel: " + travelPossibilities + ".") hasNotRun = False return hasNotRun #Checks if direction is choosable def check_if_choosable(hasNotRun,direction,currentTile,x,y): if direction.lower() == "n" and currentTile[3] == False: y += 1 hasNotRun = True elif direction.lower() == "e" and currentTile[4] == False: x += 1 hasNotRun = True elif direction.lower() == "s" and currentTile[5] == False: y -= 1 hasNotRun = True elif direction.lower() == "w" and currentTile[2] == False: x -= 1 hasNotRun = True else: print("Not a valid direction!") return hasNotRun,x,y #Moves player to next tile. def move_player(x,y,currentTile): if x == 1 and y == 1: currentTile = Tile1 elif x == 2 and y == 1: currentTile = Tile2 elif x == 3 and y == 1: currentTile = Tile3 elif x == 1 and y == 2: currentTile = Tile4 elif x == 2 and y == 2: currentTile = Tile5 elif x == 3 and y == 2: currentTile = Tile6 elif x == 1 and y == 3: currentTile = Tile7 elif x == 2 and y == 3: currentTile = Tile8 elif x == 3 and y == 3: currentTile = Tile9 return currentTile #While loop which contains the program (While not at victory x,y coordinates). while x != 3 or y != 1: leverActive = currentTile[6] if leverActive: totalCoins = pull_lever(totalCoins) hasNotRun = possible_directions(currentTile,hasNotRun) direction = input("Direction: ") hasNotRun,x,y = check_if_choosable(hasNotRun,direction,currentTile,x,y) currentTile = move_player(x,y,currentTile) #Print result when at tile x == 3 and y == 1 (Tile3) print("Victory!")
e5269fae32ae2a37d62205ebe8e1deb691f4caf3
fatmasener/CreativeHubYazilim
/Python Dersleri/Ders-8/menu.py
1,317
3.734375
4
class MenuItem: # Menudeki her bir icecegi modeller def __init__(self,isim,su,sut,kahve,maliyet): self.isim = isim self.maliyet = maliyet self.icerikler = { "su": su, "süt": sut, "kahve":kahve } class Menu: """Iceceklerle Menuyu modeller.""" def __init__(self): self.menu = [ MenuItem(isim="latte", su=200, sut=150, kahve=24, maliyet=2.5), MenuItem(isim="espresso", su=50, sut=0, kahve=18, maliyet=1.5), MenuItem(isim="cappuccino", su=250, sut=50, kahve=24, maliyet=3) ] def get_icecekler(self): """Menudeki tum iceceklerin isimlerini donderir""" secenekler = "" for item in self.menu: secenekler += f"{item.isim}/" return secenekler def icecegi_bul(self, siparis_ismi): """Menude siparis verilen icecegin ismini arar. O icecek varsa donderir, yoksa herhangi bir sey dondermez""" for item in self.menu: if item.isim == siparis_ismi: return item print("Girdiginiz icecek mevcut degil") def icecek_ekle(self, isim,su,sut,kahve,maliyet): icecek = MenuItem(isim,su,sut,kahve,maliyet) self.menu.append(icecek)
c2ba09d9312d4c1e2371dd787e405e1fdb61547b
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_158/671.py
552
3.5
4
def solve(X, R, C): ans = solve_(X, R, C) return "GABRIEL" if ans else "RICHARD" def solve_(X, R, C): if X == 1: return True if X == 2: return R % 2 == 0 or C % 2 == 0 if X == 3: return (R, C) in ((2, 3), (3, 2), (3, 3), (3, 4), (4, 3)) if X == 4: return (R, C) in ((3, 4), (4, 3), (4, 4)) return False if __name__ == '__main__': T = int(input()) for case in range(1, T+1): X, R, C = (int(i) for i in input().split()) print("Case #%d: %s" % (case, solve(X, R, C)))
17422917dcff0d4b3a54bd78e50ab07ccccafd29
Rookie-cprime/CS_learn
/class_1/part_2/homework/homework/prc_4.py
1,016
3.8125
4
def monthday(balance,annualInterestRate,minimum_money,day = 0): balance -= minimum_money if(balance<=0 or day>12): return day else: return monthday(balance+balance*(annualInterestRate/12),annualInterestRate,minimum_money,day+1) def paying_debt(balance,annualInterestRate): BOL = True t = 1 while BOL: minimum_money = t*10 s = monthday(balance,annualInterestRate,minimum_money) if s<12: BOL = False t+=1 print('Lowest payment: '+ str(minimum_money)) def paying_debt_2(balance,annualInterestRate): BOL = True min = balance/12 max = balance*((1+annualInterestRate/12)**12)/12 while BOL: s = monthday(balance,annualInterestRate,(min+max)/2) if s == 11: BOL = False minimum_money = (min+max)/2 elif s>11: min = (min+max)/2 else: max = (min+max)/2 print('Lowest payment: '+ str(round(minimum_money,2))) paying_debt_2(999999,0.18)
a3d91aa435bc7102e92bc1184e620b56b97cc440
iccowan/CSC_117
/exam_1_practice/number_2.py
527
4.34375
4
# Exam 1 Practice # Question Number 2 # Biking Mileage # Initialize variables new_day = float(input('How many miles did you ride on day 1? ')) total_miles = 0 day = 1 # Runs a loop until the user doesn't input anything while new_day != '': new_day = float(new_day) if new_day >= 0: total_miles += new_day day += 1 new_day = input('How many miles did you ride on day ' + str(day) + '? (Leave blank to end) ') # Returns the total number of miles print('You rode a total of', total_miles, 'miles!')
1dcfa3e6201696a56abcfa423a413128bd8216b7
mustbepro/toggl-api
/togglin.py
5,201
3.765625
4
#!/usr/bin/python3 from random import randint import calendar from collections import defaultdict array = [1, 2 ,3 ,4, 5] week = [] #for i in array: # week.append(randint(4,7)) total_time = 20 count = 0 #while (count < total_time): # entry = randint(4,7) # # if((entry + count) < total_time): # week.append(entry) # count += entry # # elif((count + 4) >= total_time): # week.append((total_time - count)) # break def populate_hours(total_time=None): if total_time != None: count = 0 week = [] while count < total_time: entry = randint(4,7) if (entry + count) < total_time: week.append(entry) count += entry elif (count + 4) >= total_time: week.append(total_time - count) break if len(week) < 5: week.append(0) return week #x = populate_hours(20) #print (x) def populate_days(name=None, task_num=None, total_time=None): output = {} #output = [] #task_name = name output['task_name'] = name #test_name = name hours = populate_hours(total_time) count = 0 output[task_num] = hours # for item in hours: # count += 1 # output[count] = item #output['hours'] = hours #mylist.append(output) return output # task_list = [] task_list.append(populate_days("task_1", 1, 20)) task_list.append(populate_days("task_2", 2, 20)) #y = len(x) print (task_list) tyd = [{'task': '1', 'hour': '[1, 2, 7]'}, {'task': '2', 'hour': '[3, 4, 0]'}] entry = [{'task_1': '1', 'task_2': '2', 'task_3': '7'}] for item in tyd: print (item) #print ("dict len: ", y) #array_len = len(x) count = 0 #all_hours = [{1: [1, 2, 7]}, {2: [3, 4, 0]}, {3: [5, 6, 0]}] all_hours = [[1, 2, 7], [3, 4, 0], [5, 6, 0]] #def gen_hour_entries(all_hours=[]) count = 0 all_hours_len = len(all_hours) day_hours = 8 day_limit = 0 day_count = 1 #entries = defaultdict(list) entries = {} list_entries = [] while True: for item in all_hours: array_len = len(item)-1 if item[count] != 0: if (day_limit + item[count]) <= day_hours: day_limit += item[count] entries[day_count].append(item[count]) #entries['task'].append(day_count) #print ("day count: {} hour: {}".format(day_count, item[count])) elif (day_limit + item[count]) > day_hours: remainder = day_hours - day_limit carry_over = item[count] - remainder entries[day_count] = remainder #print ("day count: {} hour: {}".format(day_count, remainder)) day_count += 1 day_limit = carry_over #print ("day count: {} hour: {}".format(day_count, carry_over)) entries[day_count] = carry_over list_entries.append(entries) count += 1 if count > array_len: break print ("entries: ", list_entries) # -- backup code ------------------------------------------------------------------ #while True: # for item in all_hours: # array_len = len(item)-1 # if item[count] != 0: # if (day_limit + item[count]) <= day_hours: # day_limit += item[count] # entries[day_count].append([item[count]]) # #entries['task'].append(day_count) # #print ("day count: {} hour: {}".format(day_count, item[count])) # elif (day_limit + item[count]) > day_hours: # remainder = day_hours - day_limit # carry_over = item[count] - remainder # entries[day_count].append([remainder]) # #print ("day count: {} hour: {}".format(day_count, remainder)) # day_count += 1 # day_limit = carry_over # #print ("day count: {} hour: {}".format(day_count, carry_over)) # entries[day_count].append([carry_over]) # count += 1 # if count > array_len: # break #print ("entries: ", entries) # ^- backup code ------------------------------------------------------------------ #2013-03-05T07:00:00.000Z #def date_list(start_month=None, start_day=None, end_month=None, end_day=None): def date_list(start_date=[], end_date=[]): start_year = start_date[0] start_month = start_date[1] start_day = start_date[2] end_year = end_date[0] end_month = end_date[1] end_day = end_date[2] day_start = 9 day_end = 5 if start_month == end_month: for item in range(start_day, end_day+1): dow = calendar.weekday(start_year, start_month, item) if dow in range(0, 5): #print ("This is a week day: ", dow) print ("{}-{}-{}T".format(start_year, start_month, item)) else: #print ("This is NOT a week day: ", dow) print () date_list([2017, 12, 15], [2017, 12, 20])
1391a0b1711c6302fe4fbec23bab5654bd1f4ada
Marciom99/DNA-Sequence-Analysis
/Option2.py
4,722
3.734375
4
from sys import exit import Interface, Modulos def exercicio2(): escolha = str(input(f""" 2 {'*'*20} \ta. Inserir uma sequência \tb. Remover uma sequência \tc. Mostrar o número de ocorrências de uma determinada base ou sub-sequência e uma lista dos respetivos índices, em cada uma das sequências \td. Mostrar as frequências de um determinado conjunto de bases ou sub-sequências (número total e relativo(%) de cada base), em cada uma das sequências \te. Mostrar as sequências complementares \tf. Voltar ao Menu anterior \tg. Sair do Programa {'*'*20}\n """)) if escolha.lower() == 'a': return exercicio2A() elif escolha.lower() == 'b': return exercicio2B() elif escolha.lower() == 'c': return exercicio2C() elif escolha.lower() == 'd': return exercicio2D() elif escolha.lower() == 'e': return exercicio2E() elif escolha.lower() == 'f': return Interface.interface() elif escolha.lower() == 'g': exit() else: print('Opção invalida') return exercicio2() def exercicio2A(): escolha = str(input('''Quer introduzir uma sequência 1 - Manual 2 - Aleatória ''')) if escolha =='1': seq = Modulos.CriarSeq(1) elif escolha =='2': seq = Modulos.CriarSeq(2) else: print('Escolheu uma opção inválida') return exercicio2() if len(Interface.List.ListaSeq)>0: Modulos.Contagem() while True: try: opcao = int(input('Escolha um indice válido:')) Interface.List.ListaSeq.insert(opcao,seq) return exercicio2() except ValueError: print('Indice inválido, escolha um indice valido') else: print('A lista ainda não tem elementos.') Interface.List.ListaSeq.insert(0,seq) return exercicio2() def exercicio2B(): if len(Interface.List.ListaSeq)<0: print('Não existem sequências') return exercicio2() Modulos.Contagem() while True: try: opcao = int(input('Escolha um indice válido para remover uma sequencia:')) del(Interface.List.ListaSeq[opcao]) return exercicio2() except (ValueError,IndexError): print('Indice inválido, escolha um indice valido') def exercicio2C(): ver = Modulos.Verlista() if ver == False: return exercicio2() localizar = str(input('Digite uma base ou uma subsequencia que seja procurada:')).upper() for ints,seq in enumerate(Interface.List.ListaSeq): listaIndice = list() ocorrencias = 0 for i,v in enumerate(seq): a = i trace = "" try: while len(trace)-1 <len(localizar)-1: trace+=seq[a] a+=1 if localizar == trace: listaIndice.append(i) ocorrencias+=1 except IndexError: print("pelo except") print(ints) print(listaIndice) print(ocorrencias) return exercicio2() def exercicio2D(): ver = Modulos.Verlista() if ver == False: return exercicio2() localizar = str(input('Digite uma base ou uma subsequencia que seja procurada:')).upper() for ind,seq in enumerate(Interface.List.ListaSeq): ocorrencias = seq.count(localizar) print(f'Numero total {ocorrencias}') print(f'Para o indice {ind} a percentagem relativa é {((len(localizar)*ocorrencias) / len(seq)) * 100:.2f}%') return exercicio2() def exercicio2E(): ver = Modulos.Verlista() if ver == False: return exercicio2() for ind,seq in enumerate(Interface.List.ListaSeq): complementar = '' print(f'Para o indice {ind} temos o complementar ', end='') for nuc in seq: if nuc =='A': complementar+='T' elif nuc == 'T': complementar += 'A' elif nuc == 'G': complementar += 'C' elif nuc =='C': complementar += 'G' else: complementar+='-' print(complementar) return exercicio2()
f6ef79c9ff1626b30d593a88f3297d98c1079b79
FrederikWilmotte/adventofcode2019
/Advent8p2.py
1,560
3.53125
4
# Advent8 - Part2 # Day 8: Space Image Format def printLayer(layer,wide): layer = makeLayerReadable(layer) startlayer = 0 stoplayer = wide while startlayer + wide <= len(layer): print(layer[startlayer:stoplayer]) startlayer = startlayer + wide stoplayer = stoplayer + wide def makeLayerReadable (layer): layerReadable = "" for c in layer: if c == "1": layerReadable = layerReadable + "X" elif c == "0": layerReadable = layerReadable + " " else: layerReadable = layerReadable + "." return layerReadable def makeLayer(image,layerNr,wide,tall): laatste = "nee" startlayer = (layerNr-1) * wide * tall stoplayer = layerNr * wide * tall if stoplayer + 1 > len(image): laatste = "ja" layer = image[startlayer:stoplayer] return (layer,laatste) def compareLayer(layerBoven,layerOnder): layer = "" v = 0 for c1 in layerBoven: c2 = layerOnder[v] if c1 == "0" or c1 == "1": c3 = c1 else: c3 = c2 layer = layer + c3 v = v + 1 return layer bestand = open("Day8image.txt","r") for imageinput in bestand: image = imageinput layerNr = 1 (layer,laatste) = makeLayer(image,layerNr,25,6) while laatste == "nee": layerBoven = layer layerNr = layerNr + 1 (layerOnder,laatste) = makeLayer(image,layerNr,25,6) layer = compareLayer(layerBoven,layerOnder) printLayer(layer,25)
6c9797b0658dbf0edb0a0f5a0d244906e666e449
sranjani47/LetsUpgrade-AI-ML
/files/solution/day5/d5.py
1,888
4.3125
4
#!/usr/bin/env python # coding: utf-8 Q1. Write a Python program to find the first 20 non-even prime natural numbers. # In[1]: def check_prime(input_number): if input_number > 1: for i in range(2, input_number): if (input_number % i) == 0: res = "No" break else: res = "Yes" else: res = "No" return res listVar = [] v = "" lst1 = list(range(3,100,2)) for i in lst1: if len(listVar) < 20: v = check_prime(i) if(v == "Yes"): listVar.append(i) print(listVar) Q2. Write a Python program to implement 15 functions of string # In[2]: strVal = "Lets Upgrade" print(strVal.capitalize()) print(strVal.casefold()) print(strVal.isalnum()) print(strVal.count("e")) print(strVal.index("p")) print(strVal.encode()) print(strVal.isalpha()) print(strVal.isdigit()) print(strVal.isspace()) print(strVal.islower()) print(strVal.split(" ")) print(strVal.replace("g","h")) print(strVal.swapcase()) print(strVal.lower()) print(strVal.isupper()) Q3. Write a Python program to check if the given string is a Palindrome or Anagram or None of them. Display the message accordingly to the user. # In[4]: str1 = str(input("Enter the word - ")) str2 = str(input("Enter the second word - ")) if(str1 == str1[::-1] ): print("Its palindrome") elif(sorted(str1)== sorted(str2)): print("Its anagrams.") else: print("None of them") Q4. Write a Python's user defined function that removes all the additional characters from the string and converts it finally to lower case using built-in lower(). eg: If the string is "Dr. Darshan Ingle @AI-ML Trainer", then the output be "drdarshaningleaimltrainer" # In[5]: str1 = str(input("Enter the word - ")) resultVal = "" for character in str1: if character.isalnum(): resultVal += character.lower() print(resultVal)
02d7bb4a5f9f5fb5177a5eb083a1299e44e2229e
ArthurErn/lista_python
/Lista02Ex14.py
530
3.828125
4
aluno = input("Digite o número de identificação do aluno\n") ME = int(input("Informe a média nos exercícios do aluno \n")) nota1 = int(input("Informe a primeira nota da prova \n")) nota2 = int(input("Informe a segunda nota da prova \n")) nota3 = int(input("Informe a terceira nota da prova \n")) if nota1 < 0 or nota2 < 0 or nota3 < 0 or ME < 0: print("Por favor, informe as notas corretamente") else: MA = (nota1 + nota2 * 2 + nota3 * 3 + ME) / 7 print(f"A média do aluno de código {aluno} é {round(MA, 2)}")
251ac6134ca3a9513b2566c1e620217bf33143c7
tathagatoroy/Automata-Theory
/q4/Q4.py
8,190
3.765625
4
''' code to minimize dfa ''' import json import sys ''' function to print dfa optimally ''' def print_dfa(dfa): print("states : ") for i in dfa['states'] : print(i) print("transition :") for s in dfa['transition_function'] : print("old state : {0} , input : {1} and next state : {2}".format(s[0],s[1],s[2])) print("Alphabet") for l in dfa['letters']: print(l) print("Initial_state") for s in dfa['start_states']: print(s) print("final_state") for s in dfa['final_states']: print(s) ''' loads to the dfa from file ''' def load_input(infile): f = open(infile) dfa = json.load(f) f.close() #print_dfa(dfa) return dfa ''' function to remove unreachable states:''' def unreachable(dfa,graph): reachable = dfa['start_states'] new_states = dfa['start_states'] while(True): temp = [] for s in new_states: #check if s leads to new states for l in dfa['letters']: var = graph[s][l] already_reachable = 0 #check if var is already there for r in temp: if(r == var): already_reachable = 1 break if(already_reachable == 0): temp.append(var) temp_new = [] #check s is not in reachable already for s in temp: is_there = 0 for r in reachable: if(s == r): is_there = 1 if(is_there == 0): temp_new.append(s) new_states = temp_new reachable = reachable + new_states if(len(new_states) == 0): break not_reachable = [] for s in dfa['states']: non_reachable = 1 for r in reachable: if(s == r): non_reachable = 0 if(non_reachable == 1): not_reachable.append(s) #print("REACHABLE = {0}".format(reachable)) #print("NON_REACHABLE = {0}".format(not_reachable)) dfa['states'] = reachable is_reachable = {} for s in reachable: is_reachable[s] = 1 for s in not_reachable: is_reachable[s] = 0 non_delete_states = [] for f in dfa['final_states']: if(is_reachable[f] == 1): non_delete_states.append(f) dfa['final_states'] = non_delete_states #print("FINAL = {0}".format(non_delete_states)) #print(is_reachable) remaining_transition = [] for l in dfa['transition_function']: if(is_reachable[l[0]] == 1 and is_reachable[l[2]] == 1): remaining_transition.append(l) #print("TRANSITION = {0}".format(remaining_transition)) dfa['transition_function'] = remaining_transition #print_dfa(dfa) return dfa ''' minimizes the dfa using partitioning ''' def partition(dfa,outfile): #print("Calling Partition") #create graph graph = {} for s in dfa['states']: graph[s] = {} for l in dfa['letters'] : graph[s][l] = "" for l in dfa['transition_function']: f = l[0] letter = l[1] to = l[2] graph[f][letter] = to #print("Calling ") dfa = unreachable(dfa,graph) #print_dfa(dfa) #print("RETURNED") state_identity = {} for s in dfa['states']: state_identity[s] = 0 for s in dfa['final_states']: state_identity[s] = 1 size = len(dfa['states']) #print(state_identity) while(True): size -= 1 #if(size < - 2): # break isThereAnyPartition = 0 identities = [] temp = [] for s in state_identity: temp.append(state_identity[s]) for i in temp : if i not in identities: identities.append(i) #print(size) #print("identities : {0}".format(identities)) #print("haha") val = 0 new_state_identities = {} for s in dfa['states'] : new_state_identities[s] = -1 #print(size) #print("naha") #print(new_state_identities) #print_dfa(dfa) for r in identities: #print("") #print("state identity with id {0}".format(r)) current_state = [] for s in dfa['states']: if(state_identity[s] == r): current_state.append(s) #print("Current_State = {0}".format(current_state)) diction = {} for state1 in current_state: diction[state1] = {} for state2 in current_state: diction[state1][state2] = 0 for s1 in current_state: for s2 in current_state: same_partition = 1 if(s1 == s2): diction[s1][s2] = 1 diction[s2][s1] = 1 else: #print("CHECKING WHETHER {0} and {1} are equivalent".format(s1,s2)) for l in dfa['letters']: #print("FOR letter {0} : State : {1} to {2} and state : {3} to {4} ".format(l,s1,graph[s1][l],s2,graph[s2][l])) if(state_identity[graph[s1][l]] != state_identity[graph[s2][l]]): same_partition = 0 isThereAnyPartition = 1 #print("FOR letter {0} : State : {1} to {2} and state : {3} to {4} ".format(l,s1,graph[s1][l],s2,graph[s2][l])) if(same_partition == 1): #print("{0} and {1} are equivalent".format(s1,s2)) diction[s1][s2] = 1 diction[s2][s1] = 1 else: #print("{0} and {1} are not equivalent".format(s1,s2)) diction[s1][s2] = 0 diction[s2][s1] = 0 for s3 in current_state: if(new_state_identities[s3] == -1): new_state_identities[s3] = val for rr in diction[s3]: if(diction[s3][rr] == 1): new_state_identities[rr] = val val += 1 for s in state_identity: state_identity[s] = new_state_identities[s] if(isThereAnyPartition == 0): break #print(state_identity) max_val = 0 for r in state_identity: if(max_val <= state_identity[r]): max_val = state_identity[r] list_of_states = [] reverse_hash = {} for z in range(max_val + 1): current_state = [] for s in dfa['states']: if(state_identity[s] == z): current_state.append(s) list_of_states.append(current_state) reverse_hash[z] = current_state #print("LIST") #for r in list_of_states: #print(r) transition = [] for r in list_of_states: for l in dfa['letters']: #print(r) #print(l) #print(graph[r[0]][l]) #print("") iden = state_identity[graph[r[0]][l]] to = reverse_hash[iden] transition.append([r,l,to]) temp1 = [] for s in dfa['final_states']: temp1.append(state_identity[s]) new_final = [] for i in temp1: if reverse_hash[i] not in new_final: new_final.append(reverse_hash[i]) temp2 = [] new_start = [] for s in dfa['start_states']: temp2.append(state_identity[s]) for i in temp2: if reverse_hash[i] not in new_start: new_start.append(reverse_hash[i]) #print(new_start,new_final) dfa['start_states'] = new_start dfa['final_states'] = new_final dfa['states'] = list_of_states dfa['transition_function'] = transition # print_dfa(dfa) g = open(outfile,"w") json.dump(dfa,g,indent=4) partition(load_input(sys.argv[1]),sys.argv[2])
2899e955f821a7b6178474e968e5d4b55a65a820
woowei0102/code2pro
/data/clean_data/A2/27.py
113
3.78125
4
def factorial (n): temp=1 for i in range (1,n+1): temp *= i return temp print(factorial(10))
66e70d6da3c1aeca7585356fbd3b75c27781de51
teodornedevski/openCVvisualCode
/test1/test1/turtleDrawing.py
1,436
4.09375
4
import turtle turtle.color('red', 'yellow') turtle.begin_fill() def Draw (elements[]): for i in elements.length() : if elements[i] == "circle": turtle.left(20) if elements [i+1] == "up": turtle.forward(10) elif elements [i+1] == "back": turtle.back(10) elif elements [i+1] == "left": turtle.left(10) else: turtle.right(10) elif elements[i] == "triangle": turtle.speed(300) if elements [i+1] == "up": turtle.forward(10) elif elements [i+1] == "back": turtle.back(10) elif elements [i+1] == "left": turtle.left(10) else: turtle.right(10) elif elements[i] == "square": turtle.tilt(30) if elements [i+1] == "up": turtle.forward(10) elif elements [i+1] == "back": turtle.back(10) elif elements [i+1] == "left": turtle.left(10) else: turtle.right(10) else: if elements [i+1] == "up": turtle.forward(10) elif elements [i+1] == "back": turtle.back(10) elif elements [i+1] == "left": turtle.left(10) else: turtle.right(10)
5698c967e99e2dda8c274dccf4c0408cfc37a11a
SMHari/Python-problems
/Module 4/11_rand_array.py
574
3.75
4
import numpy as np if __name__ == '__main__': np_rand_arr = np.random.randint(1, 1000, size=(3, 3)) # sorting by 1st column sort_column1 = np_rand_arr[np_rand_arr[:, 0].argsort()] # sorting by 2nd column sort_column2 = np_rand_arr[np_rand_arr[:, 1].argsort()] # sorting by 3rd column sort_column3 = np_rand_arr[np_rand_arr[:, 2].argsort()] print("Original array:\n", np_rand_arr) print("Sorted by first column:\n", sort_column1) print("Sorted by Second column:\n", sort_column2) print("Sorted by third column:\n", sort_column3)
22dac0a644bdfe6b0e757d863c1fc0bb1ecd9682
mkarp94/ice_project_files
/ICE 0.0/Purchase_Class.py
2,439
3.703125
4
#implementation of a purchase for the purposes of evaluating categories of rewards class purchase(object): def __init__(self, tag = None, unit_price = None, quantity = 0, company = None, product_description = None): self.tag = tag self.unit_price = unit_price self.quantity = quantity self.producer_company = company self.product_description = product_description self.purchase_id = None def get_tag(self): return self.tag def update_tag(self, updated_tag): self.tag = updated_tag def get_unit_price(self): return self.unit_price def update_unit_price(self, updated_unit_price): self.unit_price = updated_unit_price def get_quantity(self): return self.quantity def update_quantity(self, new_quantity): self.quantity = new_quantity def get_producer_company(self): return self.producer_company def update_producer_company(self, updated_producer_company): self.producer_company = updated_producer_company def get_product_description (self): return self.product_description def update_product_description (self, new_product_description ): self.product_description = new_product_description def get_purchase_price(self): return self.unit_price*1.*self.quantity def get_purchase_info(self): print print "This product is made by " + self.producer_company print "It has been labeled under the rewards category of " + self.tag print "Its possible to get a discount wether your card's rewards are determined by the its product tag or the specific company" print "This purchase includes " + str(self.quantity) + " " + self.product_description print "The purchase price is " + str(round(self.get_purchase_price(), 2)) print ''' Apple_Ipad = purchase("consumer electronics", 499.00, 1, "apple", "top rated tablet computer") print 2*Apple_Ipad.get_purchase_price() print Apple_Ipad.get_purchase_info() Google_Nexus = purchase(Apple_Ipad.get_tag(),Apple_Ipad.get_unit_price(),Apple_Ipad.get_quantity(),Apple_Ipad.get_producer_company(),Apple_Ipad.get_product_description()) Google_Nexus.update_producer_company("Google") Google_Nexus.update_unit_price(399.00) print Google_Nexus.get_purchase_info() print Apple_Ipad.get_purchase_info() '''
a5ada341354f7128df71f4d2269c0fc851a5cbc1
nmarun/LearningPython
/16FunctionBasics.py
199
3.546875
4
# Function basics # arguments are type-insensitive # allows for polymorphism def times(x, y): return x*y times(3, 4) # shows 12 times('a', 3) # shows 'aaa' times([1, 2], 2) # shows [1, 2, 1, 2]
2e3faee059571c559cde8500f30cdaf01e9944fc
vapoorva/LetsUpgradeDataScience
/Day 2/Q1.py
115
3.921875
4
list=[] for i in range(0,10): n= int(input("Enter number:")) if n%2==0: list.append(n) print(list)
1a01f9c449e61d3386243cff4ec7834ffa0cf719
odys-z/hello
/challenge/leet/medium/q377.py
2,135
3.8125
4
''' 377. Combination Sum IV https://leetcode.com/problems/combination-sum-iv/ Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. Example: nums = [1, 2, 3] target = 4 The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. Therefore the output is 7. ''' from unittest import TestCase from typing import List class SolutionDebug: def combinationSum4(self, nums: List[int], target: int) -> int: def sumto(T): # dp[T].append([T]) for n in nums: if T < n: break if not du[T - n]: sumto(T - n) du[T - n] = True for combo in dp[T - n]: dp[T].append(combo + [n]) dp = [list() for _ in range(target + 1)] dp[0].append([]) du = [False] * (target + 1) du[0] = True nums.sort() sumto(target) # print(dp[-1]) return len(dp[-1]) class Solution: ''' 87.69% ''' def combinationSum4(self, nums: List[int], target: int) -> int: def sumto(T): for n in nums: if T < n: break if not du[T - n]: sumto(T - n) du[T - n] = True dp[T] += dp[T - n] dp = [0] * (target + 1) dp[0] = 1 du = [False] * (target + 1) du[0] = True nums.sort() sumto(target) # print(dp) return dp[-1] if __name__ == '__main__': t = TestCase() s = Solution() t.assertEqual(7, s.combinationSum4([1, 2, 3], 4)) t.assertEqual(31, s.combinationSum4([4,2,1], 7)) t.assertEqual(700647, s.combinationSum4([1,5,7,14,3,11], 30)) t.assertEqual(12950466, s.combinationSum4([4,2,1], 30)) t.assertEqual(39882198, s.combinationSum4([4,2,1], 32)) print('OK!')
930299807e2b082e365f41392de09a65d2469625
UNSC1419/TestPy
/ah_28_字符串的查找和替换.py
1,026
4.4375
4
temp_str = "hello 123123123 world" # 1. 判断是否以指定的字符串开始 print(temp_str.startswith("hello")) # 2. 判断是否以指定的字符串结束 print(temp_str.endswith("world")) # 3. 查找指定字符串,返回该字符串的索引位置,不存在则返回-1 # index同样可以查找,但是不存在会报错 print(temp_str.find("llo")) print(temp_str.find("ABC")) # 通过参数来指定查找范围0开始到整个字符串长度间 print(temp_str.find("world", 0, len(temp_str))) # rfind 从右侧开始查找 print(temp_str.rfind("llo")) # index 和find一样但是找不到会报错 0开始到整个字符串长度间 print(temp_str.index("world", 0, len(temp_str))) # rindex 和rfind一样 找不到会报错 print(temp_str.rindex("world", 0, len(temp_str))) # 4. 替换字符串,记得更新变量,replace执行会返回新字符串,但不会修改原来的变量 print(temp_str.replace("world", "世界")) print(temp_str) temp_str = temp_str.replace("world", "世界") print(temp_str)
f077c91328d9fefac19322ce9181e41ab76bce67
Harjacober/LeetCodeSolvedProblems
/Bitwise AND of Number Range.py
424
3.578125
4
from math import log,floor # This algorithm is not correct def bitwise(m,n): diff = n-m binary = list(bin(m)[2::]) for j in range(len(binary)): if binary[j]=="1": a = len(binary)-1-j factor = 2**a d = diff-(diff//factor)*factor if diff+d>factor: binary[j]="0" return int("".join(binary),2)&n print(bitwise(163524,163526))
acb901f2f52aec5a7b0745747e7d61e628b4c61d
victor01001000/math_gen
/math_algorithms/math_lib/Polynomial.py
3,227
4.4375
4
#!/usr/bin/env python3 import random class Polynomial(): """ Description: A polynomial is described as a list of monomials. The initializer's default parameter is an empty list of monomials; however, it it has defualt parameters to generating a random equation. """ def __init__(self, terms_list=list()): self.equation = terms_list if len(self.equation) is 0: self.equation = list() # Default parameters for a random equation min_terms = 1 max_terms = 5 min_const = 1 max_const = 10 min_deg = 1 max_deg = 7 self.equation = self.generate_random_equation(min_terms, max_terms, min_const, max_const, min_deg, max_deg) def __repr__(self): return self.get_equation() """ Description: Generates a random polynomial equation based on the parameters given. Parameters: -length of equation is a random number between min_terms and max_terms. -parameters for constants-- min_const and max_const-- have to be positive. -parameters for degree can be negative or positive. -equation is one type of variable letter. Returns: void """ def generate_random_equation(self, min_terms, max_terms, min_const, max_const, min_deg, max_deg, letter): new_equation = list() signs = ['+', '-'] for i in range(random.randint(min_terms, max_terms)): new_equation.append( { 'sign': signs[random.randint(0, 1)], 'constant': random.randint(min_const, max_const), 'variable': letter, 'exponent': random.randint(min_deg, max_deg), } ) self.terms_list = new_equation """ Description: Generates and returns the first derivative of the equation. Parameters: none Returns: A list of dictionaries that define a monomial. """ def get_derivative(self): function = self.equation function_prime = [] for i in range(len(function)): function_prime.append( { 'sign': function[i]['sign'], 'constant': function[i]['constant'] * function[i]['exponent'], 'exponent': function[i]['exponent'] - 1, 'variable': function[i]['variable'] } ) return function_prime """ Description: Constructs a string that represents the equation based on the terms inside self.equation list. Parameters: None Returns: The equation constructed in a string. """ def get_equation(self): equation = '' for i in range(len(self.equation)): gx = self.equation[i] if (gx['sign'] is '+') and (i == 0): equation += str(gx['constant']) + gx['variable'] + '^' + str(gx['exponent']) else: equation += gx['sign'] + str(gx['constant']) + gx['variable'] + '^' + str(gx['exponent']) return equation
0a1d89fcdfde41c3912ad565620a2fdccb886e37
JuanmaLambre/TpDataMasters
/Pruebas/Perceptron/perceptronMulti.py~
4,416
3.515625
4
# # ACLARACION: En realidad aca no estoy haciendo Perceptron, simplemente estoy # categorizando con la recta y=x a fin de simplificar las cosas. # # A diferencia de perceptron.py este codigo grafica # (cant_reviews_pos; cant_revies_neg) por cada par de palabra que exista # IMPORTANTE: A difrenecia de perceptron simple (con una palabra), aca no hay # un archivo con todos los puntajes de cada palabra. Esto lo creamos nosotros # con el archivo de entrenamiento mismo. # import cleanText as ct import multiShingles import removeStopwords as rm import matplotlib.pyplot as plt import sys print "----------" # # MAIN: # puntajes = {} labeled = open("../labeledTrainData.tsv", 'r') labeled.readline() # Obtengo una lista de tuplas ([shingles], sentiment), una por cada review MULTI = 2 # PARAMETRO print "MULTI =", MULTI reviewsProcesadas = [] MAX_ITERACIONES = 20000.0 iteracion = 0.0 line = labeled.readline() print "ENTRENANDO..." while line and iteracion < MAX_ITERACIONES: reviewVec = line.split('\t') rawReview = reviewVec[2] cleanReview = ct.cleanText(rawReview) shingles = multiShingles.join( MULTI, rm.removeStopwords(cleanReview) ) sentiment = int( reviewVec[1] ) reviewsProcesadas.append( (shingles,sentiment) ) line = labeled.readline() iteracion += 1 sys.stdout.write("\r%d%%" % int( iteracion*100/MAX_ITERACIONES )) sys.stdout.flush() print print iteracion, "reviews entrenados" # Ahora lleno el hash puntajes for review in reviewsProcesadas: sumaPositivo = review[1] sumaNegativo = not sumaPositivo for shingle in review[0]: frecuencias = puntajes[shingle] = puntajes.get(shingle, (0,0)) frecActualizada = (frecuencias[0]+sumaNegativo, frecuencias[1]+sumaPositivo) puntajes[shingle] = frecActualizada # Obtenidos los puntajes ahora voy a calificar los siguientes reviews y ver # que tan bien o mal califico correctos, incorrectos, sinShingles = 0.0, 0.0, 0 iteracion = 0.0 MAX_PRUEBAS = 4900.0 line = labeled.readline() print "PREDICIENDO..." while line and iteracion < MAX_PRUEBAS: rawReview = line.split('\t')[2] cleanReview = ct.cleanText(rawReview) shingles = multiShingles.join(MULTI, cleanReview) puntajePos, puntajeNeg = 0, 0 for sh in shingles: puntajeShingle = puntajes.get(sh, (0,0)) puntajePos += puntajeShingle[1] puntajeNeg += puntajeShingle[0] if (puntajePos != puntajeNeg): sentimientoPosta = int( line.split('\t')[1] ) prediccion = (puntajePos > puntajeNeg) correctos += (prediccion == sentimientoPosta) incorrectos += (prediccion != sentimientoPosta) if (puntajePos == 0 and puntajeNeg == 0): sinShingles += 1 line = labeled.readline() iteracion += 1 sys.stdout.write("\r%d%%" % int(iteracion*100/MAX_PRUEBAS)) print print "\nCORRECTOS:", correctos*100/(correctos+incorrectos), "%" print "EVALUADOS:", correctos+incorrectos, "out of", iteracion, " (", (correctos+incorrectos)*100/iteracion, "% )" print "SIN SHINGLES:", sinShingles # Aca voy a graficar los reviews que quedaron sin entrenar para ver si hay una # separacion lineal interesante ''' iteracion, MAX_GRAFICOS = 0.0, 4900.0 missed = 0 reviewsPosX, reviewsPosY, reviewsNegX, reviewsNegY = [], [], [], [] line = labeled.readline() print "\nGRAFICANDO..." while line and iteracion<MAX_GRAFICOS: reviewVec = line.split('\t') rawReview = reviewVec[2] cleanReview = ct.cleanText(rawReview) shingles = joinMultiShingles(MULTI, cleanReview) puntajePos, puntajeNeg = 0, 0 for sh in shingles: puntajeShingle = puntajes.get(sh, (0,0)) puntajePos += puntajeShingle[1] puntajeNeg += puntajeShingle[0] if (puntajePos == puntajeNeg): missed += 1 if (int(reviewVec[1])): reviewsPosX.append(puntajePos) reviewsPosY.append(puntajeNeg) else: reviewsNegX.append(puntajePos) reviewsNegY.append(puntajeNeg) line = labeled.readline() iteracion += 1 sys.stdout.write( "\r%d%%" % int(iteracion*100/MAX_GRAFICOS) ) sys.stdout.flush() print # Detecto puntos repetidos: positivePoints = zip(reviewsPosX, reviewsPosY) negativePoints = zip(reviewsNegX, reviewsNegY) repeatedPoints = filter(lambda x: x in positivePoints, negativePoints) bothX, bothY = [], [] for point in repeatedPoints: bothX.append(point[0]) bothY.append(point[1]) print print "MISSED REVIEWS:", missed, "out of", iteracion, " (", missed*100/iteracion, "% )" plt.plot(reviewsPosX, reviewsPosY, 'bo', reviewsNegX, reviewsNegY, 'ro', bothX, bothY, 'mo') plt.show() ''' print "----------"
a5355844bd1a97f28bd3d646dac5c0a002ddaf64
SonaArora/Python-on-hands
/string/find_substring.py
641
4.03125
4
#TASK:In this challenge, the user enters a string and a substring. You have to print the number #of times that the substring occurs in the given string. String traversal will take place from #left to right, not from right to left. #Input Format:The first line of input contains the original string. The next line contains the substring. #Output Format:Output the integer number indicating the total number of occurrences of the substring in the #original string. s,t=[raw_input() for k in range(2)] #s is our main string and t is the target substring count=0 for j in range(len(s)): if s[j:j+len(t)]==t: count=count+1 print count
3d5af46e02de9807539ee55095b773a6f83084c2
janne02/ViopePython
/9.2 listan käyttäminen.py
895
3.796875
4
def selection(): try: selection=int(input("Haluatko \n(1)Lisätä listaan \n(2)Poistaa listalta vai\n(3)Lopettaa?:")) return selection except Exception: return "wrong" def secondaction(selection, memo): if selection == 1: memo.append(input("Mitä lisätään?: ")) elif selection == 2: print("Listalla on", len(memo),"alkiota.") target=int(input("Monesko niistä poistetaan?: ")) try: memo.pop(target) except Exception: print("Virheellinen valinta.") elif selection == 3: print("Listalla oli tuotteet:") for i in memo: print(i) return "end" else: print("Virheellinen valinta.") def main(): memo = [] while True: if secondaction(selection(), memo) == "end": break if __name__== "__main__": main()
e27bd3480bcb94e89d06a9d2557a9c57714cfcb5
jayceazua/wallbreakers_work
/practice_facebook/sub_left_leaves.py
1,005
4.0625
4
""" Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: total = 0 # BFS - level order queue = deque() queue.append(root) while queue: current = queue.popleft() if current and current.left: # check if it is a leaf if not current.left.left and not current.left.right: total += current.left.val else: queue.append(current.left) if current and current.right: queue.append(current.right) return total
6d4ebb93de1100fd52bc56159a7f9df3dfb49b42
leonparte/Python-Crash-Course-Learning-Projects
/Chapter 7/Test_7.1.py
1,051
4.125
4
# 函数input()的工作原理 # 从对函数input()的简单使用开始 print("\n-----------------------------------------\n") message = input("Tell me your favorite player:") print(message) # 编写清晰的程序 print("\n-----------------------------------------\n") print("What is your name?") name = input() print("You are", name.title()) # 使用int()来获取数值输入 print("\n-----------------------------------------\n") print("How od are you?") age = int(input()) if age <= 12: print("You can visit the view for free!\n") elif age <= 18: print("You can buy a ticket buy half-cut!\n") else: print("You should buy tickets with full price!\n") # 求模运算符 print("\n-----------------------------------------\n") print("Please enter an integer:") number = int(input()) if number % 2 == 0: print('The number you enter is', number, 'and it is even!') else: print('The number you enter is', number, 'and it is odd!') print("\n-----------------------------------------\n")
36d3b1a5c46cfa0aefe7466867f8eadd10b0d6e3
hb162/Algo
/Algorithm/Ex_060420/Ex_Run-Length.py
903
4.21875
4
""" Run-length encoding is a fact and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For ex, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A". Implement run-length encoding and decoding. U can assume the string to be encoded have no digigts and consists solely of alphabetic characters. You can assume the string to be decoded is valid. """ def run_length_encoding(s): n = len(s) count = 0 code = '' for i in range(n): char = s[i] count += 1 if i == n-1: code = code + str(count) + char break else: if char == s[i+1]: pass else: code = code + str(count) + char count = 0 return code print(run_length_encoding('AAAABBCADU')) """ Độ phức tạp: o(n) """
fba411311b12df6d3045514628f936a278dd2c56
siowyisheng/crypty
/crypty/crypty.py
1,231
3.734375
4
from cryptography.fernet import Fernet def encrypt(s, key=None): """Takes UTF-8 string and optional key(bytes or UTF-8), and spits UTF-8 token""" if key is None: key = Fernet.generate_key() try: f = Fernet(_to_bytes(key)) except binascii.Error: raise ValueError('The key was not valid') try: token = f.encrypt(_to_bytes(s)) except TypeError: raise TypeError('Can only encode string or bytes') s_token, s_key = token.decode('utf8'), key.decode('utf8') return s_token, s_key def decrypt(token, key): """Takes token and key in UTF-8 (or bytes) and spits UTF-8 string""" try: f = Fernet(_to_bytes(key)) except TypeError: raise TypeError('Can only encode string or bytes') try: bytes = f.decrypt(_to_bytes(token)) except TypeError: raise TypeError('Needs key as string or bytes') except binascii.Error: raise ValueError('The key was not valid') return bytes.decode('utf8') def _to_bytes(str_bytes): """Takes UTF-8 string or bytes and safely spits out bytes""" try: bytes = str_bytes.encode('utf8') except AttributeError: return str_bytes return bytes
79f2ffdc5bfef1d364087676915ba780d86d5a52
jedzej/tietopythontraining-basic
/students/myszko_pawel/lesson_03_functions/01_collatz.py
833
4.5625
5
# Write a function named collatz() that has one parameter named number. # If number is even, then collatz() should print number // 2 and return # this value. If number is odd, then collatz() should print and return # 3 * number + 1. # Then write a program that lets the user type in an integer and that # keeps calling collatz() on that number until the function returns # the value 1. def collatz(num_1): if num_1 % 2 == 0: num_1 = num_1 // 2 print(num_1) return int(num_1) elif num_1 % 2 == 1: num_1 = 3 * num_1 + 1 print(num_1) return int(num_1) try: number = int(input("Please type the number (collatz() function " "parameters:")) while number != 1: number = collatz(number) except ValueError: print("Please type an intiger")
5d22a80f66c53304917c56c8b9e25e1aff8a7718
tuncatunc/algorithms
/DataStructures/Graph/Bfs/Minimum steps to reach any of the boundary edges of a matrix/solution.py
1,816
3.609375
4
from collections import namedtuple Point = namedtuple('Point', 'row col') Q = namedtuple('Q', 'point distance') class Graph: def __init__(self, matrix): self.matrix = matrix self.ROWS = len(matrix) self.COLS = len(matrix[0]) def isEdge(self, point): return (point.row == 0 or point.row == self.ROWS - 1 or point.col == 0 or point.col == self.COLS - 1) def isValid(self, point): return (point.row >= 0 and point.row < self.ROWS and point.col >= 0 and point.col < self.COLS and self.matrix[point.row][point.col] != 1) def BFS_nearest_boundry(self, start): visited = [start] queue = [Q(start, 0)] minDistance = Q(Point(-1, -1), 999999) neighs = [ Point(0, -1), # LEFT Point(-1, 0), # TOP Point(0, 1), # RIGHT Point(1, 0) # BOTTOM ] while queue: q = queue.pop(0) # q Point qP = q.point qD = q.distance # print("BFS=>", q) if self.isEdge(q.point): # print("Edge is reached", q) if q.distance < minDistance.distance: minDistance = q for neigh in neighs: # Neigh point nextPoint = Point(qP.row + neigh.row, qP.col + neigh.col) if self.isValid(nextPoint) and nextPoint not in visited: visited.append(nextPoint) queue.append(Q(nextPoint, qD + 1)) print("Min distance to edge", minDistance) matrix = [ [1, 1, 1, 0, 1], [1, 0, 2, 0, 1], [0, 0, 1, 0, 1], [1, 0, 1, 1, 0], ] graph = Graph(matrix) graph.BFS_nearest_boundry(Point(1, 2))
2b419f06830c791d1c3af3dcce62faf97daf9aab
JasonDev-Coder/tictactoe
/tictactoe.py
5,761
3.953125
4
""" Tic Tac Toe Player """ import math import copy X = "X" O = "O" EMPTY = None counter = 0 def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ Returns player who has the next turn on a board. """ Empty = True if (terminal(board)): return for i in range(0, len(board)): for j in range(0, len(board[i])): if (board[i][j] != EMPTY): Empty = False break if (Empty): return X countX = 0 countO = 0 for i in range(0, len(board)): for j in range(0, len(board[i])): if (board[i][j] == X): countX = countX + 1 elif (board[i][j] == O): countO = countO + 1 if (countX > countO): return O else: return X raise NotImplementedError def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ mySet = set() for i in range(3): for j in range(3): if (board[i][j] == EMPTY): mySet.add((i, j)) return mySet raise NotImplementedError def result(board, action): """ Returns the board that results from making move (i, j) on the board. """ board2 = copy.deepcopy(board) if (terminal(board)): return i = action[0] j = action[1] if (i > 2 or i < 0) or (j > 2 or j < 0) or board2[i][j]: raise Exception if (player(board2) == X): board2[i][j] = X else: board2[i][j] = O return board2 raise NotImplementedError def winner(board): """ Returns the winner of the game, if there is one. """ stringX = "" stringO = "" # check for rows for i in range(3): for j in range(3): if (board[i][j] == X): stringX += X elif (board[i][j] == O): stringO += O if (stringX == "XXX"): return X elif (stringO == "OOO"): return O else: stringX = "" stringO = "" stringX = "" stringO = "" # check for columns for j in range(3): for i in range(3): if (board[i][j] == X): stringX += X elif (board[i][j] == O): stringO += O if (stringX == "XXX"): return X elif (stringO == "OOO"): return O else: stringX = "" stringO = "" stringX = "" stringO = "" # check for diagonal for i in range(3): if (board[i][i] == X): stringX += X elif (board[i][i] == O): stringO += O if (stringX == "XXX"): return X elif (stringO == "OOO"): return O stringX = "" stringO = "" # check for anti-diagonal for i in range(3): if (board[i][2 - i] == X): stringX += X elif (board[i][2 - i] == O): stringO += O if (stringX == "XXX"): return X elif (stringO == "OOO"): return O return None raise NotImplementedError def terminal(board): """ Returns True if game is over, False otherwise. """ if (winner(board) != None): return True for i in range(3): for j in range(3): if (board[i][j] == EMPTY): return False return True raise NotImplementedError def utility(board): """ Returns 1 if X has won the game, -1 if O has won, 0 otherwise. """ if (terminal(board)): win = winner(board) if (win == X): return 1 elif (win == O): return -1 else: return 0 raise NotImplementedError def AlphaBeta(board, depth, alpha, beta, maximazinPlayer): if depth == 0 or terminal(board): return utility(board) if maximazinPlayer: bestScore = -math.inf for child in actions(board): board[child[0]][child[1]] = X evaluate = AlphaBeta(board, depth - 1, alpha, beta, False) board[child[0]][child[1]] = EMPTY bestScore = max(bestScore, evaluate) alpha = max(alpha, bestScore) if (beta <= alpha): break return bestScore else: bestScore = math.inf for child in actions(board): board[child[0]][child[1]] = O evaluate = AlphaBeta(board, depth - 1, alpha, beta, True) board[child[0]][child[1]] = EMPTY bestScore = min(bestScore, evaluate) beta = min(beta, bestScore) if (beta <= alpha): break return bestScore def minimax(board): eligiblePairs = actions(board) if (terminal(board)): return None i = -1 j = -1 if player(board) == X: BestScore = -math.inf for child in eligiblePairs: board[child[0]][child[1]] = X Score = AlphaBeta(board, len(eligiblePairs), -math.inf, math.inf, False) board[child[0]][child[1]] = EMPTY if (Score > BestScore): BestScore = Score i = child[0] j = child[1] else: BestScore = math.inf for child in eligiblePairs: board[child[0]][child[1]] = O Score = AlphaBeta(board, len(eligiblePairs), -math.inf, math.inf, True) board[child[0]][child[1]] = EMPTY if Score < BestScore: BestScore = Score i = child[0] j = child[1] return (i, j)
b227fa6b56ae39490dfc59d5185110552a2f96f2
dreilly369/Py
/FizzBuzz/multiplesOf3or5.py
118
3.984375
4
the_sum = 0; for i in range(1,1000): if i % 3 == 0 or i % 5 == 0: the_sum += i print("The sum is: %d" % the_sum)
adfa638bdede78564ce5307b9999e05f6f549efc
LaundroMat/kodi-screentalk
/script.service.screentalk/resources/lib/fractional_seconds.py
535
4.03125
4
def convert_dict_to_fractional_seconds(hours=0, minutes=0, seconds=0, milliseconds=0): fractional_seconds = 0.0 fractional_seconds += milliseconds / 1000.0 fractional_seconds += seconds fractional_seconds += minutes * 60 fractional_seconds += hours * 60 * 60 return fractional_seconds def convert_time_string_to_fractional_seconds(s): # Converts eg 0:20:00 to 120.00 # Format = "hh:mm:ss" hours, minutes, seconds = s.split(":") return int(hours) * 60 * 60 + int(minutes) * 60 + int(seconds)
d15c4da8f399c0fcd9e82b3e6693e6dea693b088
blhwong/algos_py
/grokking_dp/knapsack_dp/count_subsets/main.py
923
3.859375
4
""" Problem Statement Given a set of positive numbers, find the total number of subsets whose sum is equal to a given number 'S'. Example 1: Input: {1, 1, 2, 3}, S=4 Output: 3 The given set has '3' subsets whose sum is '4': {1, 1, 2}, {1, 3}, {1, 3} Note that we have two similar sets {1, 3}, because we have two '1' in our input. Example 2: Input: {1, 2, 7, 1, 5}, S=9 Output: 3 The given set has '3' subsets whose sum is '9': {2, 7}, {1, 7, 1}, {1, 2, 1, 5} """ def count_subsets(num, sum1): dp = [[0] * (sum1 + 1) for _ in range(len(num))] for i in range(len(num)): dp[i][0] = 1 for j in range(1, sum1): dp[0][j] = 1 if num[0] == j else 0 for i in range(1, len(num)): for j in range(1, sum1 + 1): s1 = 0 if num[i] <= j: s1 = dp[i - 1][j - num[i]] s2 = dp[i - 1][j] dp[i][j] = s1 + s2 return dp[-1][sum1]
f80835ecffbd8e0ca45997a667c632715ba3de07
anhpt1993/spiral
/spiral.py
603
3.78125
4
import turtle as t import math while True: try: radius = float(input("Nhập giá trị bán kính lớn nhất của đường xoắn ốc: ")) if radius > 0: break else: print("Nhập số dương nhé bạn!") print() except ValueError: print("Nhập giá trị là số nhé bạn tôi ơi.") print() t.speed(100) i = 0 check = 0 while True: t.circle(i,20) x, y = t.position() i += 1 check = math.sqrt(x**2+y**2) if check > radius: print("{:.2f}".format(check)) break t.done()
03566e8cdb51d947490fc8f0b35e4acc27b41c24
RuzhaK/PythonOOP
/IteratorsAndGeneratorsExercise/CountdownIterator.py
363
3.6875
4
class countdown_iterator: def __init__(self,count): self.count = count def __iter__(self): return self def __next__(self): if self.count<0: raise StopIteration() temp=self.count self.count-=1 return temp iterator = countdown_iterator(10) for item in iterator: print(item, end=" ")
10ae638358f99a4ae5ab601933c4163762fca761
victoriaparkhomenko885/homework_strings_other
/Task1.py
149
3.71875
4
text = 'Я учусь программированию в BRAIN' result = ' '.join(word[0].upper() + word[1:] for word in text.split()) print(result)
47f79eb41255e58d8157565c0316ec2864564c9f
xprilion/-_-
/^__^/2.5.py
1,334
3.671875
4
from LinkedList import LinkedList # def sumList(a, b): # if a.head == None: # return b # elif b.head == None: # return a # c = [] # ta = a.head # tb = b.head # carry = 0 # while ta != None and tb != None: # s = ta.data + tb.data + carry # c.append(s % 10) # carry = int(s > 9) # ta = ta.next # tb = tb.next # if ta == None: # tx = tb # else: # tx = ta # while tx != None: # s = tx.data + carry # c.append(s % 10) # carry = s - c[-1] # tx = tx.next # if carry != 0: # c.append(carry) # ll = LinkedList() # ll.pushList(c) # return ll def sumList(a, b): if a.head == None: return b elif b.head == None: return a c = LinkedList() ta = a.head tb = b.head carry = 0 while ta or tb: s = 0 if ta: s += ta.data ta = ta.next if tb: s += tb.data tb = tb.next if carry: s += carry c.push(s % 10) carry = int(s > 9) if carry != 0: c.push(carry) return c a = LinkedList() b = LinkedList() a.pushList([9, 2, 3]) b.pushList([9, 2, 9]) a.display() b.display() c = sumList(a, b) c.display()
c73665ca48e0ff5ec4681c0d2a010d749a7bff57
collin-clark/python
/server-by-port.py
883
3.9375
4
#!/usr/bin/python # Demo server to open a port # Modified from Python tutorial docs import socket import subprocess print "---------------------------------------------------------" print "This script will open any TCP port that is not currently" print "in use. Below are the ports in use. Any port < 1024 will" print "require sudo." print "---------------------------------------------------------" print " " # subprocess.check_output(['netstat', '-tulpn', '| grep tcp$']) what_port = int(raw_input("What port do you want the server to run on? ")) HOST = '127.0.0.1' # Hostname to bind PORT = what_port # Open non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close()
db1455b8e53097f0e6a79b58babec7f3ac18e555
gjedlicska/speckle-py
/specklepy/objects/units.py
1,604
3.5
4
from specklepy.logging.exceptions import SpeckleException UNITS = ["mm", "cm", "m", "in", "ft", "yd", "mi"] UNITS_STRINGS = { "mm": ["mm", "mil", "millimeters", "millimetres"], "cm": ["cm", "centimetre", "centimeter", "centimetres", "centimeters"], "m": ["m", "meter", "meters", "metre", "metres"], "km": ["km", "kilometer", "kilometre", "kilometers", "kilometres"], "in": ["in", "inch", "inches"], "ft": ["ft", "foot", "feet"], "yd": ["yd", "yard", "yards"], "mi": ["mi", "mile", "miles"], "none": ["none", "null"], } UNITS_ENCODINGS = { "none": 0, "mm": 1, "cm": 2, "m": 3, "km": 4, "in": 5, "ft": 6, "yd": 7, "mi": 8, } def get_units_from_string(unit: str): unit = str.lower(unit) for name, alternates in UNITS_STRINGS.items(): if unit in alternates: return name raise SpeckleException( message=f"Could not understand what unit {unit} is referring to. Please enter a valid unit (eg {UNITS})." ) def get_units_from_encoding(unit: int): for name, encoding in UNITS_ENCODINGS.items(): if unit == encoding: return name raise SpeckleException( message=f"Could not understand what unit {unit} is referring to. Please enter a valid unit encoding (eg {UNITS_ENCODINGS})." ) def get_encoding_from_units(unit: str): try: return UNITS_ENCODINGS[unit] except KeyError: raise SpeckleException( message=f"No encoding exists for unit {unit}. Please enter a valid unit to encode (eg {UNITS_ENCODINGS})." )
b56914b0a8aac1226fc47cf60a1ddff8c2386d82
melissapott/codefights
/adjacent.py
489
4.25
4
"""Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.""" def adjacentElementsProduct(inputArray): products = [] for x in range (0,len(inputArray)-1): products.append(inputArray[x]*inputArray[x+1]) return max(products) # expected result = 21 inputArray = [3, 6, -2, -5, 7, 3] print(adjacentElementsProduct(inputArray)) #expected result = 6 inputArray = [5, 1, 2, 3, 1, 4] print(adjacentElementsProduct(inputArray))
c3a6ca654d161f8894fdba561f4d43c5cc363e77
noamalka228/PythonExercise
/Bank.py
7,164
4.25
4
import sqlite3 import socket con = sqlite3.connect('mydb.db') cur = con.cursor() # running steps: # 1. run Database first. # 2. run Bank # 3. run Atm # each run of the Database file deletes the Bank table contents. # So running it once and then preforming only 2nd and 3rd steps is the optimal action. # python interpreter 3.8 class Bank: # constructor def __init__(self, fortune, accounts): self.fortune=fortune self.accounts=accounts # adding an account to the bank, using a valid credentials that was sent by the client def add_account(self, account_num, name, pin, balance): cur.execute("INSERT INTO Bank (account_number, name, pin, balance) VALUES(?,?,?,?)" ,(account_num, name, pin, balance)) con.commit() print("New bank account has been created successfully!") # depositing money to the valid account number that was sent as parameter def deposit(self, account_num, amount): m="Success! account have deposited %d$." %amount result = cur.execute("SELECT * FROM Bank WHERE account_number=?", (account_num, )).fetchone() cur.execute("UPDATE Bank SET balance=? WHERE account_number=?", (result[3]+amount, account_num)) con.commit() print(m) return m # returning the string and in the main sending it to the client # withdrawing money from the valid account number that was sent as parameter def withdraw(self, account_num, amount): m = "Error Occured!" result = cur.execute("SELECT * FROM Bank WHERE account_number=?", (account_num, )).fetchone() if amount > result[3]: m = ("Cant withdraw more than %d$!" %result[3]) else: cur.execute("UPDATE Bank SET balance=? WHERE account_number=?", (result[3] - amount, account_num)) con.commit() m = "Success! account have withdraw %d$." % amount print(m) return m # returning the string and in the main sending it to the client # checking if the user credentials are valid and exist in the Bank in order to log into their account def check_credentials(self, acc, pin_code): result = cur.execute("SELECT * FROM Bank WHERE account_number=? AND pin=?", (acc, pin_code)).fetchone() if result: return True return False # checking the balance of the account whom account number was sent as parameter def check_balance(self, account_num): result = cur.execute("SELECT * FROM Bank WHERE account_number=?", (account_num,)).fetchone() m = ("You have %d$ in your account" % result[3]) print(m) return m # returning the string and in the main sending it to the client def main(): sum=0 count=0 action='0' msg = '''\nWelcome to the Noam's Bank! Enter the code of the action you would like to execute: 1 = deposit 2 = withdraw 3 = check balance 4 = exit\n The code: ''' server_socket = socket.socket() # creating new socket server_socket.bind(('0.0.0.0',1729)) # setting it as the server and connect on port 1729 server_socket.listen(1) # determing the number of clients connecting to the server (client_socket, client_address) = server_socket.accept() # establishing the connection between the client socket and address print("Client has entered") # printing all existing bank accounts print("All of the bank accounts:\n" "account_num | name | PIN | balance\n" "___________________________________") rows = cur.execute("SELECT * FROM Bank").fetchall() if rows: for row in rows: print(row) count+=1 sum+=row[3] else: print("No bank accounts at the moment...") # creating new bank my_bank = Bank(sum, count) # as long as the sent action by the client is not 4 (exit), keep getting input from the client while True and action!='4': first_code = int(client_socket.recv(1024).decode()) # 1= log in, 2= create new account print("The code is: %d" %first_code) while True: # keep getting input from user until action=4 if first_code==1: # receiving log in credentials from the client acc = client_socket.recv(1024).decode() print(acc) pin_code = client_socket.recv(1024).decode() print(pin_code) credentials = my_bank.check_credentials(acc, pin_code) # checking client credentials print(credentials) client_socket.send(bytes((str(credentials)).encode('utf-8'))) # letting the client know if credentials are valid if credentials == True: # keep getting input from user until action=4 while action != '4': client_socket.send(bytes((msg).encode('utf-8'))) action = client_socket.recv(1024).decode() if action == '1': # deposit amount = client_socket.recv(1024).decode() if int(amount) > 0: client_socket.send(bytes(my_bank.deposit(acc, int(amount)).encode('utf-8'))) else: client_socket.send(bytes((msg).encode('utf-8'))) elif action=='2': # withdraw amount = client_socket.recv(1024).decode() if int(amount) > 0: client_socket.send(bytes(my_bank.withdraw(acc, int(amount)).encode('utf-8'))) else: client_socket.send(bytes((msg).encode('utf-8'))) elif action == '3': # check balance client_socket.send(bytes(my_bank.check_balance(acc).encode('utf-8'))) elif action=='4': # exit print("Goodbye!") break else: # not a number between 1-4 so print invalid input and show menu again print("Invalid input!") client_socket.send(bytes((msg).encode('utf-8'))) break # breaking the first While to exit the system else: # creating new account # getting new account valid credentials from the client print("Creating new account...") acc_num = int(client_socket.recv(1024).decode()) print(acc_num) name = client_socket.recv(1024).decode() print(name) pin = client_socket.recv(1024).decode() print(pin) balance = client_socket.recv(1024).decode() print(balance) my_bank.add_account(acc_num, name, pin, balance) # creating the new account first_code = int(client_socket.recv(1024).decode()) print("The code is: %d" % first_code) server_socket.close() # ending the session if __name__ == '__main__': main()
80621f0bc511a2f91efc98192616b18dbc68259b
shoobham1011/NewProjectLAB
/Labratory/Lab2/Question3.py
299
3.625
4
''' Price of a house is $1M. If buyer has good credit, they need to put down 10% otherwise they need to put down 20% print down the payment. ''' buyer_credit = True price = 1000000 if buyer_credit: down_pay = 0.1 * price else: down_pay = 0.2 * price print(f'Down payment is ${down_pay}')
042c6e961f512b112e8e0a92b14b7cdbb00ca570
kruthikapalleda/Python-Project-1
/sortingPy.py
2,107
3.671875
4
import sys class Emplyoee: def __init__(self,eno,ename,esal,eaddr,sortingKey="ENO"): self.eno = eno self.ename = ename self.esal = esal self.eaddr = eaddr def __lt__(self,other): if self.sortingKey == "ENO": return self.eno < other.eno elif self.sortingKey == "ENAME" return self.ename < other.ename elif self.sortingKey == "ESAL" return self.esal < other.esal elif self.sortingKey == "EADDR" return self.eaddr < other.eaddr else: pass emp1 = Employee(111,'Kruthi',9000,'HYD') emp2 = Employee(222,'Bruno',8000,'PUNE') emp3 = Employee(333,'chayu',1000,'KAR') emp4 = Employee(444,'divi',3000,'BLR') emp5 = Employee(555,'Ranju',2000,'CHE') def sort(list): while True: count = 0 for x in range(0, len(list) - 1): if list[x] < list[x+1]: pass else: count = count + 1 temp = list[x] list[x] = list [x+1] if count == 0 break else: continue list = [emp1 , emp2 , emp3 , emp4 , emp5] while True: print("1.Sorting By ENO") print("2.Sorting BY ENAME") print("3.Sorting By ESAL") print("4.Sorting By EADDR") print("EXIT") option = int(input("Your options :") if option == 1: Employee.sortingKey = "ENO" sort(list) elif option == 2: Employee.sortingKey = "ENAME" sort(list) elif option == 3: Employee.sortingKey = "ESAL" sort(list) elif option == 4: Employee.sortingKey = "EADDR" sort(list) elif option == 5: Employee.sortingKey = "EXIT" sys.exit else: print("Provide the number from 1 to 5") print("ENO\tENAME\tESAL\tEADDR") print("----------------------------------------") for emp in list: print(emp.eno,"\t", emp.ename,"\t", emp.esal,"\t", emp.eaddr,"\t") print()
b5b3334200f7cb3ced7c3bc6843c4ab7cfa15477
KudynDmytro/Practice
/hw4.py
2,389
3.828125
4
#1.Найти все числа, что нацело делятся на 7 впромежутке от 1 до 50 z = input('enter a number:') def first_ex(x): if x.isnumeric(): for i in range(1, int(x)): if i % 7 == 0: print(i) else: print('Error: you entered not a number!') return first_ex(z) #2.Написать ИИ, который будет распознавать, что ввёл пользователь:e-mail, телефон или имя. ent = input('enter:') def lama(a): w = 'Sorry, I don\'t know what is that' if a[0] == '+': if len(a) == 13: if a[1:].isnumeric(): if a[1:3] == '61': print('You entered Australian phone number') elif a[1:3] == '43': print('You entered Austrian phone number') elif a[1:5] == '1264': print('You entered English phone number') elif a[1:4] == '375': print('You entered Belorussian phone number') elif a[1] == '7': print('You entered Russian phone number') elif a[1:4] == '380': print('You entered Ukrainian phone number') else: print(w) else: print(w) else: if'@' in a: s = a.split('@') d = s[1].split('.') if '.' in s[0]: if s[0].count('.') > 1: print(w) elif s[0][0] == '.': print(w) else: if len(s[0]) >= 3: if len(d[0]) == 3: if len(d[1]): print('You entered an e-mail') else: f = a.split(' ') if a.replace(' ', '').isalpha(): for i in f: if len(i) >= 2: for j in i: if j.isupper(): print('You entered a name') return else: print(w) break else: print(w) break else: print(w) lama(ent)
a51fea67ff9a3362f94fa101d8abaac6f4f290d3
Amberttt/Python3-Test
/REGExpressions.py
19,268
3.5625
4
# Python3 正则表达式 # 正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。 # Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。 # re 模块使 Python 语言拥有全部的正则表达式功能。 # compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。 # re 模块也提供了与这些方法功能完全一致的函数,这些函数使用一个模式字符串做为它们的第一个参数。 # 本章节主要介绍Python中常用的正则表达式处理函数。 # re.match函数 # re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。 # 函数语法: # re.match(pattern, string, flags=0) # 函数参数说明: # 参数 描述 # pattern 匹配的正则表达式 # string 要匹配的字符串。 # flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志 # 匹配成功re.match方法返回一个匹配的对象,否则返回None。 # 我们可以使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。 # 匹配对象方法 描述 # group(num=0) 匹配的整个表达式的字符串,group() 可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。 # groups() 返回一个包含所有小组字符串的元组,从 1 到 所含的小组号。 # 实例 # #!/usr/bin/python # import re # print(re.match('www', 'www.runoob.com').span()) # 在起始位置匹配 # print(re.match('com', 'www.runoob.com')) # 不在起始位置匹配 # 以上实例运行输出结果为: # (0, 3) # None # 实例 # #!/usr/bin/python3 # import re # line = "Cats are smarter than dogs" # matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) # if matchObj: # print ("matchObj.group() : ", matchObj.group()) # print ("matchObj.group(1) : ", matchObj.group(1)) # print ("matchObj.group(2) : ", matchObj.group(2)) # else: # print ("No match!!") # 以上实例执行结果如下: # matchObj.group() : Cats are smarter than dogs # matchObj.group(1) : Cats # matchObj.group(2) : smarter # re.search方法 # re.search 扫描整个字符串并返回第一个成功的匹配。 # 函数语法: # re.search(pattern, string, flags=0) # 函数参数说明: # 参数 描述 # pattern 匹配的正则表达式 # string 要匹配的字符串。 # flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志 # 匹配成功re.search方法返回一个匹配的对象,否则返回None。 # 我们可以使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。 # 匹配对象方法 描述 # group(num=0) 匹配的整个表达式的字符串,group() 可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。 # groups() 返回一个包含所有小组字符串的元组,从 1 到 所含的小组号。 # 实例 # #!/usr/bin/python3 # import re # print(re.search('www', 'www.runoob.com').span()) # 在起始位置匹配 # print(re.search('com', 'www.runoob.com').span()) # 不在起始位置匹配 # 以上实例运行输出结果为: # (0, 3) # (11, 14) # 实例 # #!/usr/bin/python3 # import re # line = "Cats are smarter than dogs"; # searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) # if searchObj: # print ("searchObj.group() : ", searchObj.group()) # print ("searchObj.group(1) : ", searchObj.group(1)) # print ("searchObj.group(2) : ", searchObj.group(2)) # else: # print ("Nothing found!!") # 以上实例执行结果如下: # searchObj.group() : Cats are smarter than dogs # searchObj.group(1) : Cats # searchObj.group(2) : smarter # re.match与re.search的区别 # re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。 # 实例 # #!/usr/bin/python3 # import re # line = "Cats are smarter than dogs"; # matchObj = re.match( r'dogs', line, re.M|re.I) # if matchObj: # print ("match --> matchObj.group() : ", matchObj.group()) # else: # print ("No match!!") # matchObj = re.search( r'dogs', line, re.M|re.I) # if matchObj: # print ("search --> matchObj.group() : ", matchObj.group()) # else: # print ("No match!!") # 以上实例运行结果如下: # No match!! # search --> matchObj.group() : dogs # 检索和替换 # Python 的re模块提供了re.sub用于替换字符串中的匹配项。 # 语法: # re.sub(pattern, repl, string, count=0) # 参数: # pattern : 正则中的模式字符串。 # repl : 替换的字符串,也可为一个函数。 # string : 要被查找替换的原始字符串。 # count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。 # 实例 # #!/usr/bin/python3 # import re # phone = "2004-959-559 # 这是一个电话号码" # # 删除注释 # num = re.sub(r'#.*$', "", phone) # print ("电话号码 : ", num) # # 移除非数字的内容 # num = re.sub(r'\D', "", phone) # print ("电话号码 : ", num) # 以上实例执行结果如下: # 电话号码 : 2004-959-559 # 电话号码 : 2004959559 # repl 参数是一个函数 # 以下实例中将字符串中的匹配的数字乘于 2: # 实例 # #!/usr/bin/python # import re # # 将匹配的数字乘于 2 # def double(matched): # value = int(matched.group('value')) # return str(value * 2) # s = 'A23G4HFD567' # print(re.sub('(?P<value>\d+)', double, s)) # 执行输出结果为: # A46G8HFD1134 # compile 函数 # compile 函数用于编译正则表达式,生成一个正则表达式( Pattern )对象,供 match() 和 search() 这两个函数使用。 # 语法格式为: # re.compile(pattern[, flags]) # 参数: # pattern : 一个字符串形式的正则表达式 # flags 可选,表示匹配模式,比如忽略大小写,多行模式等,具体参数为: # re.I 忽略大小写 # re.L 表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境 # re.M 多行模式 # re.S 即为' . '并且包括换行符在内的任意字符(' . '不包括换行符) # re.U 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依赖于 Unicode 字符属性数据库 # re.X 为了增加可读性,忽略空格和' # '后面的注释 # 实例 # 实例 # >>>import re # >>> pattern = re.compile(r'\d+') # 用于匹配至少一个数字 # >>> m = pattern.match('one12twothree34four') # 查找头部,没有匹配 # >>> print m # None # >>> m = pattern.match('one12twothree34four', 2, 10) # 从'e'的位置开始匹配,没有匹配 # >>> print m # None # >>> m = pattern.match('one12twothree34four', 3, 10) # 从'1'的位置开始匹配,正好匹配 # >>> print m # 返回一个 Match 对象 # <_sre.SRE_Match object at 0x10a42aac0> # >>> m.group(0) # 可省略 0 # '12' # >>> m.start(0) # 可省略 0 # 3 # >>> m.end(0) # 可省略 0 # 5 # >>> m.span(0) # 可省略 0 # (3, 5) # 在上面,当匹配成功时返回一个 Match 对象,其中: # group([group1, …]) 方法用于获得一个或多个分组匹配的字符串,当要获得整个匹配的子串时,可直接使用 group() 或 group(0); # start([group]) 方法用于获取分组匹配的子串在整个字符串中的起始位置(子串第一个字符的索引),参数默认值为 0; # end([group]) 方法用于获取分组匹配的子串在整个字符串中的结束位置(子串最后一个字符的索引+1),参数默认值为 0; # span([group]) 方法返回 (start(group), end(group))。 # 再看看一个例子: # 实例 # >>>import re # >>> pattern = re.compile(r'([a-z]+) ([a-z]+)', re.I) # re.I 表示忽略大小写 # >>> m = pattern.match('Hello World Wide Web') # >>> print m # 匹配成功,返回一个 Match 对象 # <_sre.SRE_Match object at 0x10bea83e8> # >>> m.group(0) # 返回匹配成功的整个子串 # 'Hello World' # >>> m.span(0) # 返回匹配成功的整个子串的索引 # (0, 11) # >>> m.group(1) # 返回第一个分组匹配成功的子串 # 'Hello' # >>> m.span(1) # 返回第一个分组匹配成功的子串的索引 # (0, 5) # >>> m.group(2) # 返回第二个分组匹配成功的子串 # 'World' # >>> m.span(2) # 返回第二个分组匹配成功的子串 # (6, 11) # >>> m.groups() # 等价于 (m.group(1), m.group(2), ...) # ('Hello', 'World') # >>> m.group(3) # 不存在第三个分组 # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # IndexError: no such group # findall # 在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。 # 注意: match 和 search 是匹配一次 findall 匹配所有。 # 语法格式为: # findall(string[, pos[, endpos]]) # 参数: # string 待匹配的字符串。 # pos 可选参数,指定字符串的起始位置,默认为 0。 # endpos 可选参数,指定字符串的结束位置,默认为字符串的长度。 # 查找字符串中的所有数字: # 实例 # import re # pattern = re.compile(r'\d+') # 查找数字 # result1 = pattern.findall('runoob 123 google 456') # result2 = pattern.findall('run88oob123google456', 0, 10) # print(result1) # print(result2) # 输出结果: # ['123', '456'] # ['88', '12'] # re.finditer # 和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。 # re.finditer(pattern, string, flags=0) # 参数: # 参数 描述 # pattern 匹配的正则表达式 # string 要匹配的字符串。 # flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志 # 实例 # import re # it = re.finditer(r"\d+","12a32bc43jf3") # for match in it: # print (match.group() ) # 输出结果: # 12 # 32 # 43 # 3 # re.split # split 方法按照能够匹配的子串将字符串分割后返回列表,它的使用形式如下: # re.split(pattern, string[, maxsplit=0, flags=0]) # 参数: # 参数 描述 # pattern 匹配的正则表达式 # string 要匹配的字符串。 # maxsplit 分隔次数,maxsplit=1 分隔一次,默认为 0,不限制次数。 # flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志 # 实例 # >>>import re # >>> re.split('\W+', 'runoob, runoob, runoob.') # ['runoob', 'runoob', 'runoob', ''] # >>> re.split('(\W+)', ' runoob, runoob, runoob.') # ['', ' ', 'runoob', ', ', 'runoob', ', ', 'runoob', '.', ''] # >>> re.split('\W+', ' runoob, runoob, runoob.', 1) # ['', 'runoob, runoob, runoob.'] # >>> re.split('a*', 'hello world') # 对于一个找不到匹配的字符串而言,split 不会对其作出分割 # ['hello world'] # 正则表达式对象 # re.RegexObject # re.compile() 返回 RegexObject 对象。 # re.MatchObject # group() 返回被 RE 匹配的字符串。 # start() 返回匹配开始的位置 # end() 返回匹配结束的位置 # span() 返回一个元组包含匹配 (开始,结束) 的位置 # 正则表达式修饰符 - 可选标志 # 正则表达式可以包含一些可选标志修饰符来控制匹配的模式。修饰符被指定为一个可选的标志。多个标志可以通过按位 OR(|) 它们来指定。如 re.I | re.M 被设置成 I 和 M 标志: # 修饰符 描述 # re.I 使匹配对大小写不敏感 # re.L 做本地化识别(locale-aware)匹配 # re.M 多行匹配,影响 ^ 和 $ # re.S 使 . 匹配包括换行在内的所有字符 # re.U 根据Unicode字符集解析字符。这个标志影响 \w, \W, \b, \B. # re.X 该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。 # 正则表达式模式 # 模式字符串使用特殊的语法来表示一个正则表达式: # 字母和数字表示他们自身。一个正则表达式模式中的字母和数字匹配同样的字符串。 # 多数字母和数字前加一个反斜杠时会拥有不同的含义。 # 标点符号只有被转义时才匹配自身,否则它们表示特殊的含义。 # 反斜杠本身需要使用反斜杠转义。 # 由于正则表达式通常都包含反斜杠,所以你最好使用原始字符串来表示它们。模式元素(如 r'\t',等价于 \\t )匹配相应的特殊字符。 # 下表列出了正则表达式模式语法中的特殊元素。如果你使用模式的同时提供了可选的标志参数,某些模式元素的含义会改变。 # 模式 描述 # ^ 匹配字符串的开头 # $ 匹配字符串的末尾。 # . 匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符。 # [...] 用来表示一组字符,单独列出:[amk] 匹配 'a','m'或'k' # [^...] 不在[]中的字符:[^abc] 匹配除了a,b,c之外的字符。 # re* 匹配0个或多个的表达式。 # re+ 匹配1个或多个的表达式。 # re? 匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式 # re{ n} 匹配n个前面表达式。例如,"o{2}"不能匹配"Bob"中的"o",但是能匹配"food"中的两个o。 # re{ n,} 精确匹配n个前面表达式。例如,"o{2,}"不能匹配"Bob"中的"o",但能匹配"foooood"中的所有o。"o{1,}"等价于"o+"。"o{0,}"则等价于"o*"。 # re{ n, m} 匹配 n 到 m 次由前面的正则表达式定义的片段,贪婪方式 # a| b 匹配a或b # (re) G匹配括号内的表达式,也表示一个组 # (?imx) 正则表达式包含三种可选标志:i, m, 或 x 。只影响括号中的区域。 # (?-imx) 正则表达式关闭 i, m, 或 x 可选标志。只影响括号中的区域。 # (?: re) 类似 (...), 但是不表示一个组 # (?imx: re) 在括号中使用i, m, 或 x 可选标志 # (?-imx: re) 在括号中不使用i, m, 或 x 可选标志 # (?#...) 注释. # (?= re) 前向肯定界定符。如果所含正则表达式,以 ... 表示,在当前位置成功匹配时成功,否则失败。但一旦所含表达式已经尝试,匹配引擎根本没有提高;模式的剩余部分还要尝试界定符的右边。 # (?! re) 前向否定界定符。与肯定界定符相反;当所含表达式不能在字符串当前位置匹配时成功。 # (?> re) 匹配的独立模式,省去回溯。 # \w 匹配数字字母下划线 # \W 匹配非数字字母下划线 # \s 匹配任意空白字符,等价于 [\t\n\r\f]。 # \S 匹配任意非空字符 # \d 匹配任意数字,等价于 [0-9]。 # \D 匹配任意非数字 # \A 匹配字符串开始 # \Z 匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串。 # \z 匹配字符串结束 # \G 匹配最后匹配完成的位置。 # \b 匹配一个单词边界,也就是指单词和空格间的位置。例如, 'er\b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。 # \B 匹配非单词边界。'er\B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。 # \n, \t, 等。 匹配一个换行符。匹配一个制表符, 等 # \1...\9 匹配第n个分组的内容。 # \10 匹配第n个分组的内容,如果它经匹配。否则指的是八进制字符码的表达式。 # 正则表达式实例 # 字符匹配 # 实例 描述 # python 匹配 "python". # 字符类 # 实例 描述 # [Pp]ython 匹配 "Python" 或 "python" # rub[ye] 匹配 "ruby" 或 "rube" # [aeiou] 匹配中括号内的任意一个字母 # [0-9] 匹配任何数字。类似于 [0123456789] # [a-z] 匹配任何小写字母 # [A-Z] 匹配任何大写字母 # [a-zA-Z0-9] 匹配任何字母及数字 # [^aeiou] 除了aeiou字母以外的所有字符 # [^0-9] 匹配除了数字外的字符 # 特殊字符类 # 实例 描述 # . 匹配除 "\n" 之外的任何单个字符。要匹配包括 '\n' 在内的任何字符,请使用象 '[.\n]' 的模式。 # \d 匹配一个数字字符。等价于 [0-9]。 # \D 匹配一个非数字字符。等价于 [^0-9]。 # \s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。 # \S 匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。 # \w 匹配包括下划线的任何单词字符。等价于'[A-Za-z0-9_]'。 # \W 匹配任何非单词字符。等价于 '[^A-Za-z0-9_]'。 # 4 篇笔记 # Chen # 386***542@qq.com # 正则表达式符号使用小总结: # 1、[ ]:方括号。匹配需要的字符集合,如[1-3]或[123]都是匹配1、2或者3。 # 2、^:脱字符号。方括号中加入脱字符号,就是匹配未列出的所有其他字符,如[^a]匹配除a以外的所有其他字符。 # 3、\:反斜杠。和python字符串使用规则一样,可以匹配特殊字符本身,如\d表示匹配0到9的任意一个数字字符,而\\d则表示匹配\d本身。 # 4、*:星号。匹配前一个字符0到n次,如pytho*n可以匹配pythn、pytoon、pythooooon等。还有其它匹配重复字符的如?、+或{m,n},其中{n,m}可以灵活使用,它表示匹配n次到m次。 # Chen # Chen # 386***542@qq.com # 10个月前 (09-15) # Tina # 223***4288@qq.com # re.sub 使用实例:改变日期的格式,如中国格式 2017-11-27 改为美国格式 11/27/2017: # >>> s = '2017-11-27' # >>> import re # >>> print(re.sub('(\d{4})-(\d{2})-(\d{2})',r'\2/\3/\1', s)) # 11/27/2017 # >>> # 用 () 来划定原字符串的组,{} 中表示数字的个数,r 即后面的字符串为原始字符串,防止计算机将 \ 理解为转义字符,2,3,1 为输入的字符串三段的序号。 # Tina # Tina # 223***4288@qq.com # 7个月前 (11-27) # 不梦君 # 411***800@qq.com # 关于正则表达式 \b 模式,还有一点需要说明,\b 是指匹配一个单词边界,也就是指单词和空格间的位置。但事实上,\b 可以匹配的边界包括单词和特殊字符边界,比如 $,#… 等。 # 例如: # import re # ret = re.findall(r'o\b','hello nano$') # print(ret) #结果为['o', 'o'] # 不梦君 # 不梦君 # 411***800@qq.com # 2个月前 (05-06) # 按倒揉咪咪 # sym***roc@163.com # (?<name>exp) 匹配 exp,并捕获文本到名称为 name 的组里,也可以写成 (?'name'exp)。 # 但是在Python中,为 (?P<name>exp)。 简单例子: # import re # pattern = re.compile(r'(?P<here>[a-z]+) ([a-z]+)', re.I) # m = pattern.match('Hello World word helo') # print (m.group('here')) # 输出结果为: # Hello # 命名组是便于使用的,可以替代需要记住组的数字,可以进行扩展使用。
20f7834a0700706479f41d7ef7a81d9e5c0c15e2
escharf72/Engineering_4_Notebook
/arrays.py
114
3.625
4
def myFunc(a): b = [] for stuff in a: b.append(stuff**2) return(b) myArr = [1,3,6,23] print(myFunc(myArr))
cc37fdd4e673ff3fc16abf82bed8454416d58619
skizap/DDos
/bot.py
159
3.59375
4
import urllib url = raw_input ("url :") with open ("123.txt",'r') as f: for i in f : x = urllib.urlopen (i.strip()+url) print x.getcode()
f110037bfd574542f0653c40184e70c58ba768e8
mew177/MJW_Egan
/LeetCode/121. Best Time to Buy and Sell Stock.py
332
3.90625
4
""" Question: 1. Will there be negative value? 2. How largest would the price can be? Idea: 1. Use dynamic program """ prices = [7,1,5,3,6,4] maxDiff = 0 lowest = float('inf') for price in prices: lowest = min(lowest, price) maxDiff = max(maxDiff, price - lowest) print(maxDiff)
861b86669573b739121d414562e0418a2d48a594
TianrunCheng/LeetcodeSubmissions
/distribute-candies/Accepted/3-2-2021, 2:27:12 AM/Solution.py
344
3.71875
4
// https://leetcode.com/problems/distribute-candies class Solution: def distributeCandies(self, candyType: List[int]) -> int: types = set() n = len(candyType) for c in candyType: types.add(c) t = len(types) if t < n//2: return t else: return n//2
84e30e8203f9c9e49ab18230265538fa9c9c4e2b
dbtomato/PythonStudy
/每周作业/郭岳雄/第三周/Queue_code.py
2,907
4
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Python37-32 ''' @Author : {Gavin Guo} @License : (C) Copyright 2019-2024, {Daxiong's Company} @Contact : {878953027@qq.com} @Software: PyCharm @File : Queue_code.py @Time : 2020/3/1 12:20 @Desc : ''' ''' 代码引用来自:https://www.cnblogs.com/yhleng/p/9493457.html ''' from queue import Queue,LifoQueue,PriorityQueue from collections import deque import time from threading import Thread ''' Queue 先进先出队列: #基本FIFO队列 先进先出 FIFO即First in First Out,先进先出 #maxsize设置队列中,数据上限,小于或等于0则不限制,容器中大于这个数则阻塞,直到队列中的数据被消掉 ''' print("----------------------------------------------------------") q = Queue(maxsize=0) q.put(0) q.put(1) q.put(2) #输出当前队列所有数据 print(q.queue) #获取一个值,并删除 first_value = q.get() print(q.queue) print(first_value) print("----------------------------------------------------------") #LIFO即Last in First Out,后进先出。与栈的类似,使用也很简单,maxsize用法同上 lq = LifoQueue(maxsize=0) #队列写入数据 lq.put(0) lq.put(1) lq.put(2) #输出队列所有数据 print(lq.queue) #删除队尾数据,并返回该数据 print(lq.get()) #输出队列所有数据 print(lq.queue) #输出: # [0, 1, 2] # [0, 1] print("----------------------------------------------------------") # 存储数据时可设置优先级的队列 # 优先级设置数越小等级越高 pq = PriorityQueue(maxsize=0) #写入队列,设置优先级 pq.put((9,'a')) pq.put((7,'c')) pq.put((1,'d')) #输出队例全部数据 print(pq.queue) #取队例数据,可以看到,是按优先级取的。 pq.get() pq.get() print(pq.queue) #输出: [(9, 'a')] print("----------------------------------------------------------") #双边队列 dq = deque(['a','b']) #增加数据到队尾 dq.append('c') #增加数据到队左 dq.appendleft('d') #输出队列所有数据 print(dq) #移除队尾,并返回 print(dq.pop()) #移除队左,并返回 print(dq.popleft()) #输出: #deque(['d', 'a', 'b', 'c']) #c #d print("----------------------------------------------------------") #生产消费模型 qq = Queue(maxsize=10) def product(name): count = 1 while True: q.put('步枪{}'.format(count)) print('{}生产步枪{}支'.format(name,count)) count+=1 time.sleep(0.3) def cousume(name): while True: print('{}装备了{}'.format(name,q.get())) time.sleep(0.3) q.task_done() #部队线程 p = Thread(target=product,args=('张三',)) k = Thread(target=cousume,args=('李四',)) w = Thread(target=cousume,args=('王五',)) p.start() k.start() w.start()
85b4585fcbca078f95cc280d245b56590982c907
glendaascencio/Python-Tutorials
/Working_With_Lists.py
424
4.0625
4
# Combining two lists numbers = [1, 2, 3, 4] letters = ['a', 'b'] glenda = numbers + letters glenda # see how many methods a declared variable has dir(glenda) glenda.reverse() print 'See what happens when you use the reverse function = ', glenda glenda.append(23) print 'See what happens when you use the append function = ', glenda glenda.remove(23) print 'See what happens when you use the remove function = ', glenda
a855de7b2a36267f1f1b6136e0efa1de94d224c9
felipesilvadv/felipesilvadv-iic2233-2017-1
/Tareas/T02/Partida.py
10,774
3.65625
4
from Planeta import Planeta from EDD import ListaLigada class Partida: def __init__(self, infeccion=""): if infeccion: self.planeta = Planeta(infeccion) self.planeta.agregar_vecinos() self.planeta.agregar_aeropuertos() else: self.planeta = None self.sucesos_dia = "" self.dia_actual = 0 def menu(self): # diseño del menu del usuario print("""Bienvendido a Pandemic""") print("Que tipo de partida quieres jugar?: \n" "1. Nueva\n" "2. Anterior\n") opcion = verificar_int("Tipo de Partida", menu=True) if opcion == 1: self.partida_nueva() else: self.cargar_partida() while self.planeta.esta_infectado and not self.planeta.esta_muerto: if self.dia_actual > 0: print("Dia actual : {}".format(self.dia_actual)) print("Opciones de Juego\n" "1. Pasar de dia\n" "2. Consultar Estadisticas\n" "3. Guardar Partida\n" "4. Salir\n") opcion_juego = verificar_int("Opcion", menu=True, posibles="[1-4]", lista_posibles=(1, 2, 3, 4)) if opcion_juego == 1: self.pasar_dia() elif opcion_juego == 2: self.estadisticas() elif opcion_juego == 3: self.guardar_partida() else: print("Hasta luego!") break if self.planeta.esta_muerto: print("Ganaste, destruiste al mundo completo") elif opcion != 4: print("Perdiste, ha desaparecido tu infección") def cargar_partida(self): # Tiene que leer una partida guardada por este mismo programa y instanciar todos los objetos # para poder continuar una partida print("No esta implementado") def guardar_partida(self): # tiene que guardar de una forma sencilla los paises, poblacion: # viva,infectada,muerta y el tipo de infeccion que habia # guardar las conecciones terrestres y aereas print("No esta implementado") def partida_nueva(self): # Tiene que crear una partida a partir de los csv dados inicialmente infeccion = "algo" tipo = ListaLigada("Virus", "Bacteria", "Parasito") while infeccion not in tipo: infeccion = input("Escoja su tipo de infeccion [Virus-Bacteria-Parasito]: ").title() if infeccion not in tipo: print("Intentalo de nuevo, recuerda que debes escoger entre Virus-Bacteria-Parasito") self.planeta = Planeta(infeccion) self.planeta.paises = self.planeta.poblar_mundo() for pais in self.planeta: self.planeta.poblacion_mundial += pais.poblacion pais.infeccion = self.planeta.infeccion self.planeta.agregar_aeropuertos() self.planeta.agregar_vecinos() lista_nombres = ListaLigada(*(pais.nombre for pais in self.planeta)) while True: nombre = input("Desde que país quieres partir la infeccion?: ").title() if nombre in lista_nombres: break else: print("El pais dado no es válido") for pais in self.planeta: if pais.nombre == nombre: pais.infectados = 10 def estadisticas(self): # Resumen del dia: Gente que murio/infecto, a que paises llego la infeccion, # aeropuertos que cerraron, que paises cerraron fronteras y cuales empezaron # a entregar mascarillas # Por pais: estatus general(vivos/inf/muertos) y ver la cola de prioridades del gobierno del dia # Global: Mostrar paises limpios, infectados y muertos y totales de poblacion (v/i/m) # Lista de infecciones y muertes por día # Debe mostrar la tasa de vida y muerte de las personas del día actual o el acumulado hasta la fecha while True: opcion = input("Que estadisticas deseas ver?\n" "1. Resumen del dia\n" "2. Por pais\n" "3. Global\n") try: opcion = int(opcion) if opcion > 3 or opcion < 1: raise ValueError break except ValueError: print("Debes ingresar alguno de los números: 1, 2 o 3") if opcion == 1: print(self.sucesos_dia) elif opcion == 2: lista_nombres = ListaLigada(*(pais.nombre for pais in self.planeta)) while True: nombre = input("Sobre que país quieres saber?: ").title() if nombre in lista_nombres: break else: print("El pais dado no es válido") for pais in self.planeta: if nombre == pais.nombre: estatus = "Vivos: {0}, Infectados: {1}, Muertos: {2}".format(pais.vivos, pais.infectados, pais.muertos) + "\n" estatus += str(pais.gob) print(estatus) else: paises_limpios = ListaLigada(*(pais.nombre for pais in self.planeta if not pais.esta_infectado)) paises_infectados = ListaLigada(*(pais.nombre for pais in self.planeta if pais.esta_infectado)) paises_muertos = ListaLigada(*(pais.nombre for pais in self.planeta if pais.esta_muerto)) vmis = "Vivos/Muertos: {0}/{2}\nSanos/Infectados: {3}/{1}".format(self.planeta.vivos, self.planeta.infectados, self.planeta.muertos, self.planeta.sanos) status = vmis + "\nPaises Limpios:\n" + "\n".join(paises_limpios) + "\nPaises Infectados:\n" + "\n".join( paises_infectados) + "\nPaises Muertos: \n" + "\n".join(paises_muertos) print(status) input("<Presione Enter para continuar>") def pasar_dia(self): # tiene que considerar muertes de humanos, infecciones de humanos, # traslado de la infeccion a otro pais, mejora de la cura, # traslado de la cura, cerrar aeropuertos o fronteras # y entrega de mascarillas infectados_iniciales = self.planeta.infectados muertos_iniciales = self.planeta.muertos cerraron_aeropuertos = ListaLigada() cerraron_fronteras = ListaLigada() entrego_mascarillas = ListaLigada() for pais in self.planeta: pais.gob.formar_cola(pais) try: medidas = pais.gob.cola[0:3] for i in range(3): pais.gob.cola.pop(0) except IndexError: medidas = pais.gob.cola[0:] pais.gob.cola.clear() for medida in medidas: if medida.nombre == "Cerrar aeropuertos": for otro in self.planeta: if otro.nombre in pais.aeropuerto: otro.aeropuerto.remove(pais.nombre) pais.aeropuerto.clear() cerraron_aeropuertos.append(pais.nombre) elif medida.nombre == "Cerrar fronteras": for otro in self.planeta: if otro.nombre in pais.vecinos: otro.vecinos.remove(pais.nombre) pais.vecinos.clear() cerraron_fronteras.append(pais.nombre) elif medida.nombre == "Abrir fronteras": pais.aeropuerto, pais.vecinos = pais.respaldos for otro in self.planeta: if otro.nombre in pais.vecinos: otro.vecinos.append(pais.nombre) elif otro.nombre in pais.aeropuerto: otro.aeropuerto.append(pais.nombre) elif medida.nombre == "Mandar mascarillas": pais.infeccion.contagiosidad *= 0.3 entrego_mascarillas.append(pais.nombre) pais.muerte() pais.contagio_interno() self.planeta.descubrimiento_infeccion() muertos_dia = self.planeta.muertos - muertos_iniciales infectados_dia = self.planeta.infectados - infectados_iniciales datos_dia = ListaLigada("Infectados del dia: {}".format(infectados_dia), "Muertos del dia : {}".format(muertos_dia)) contagio_paises = self.planeta.contagio_entre_paises() if len(contagio_paises[0]) > 0 and len(contagio_paises)[1] > 0: for nombre_pais, otro_pais in contagio_paises: print("{0} contagio a {1}".format(nombre_pais, otro_pais)) contagio_paises = contagio_paises[0].msort() cerraron_aeropuertos = cerraron_aeropuertos.msort() cerraron_fronteras = cerraron_fronteras.msort() entrego_mascarillas = entrego_mascarillas.msort() if self.planeta.cura >= 100 and not self.planeta.implantado: self.planeta.implantar_cura() if self.planeta.descubierto: self.planeta.progreso_cura() self.planeta.actualizar_promedio() self.sucesos_dia = "\n".join(datos_dia) + "\nPaises infectados hoy:\n " + "\n".join(contagio_paises) + \ "\nPaises que cerraron fronteras:\n" + "\n".join(cerraron_fronteras) + \ "\nPaises que cerraron aeropuerto: \n" + "\n".join(cerraron_aeropuertos) + "\nPaises que" \ " repartieron mascarillas: \n" + "\n".join(entrego_mascarillas) def verificar_int(variable, menu=False, posibles="1 o 2", lista_posibles=(1, 2)): def sacar_espacio(s): i = 0 resultado = "" while i < len(s): if s[i] != " ": resultado = resultado + s[i] i += 1 return resultado algo = "" while not algo.isdecimal(): algo = input("Ingrese {}: ".format(variable)) algo = sacar_espacio(algo) if not algo.isdecimal(): print("ERROR, debes ingresar un número entero") else: if not menu: print("{} se ingreso correctamente".format(variable)) elif int(algo) not in lista_posibles: print("Debes ingresar {}".format(posibles)) algo = "" return int(algo) if __name__ == "__main__": juego = Partida() juego.menu()
cdf6b00aca3cf129335b0a604a7725a9998cc5bb
AkankshaKaple/Python_Data_Structures
/list/samllest_element_list.py
222
4.15625
4
#This is the program to find the smallest element in the list list = [11,13,4,15,6,27,28,1] j = len(list) min_val = list[0] for i in range(0,len(list)): if min_val > list[i]: min_val = list[i] print(min_val)
ef7db260c7c1268f6bbc62fd00abfaf9c907007a
AlexMenor/practicas_aprendizaje_automatico
/p2/p2.py
20,660
3.515625
4
#!/usr/bin/env python # coding: utf-8 # # Práctica 2 de AA # ## Ejercicio 1 import numpy as np import matplotlib.pyplot as plt # Fijamos la semilla np.random.seed(4) def simula_unif(N, dim, rango): return np.random.uniform(rango[0],rango[1],(N,dim)) def simula_gaus(N, dim, sigma): media = 0 out = np.zeros((N,dim),np.float64) for i in range(N): # Para cada columna dim se emplea un sigma determinado. Es decir, para # la primera columna (eje X) se usará una N(0,sqrt(sigma[0])) # y para la segunda (eje Y) N(0,sqrt(sigma[1])) out[i,:] = np.random.normal(loc=media, scale=np.sqrt(sigma), size=dim) return out def simula_recta(intervalo): points = np.random.uniform(intervalo[0], intervalo[1], size=(2, 2)) x1 = points[0,0] x2 = points[1,0] y1 = points[0,1] y2 = points[1,1] # y = a*x + b a = (y2-y1)/(x2-x1) # Calculo de la pendiente. b = y1 - a*x1 # Calculo del termino independiente. return a, b # Esta función separa los datos (matrix) en vectores, uno por cada columna def getListForEachDimension(points): return points[:,0], points[:,1] #Imprimimos la nube de puntos def printCloudOfPoints(points, title): x, y = getListForEachDimension(points) fig, ax = plt.subplots() ax.scatter(x,y) ax.set_title(title) plt.show() # EJERCICIO 1 a) x = simula_unif(50, 2, [-50,50]) printCloudOfPoints(x, "Distribución de puntos uniforme") input('Pulse cualquier tecla para continuar') # EJERCICIO 1 b) x = simula_gaus(50, 2, np.array([5,7])) printCloudOfPoints(x, "Distribución de puntos Gaussiana") input('Pulse cualquier tecla para continuar') # Funciones necesarias para el apartado def sign(x): if x >= 0: return 1 else: return -1 def f2(x,y,a,b): valueUnsigned = y - a*x - b return sign(valueUnsigned) # Lista de etiquetas dados los datos y los parámetros # de la recta para poder clasificarlos def getLabels(x,a,b): labels = [] for i in range(len(x)): labels.append(f2(x[i][0], x[i][1],a,b)) return labels # Devuelve puntos generados para pintar la función en la gráfica def getPointsFromFunction(f): puntosx = list(np.arange(-50,50,1)) puntosy = [] for x in puntosx: puntosy.append(f(x)) return puntosx, puntosy # Separa los puntos según las labels # para que sea más fácil # su impresión en matplotlib def getPositivesAndNegatives(x,labels): positives = [] negatives = [] for xn, l in zip(x, labels): if l == 1: positives.append(xn) else: negatives.append(xn) return positives, negatives # Función para imprimir los puntos con su clase y la recta que los clasifica def printPointsWithClassificationF2(x, labels, f): fig, ax = plt.subplots() positives, negatives = getPositivesAndNegatives(x,labels) x,y = getListForEachDimension(np.array(positives)) ax.scatter(x,y, c="blue", label="Positivos") x,y = getListForEachDimension(np.array(negatives)) ax.scatter(x,y, c="orange", label="Negativos") ax.legend() x,y = getPointsFromFunction(f) ax.plot(x,y) ax.set_ylim(-50,50) ax.set_xlim(-50,50) plt.show() ## EJERCICIO 2 a) np.random.seed(0) # Generamos los puntos x = simula_unif(50, 2, [-50,50]) #Generamos a y b a,b = simula_recta([-50,50]) # Obtenemos las clases labels = getLabels(x,a,b) # Mostramos la gráfica printPointsWithClassificationF2(x, labels, lambda x:a*x + b) input('Pulse cualquier tecla para continuar') # Para añadir estrictamente el ruido que se pide def addNoiseToLabels(labels): numOfPositives = labels.count(1) positivesToDelete = numOfPositives * 0.1 positivesToBecameNegatives = [] numOfNegatives = labels.count(-1) negativesToDelete = numOfNegatives * 0.1 negativesToBecamePositives = [] while (positivesToDelete > 0): index = np.random.randint(0, len(labels)-1) if labels[index] == 1: positivesToBecameNegatives.append(index) positivesToDelete-=1 while (negativesToDelete > 0): index = np.random.randint(0, len(labels)-1) if labels[index] == -1: negativesToBecamePositives.append(index) negativesToDelete-=1 for i in positivesToBecameNegatives: labels[i] = -1 for i in negativesToBecamePositives: labels[i] = 1 ## EJERCICIO 2 b) addNoiseToLabels(labels) # Mostramos la gráfica printPointsWithClassificationF2(x, labels, lambda x:a*x + b) input('Pulse cualquier tecla para continuar') # FUNCIÓN DADA EN LA PLANTILLA def plot_datos_cuad(X, y, fz, title='Point cloud plot', xaxis='x axis', yaxis='y axis'): #Preparar datos min_xy = X.min(axis=0) max_xy = X.max(axis=0) border_xy = (max_xy-min_xy)*0.01 #Generar grid de predicciones xx, yy = np.mgrid[min_xy[0]-border_xy[0]:max_xy[0]+border_xy[0]+0.001:border_xy[0], min_xy[1]-border_xy[1]:max_xy[1]+border_xy[1]+0.001:border_xy[1]] grid = np.c_[xx.ravel(), yy.ravel(), np.ones_like(xx).ravel()] pred_y = fz(grid) # pred_y[(pred_y>-1) & (pred_y<1)] pred_y = np.clip(pred_y, -1, 1).reshape(xx.shape) #Plot f, ax = plt.subplots(figsize=(8, 6)) contour = ax.contourf(xx, yy, pred_y, 50, cmap='RdBu',vmin=-1, vmax=1) ax_c = f.colorbar(contour) ax_c.set_label('$f(x, y)$') ax_c.set_ticks([-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1]) ax.scatter(X[:, 0], X[:, 1], c=y, s=50, linewidth=2, cmap="RdYlBu", edgecolor='white') XX, YY = np.meshgrid(np.linspace(round(min(min_xy)), round(max(max_xy)),X.shape[0]),np.linspace(round(min(min_xy)), round(max(max_xy)),X.shape[0])) positions = np.vstack([XX.ravel(), YY.ravel()]) ax.contour(XX,YY,fz(positions.T).reshape(X.shape[0],X.shape[0]),[0], colors='black') ax.set( xlim=(min_xy[0]-border_xy[0], max_xy[0]+border_xy[0]), ylim=(min_xy[1]-border_xy[1], max_xy[1]+border_xy[1]), xlabel=xaxis, ylabel=yaxis) plt.title(title) plt.show() # Lista de etiquetas dados los datos y la función para clasificarlos def getLabelsFromAnyF(x,f): labels = [] for i in range(len(x)): labels.append(sign(f(x[i][0], x[i][1]))) return labels labels = getLabelsFromAnyF(x, lambda x,y: (x-10)**2 + (y- 20)**2 - 400) addNoiseToLabels(labels) plot_datos_cuad(x,labels, lambda x : (x[:, 0] - 10) ** 2 + (x[:, 1] - 20) ** 2 - 400) input('Pulse cualquier tecla para continuar') labels = getLabelsFromAnyF(x, lambda x,y: 0.5*(x+10)**2 + (y- 20)**2 - 400) addNoiseToLabels(labels) plot_datos_cuad(x,labels, lambda x : 0.5 * (x[:, 0] + 10) ** 2 + (x[:, 1] - 20) ** 2 - 400) input('Pulse cualquier tecla para continuar') labels = getLabelsFromAnyF(x, lambda x,y: 0.5*(x-10)**2 - (y+ 20)**2 - 400) addNoiseToLabels(labels) plot_datos_cuad(x,labels, lambda x : 0.5 * (x[:, 0] - 10) ** 2 - (x[:, 1] + 20) ** 2 - 400) input('Pulse cualquier tecla para continuar') labels = getLabelsFromAnyF(x, lambda x,y: y - 20 * x **2 - 5*x + 3) addNoiseToLabels(labels) plot_datos_cuad(x,labels, lambda x : x[:, 1] - 20 * x[:,0]**2 - 5*x[:,0] + 3) input('Pulse cualquier tecla para continuar') # ## Ejercicio 2 #Añadimos un uno como primer elemento def addOneAsFirstElement(x_original): x = np.zeros((len(x_original),3), dtype=float) for i in range(len(x_original)): x[i][0] = 1 x[i][1] = x_original[i][0] x[i][2] = x_original[i][1] return x #Función de error para problemas de clasificación def error(data, labels, w): # x (dot) wt # n x 3 | 3 x 1 -> n x 1 guessUnsigned = data.dot(w.reshape(3,-1)) count = 0 # Contamos los puntos mal clasificados for i in range(len(guessUnsigned)): if labels[i] != sign(guessUnsigned[i]): count += 1 # Devolvemos el promedio return count / len(data) # PLA def pla(data, labels, max_iter, vini): # Copiamos la w inicial w = vini.copy() hasConverged = False pasadas = 0 # Si no hemos llegado al número máximo # de pasadas y no ha convergido... # SEGUIMOS! while pasadas != max_iter and not hasConverged: hasConverged = True for i in range(len(data)): guess = sign(w.dot(data[i].reshape(-1,1))) # En caso de fallar la predicción # ajustamos los pesos if guess != labels[i]: hasConverged = False w += labels[i] * data[i] pasadas += 1 return w, pasadas # Función para pintar el ajuste def printFit(x, labels, w): positives, negatives = getPositivesAndNegatives(x,labels) fig, ax = plt.subplots() x,y = getListForEachDimension(np.array(positives)) ax.scatter(x,y, c="blue", label="Positivos") x,y = getListForEachDimension(np.array(negatives)) ax.scatter(x,y, c="orange", label="Negativos") puntosDeRectaX = np.arange(-50,50) puntosDeRectaY = [] for i in range(len(puntosDeRectaX)): puntosDeRectaY.append((-w[0]-w[1]*puntosDeRectaX[i])/w[2]) ax.plot(puntosDeRectaX, puntosDeRectaY, label="Ajuste") ax.legend() ax.set_xlim(-50,50) ax.set_ylim(-50,50) plt.show() np.random.seed(44) # Generamos puntos en [-50,50] xOriginal = simula_unif(50, 2, [-50,50]) # Generamos una recta para clasificarlos a,b = simula_recta([-50,50]) # Obtenemos sus etiquetas dados los parámetros que acabamos de generar labels = getLabels(xOriginal,a,b) x = addOneAsFirstElement(xOriginal) # Ajustamos w, pasadas = pla(x, labels, 500, np.zeros(3)) error_obtenido = error(x, labels, w) print("PLA - Puntos linealmente separables - Con un vector de ceros") print("Coordenadas",w) print("Error", error_obtenido) print("Iteraciones", pasadas) printFit(xOriginal, labels, w) input('Pulse cualquier tecla para continuar') error_sum = 0 numOfIterations = [] for i in range(10): # De esta forma tenemos un vector en vez de una matriz de una fila # más cómodo para la función de printFit pesos_iniciales= np.random.uniform(0.0,1,(3,1)).reshape(-1) w, pasadas = pla(x, labels, 500, pesos_iniciales) error_obtenido = error(x, labels, w) error_sum += error_obtenido numOfIterations.append(pasadas) print("PLA - Puntos linealmente separables - Puntos de arranque estocásticos") print("Error medio", error_sum / 10) print("Iteraciones de media", np.array(numOfIterations).mean()) print("Desviación típica de las iteraciones", np.array(numOfIterations).std()) input('Pulse cualquier tecla para continuar') # Probamos ahora con el etiquetado "ruidoso" addNoiseToLabels(labels) w, pasadas = pla(x, labels, 500, np.zeros(3)) error_obtenido = error(x, labels, w) print("PLA - Puntos NO linealmente separables - Con un vector de ceros") print("Coordenadas",w) print("Error", error_obtenido) print("Iteraciones", pasadas) printFit(xOriginal, labels, w) input('Pulse cualquier tecla para continuar') error_sum = 0 numOfIterations = [] for i in range(10): # De esta forma tenemos un vector en vez de una matriz de una fila # más cómodo para la función de printFit pesos_iniciales= np.random.uniform(0.0,1,(3,1)).reshape(-1) w, pasadas = pla(x, labels, 500, pesos_iniciales) error_obtenido = error(x, labels, w) error_sum += error_obtenido numOfIterations.append(pasadas) print("PLA - Puntos NO linealmente separables - Arrancando estocásticamente") print("Error medio", error_sum / 10) print("Iteraciones de media", np.array(numOfIterations).mean()) print("Desviación típica de las iteraciones", np.array(numOfIterations).std()) input('Pulse cualquier tecla para continuar') # Implemento el POCKET para ver si podemos mejorar en muestras ruidosas def pocket(data, labels, max_iter, vini): # Copiamos la w inicial w = vini.copy() hasConverged = False pasadas = 0 best_w = w.copy() best_error = error(data, labels, w) # Si no hemos llegado al número máximo # de pasadas y no ha convergido... # SEGUIMOS! while pasadas != max_iter and not hasConverged: hasConverged = True for i in range(len(data)): guess = sign(w.dot(data[i].reshape(-1,1))) # En caso de fallar la predicción # ajustamos los pesos if guess != labels[i]: hasConverged = False w += labels[i] * data[i] # Nos metemos al "pocket" la mejor # solución que hemos encontrado current_error = error(data, labels, w) if current_error < best_error: best_w = w.copy() best_error = current_error pasadas += 1 return best_w, pasadas w, pasadas = pocket(x, labels, 500, np.zeros(3)) error_obtenido = error(x, labels, w) print("PLA-POCKET, datos NO linealmente separables. Arrancando con un vector de ceros") print("Coordenadas",w) print("Error", error_obtenido) print("Iteraciones", pasadas) printFit(xOriginal, labels, w) input('Pulse cualquier tecla para continuar') # Regresión logística # Funciones de utilidad en este ejercicio ## Imprimimos los puntos obtenidos def printPointsWithClassificationLogistic(x, labels, f): positives, negatives = getPositivesAndNegatives(x,labels) fig, ax = plt.subplots() x,y = getListForEachDimension(np.array(positives)) ax.scatter(x,y, c="blue", label="Positivos") x,y = getListForEachDimension(np.array(negatives)) ax.scatter(x,y, c="orange", label="Negativos") ax.legend() x,y = getPointsFromFunction(f) ax.plot(x,y) ax.set_xlim(0,2) ax.set_ylim(0,2) plt.show() ## Imprimimos los puntos con el ajuste ## obtenido def printFitLogistic(x, labels, w): positives, negatives = getPositivesAndNegatives(x,labels) fig, ax = plt.subplots() x,y = getListForEachDimension(np.array(positives)) ax.scatter(x,y, c="blue", label="Positivos") x,y = getListForEachDimension(np.array(negatives)) ax.scatter(x,y, c="orange", label="Negativos") puntosDeRectaX = np.arange(0,20) puntosDeRectaY = [] for i in range(len(puntosDeRectaX)): puntosDeRectaY.append((-w[0]-w[1]*puntosDeRectaX[i])/w[2]) ax.plot(puntosDeRectaX, puntosDeRectaY, label="Ajuste") ax.legend() ax.set_xlim(0,2) ax.set_ylim(0,2) plt.show() def sgd(x, y, eta, cambio_minimo, w=np.zeros(3)): cambio_actual = np.inf indices = np.arange(0, len(x)) while cambio_actual >= cambio_minimo: # Nos quedamos con el w pre-iteración # para poder hacer el incremento después w_anterior = w.copy() # Permutación np.random.shuffle(indices) for i in indices: xn = x[i] yn = y[i] gt = -( yn * xn ) / ( 1 + np.exp(yn * np.dot(w,xn))) w -= eta * gt cambio_actual = np.linalg.norm(w_anterior - w) return w def errorSgd(x,y,w): error = 0 for xn, yn in zip(x, y): error += np.log(1 + np.exp(-yn * w.dot(xn))) return error / len(x) ## Recta que corta el cuadro [0,2] X [0,2] a,b = simula_recta([0,2]) ## Puntos en ese cuadro, probabilidad uniforme xOriginal = simula_unif(100,2,[0,2]) # Obtenemos las clases y = getLabels(xOriginal,a,b) printPointsWithClassificationLogistic(xOriginal, y, lambda x: a*x+b) input('Pulse cualquier tecla para continuar') # Añadimos el 1 al principio x = addOneAsFirstElement(xOriginal) # Ajustamos w = sgd(x,y,0.01, 0.01) printFitLogistic(xOriginal, y,w) print("Ajuste de regresión logística con datos linealmente separables") print("Error Ein", errorSgd(x,y,w)) input('Pulse cualquier tecla para continuar') xOriginalNuevasMuestras = simula_unif(1000,2,[0,2]) # Obtenemos las clases yNuevasMuestras = getLabels(xOriginalNuevasMuestras, a,b) printPointsWithClassificationLogistic(xOriginalNuevasMuestras, yNuevasMuestras, lambda x: a*x+b) input('Pulse cualquier tecla para continuar') # Añadimos el 1 al principio xNuevasMuestras = addOneAsFirstElement(xOriginalNuevasMuestras) # Imprimimos los nuevos puntos con el ajuste que # obtuvimos antes printFitLogistic(xOriginalNuevasMuestras, yNuevasMuestras,w) print("Ajuste de regresión logística con datos linealmente separables") print("Error Eout", errorSgd(xNuevasMuestras,yNuevasMuestras,w)) input('Pulse cualquier tecla para continuar') # ## EJERCICIO 3 # Funcion para leer los datos def readData(file_x, file_y, digits, labels): # Leemos los ficheros datax = np.load(file_x) datay = np.load(file_y) y = [] x = [] # Solo guardamos los datos cuya clase sea la digits[0] o la digits[1] for i in range(0,datay.size): if datay[i] == digits[0] or datay[i] == digits[1]: if datay[i] == digits[0]: y.append(labels[0]) else: y.append(labels[1]) x.append(np.array([1, datax[i][0], datax[i][1]])) x = np.array(x, np.float64) y = np.array(y, np.float64) return x, y def printEjer3(x,y, w = [], training = True): if training: title = "Dígitos manuscritos (TRAINING)" else: title = "Dígitos manuscritos (TEST)" #mostramos los datos fig, ax = plt.subplots() ax.plot(np.squeeze(x[np.where(y == -1),1]), np.squeeze(x[np.where(y == -1),2]), 'o', color='red', label='4') ax.plot(np.squeeze(x[np.where(y == 1),1]), np.squeeze(x[np.where(y == 1),2]), 'o', color='blue', label='8') ax.set(xlabel='Intensidad promedio', ylabel='Simetria', title=title) ax.set_xlim((0, 1)) if len(w) != 0: puntosDeRectaX = np.arange(0,1,0.01) puntosDeRectaY = [] for i in range(len(puntosDeRectaX)): puntosDeRectaY.append((-w[0]-w[1]*puntosDeRectaX[i])/w[2]) ax.plot(puntosDeRectaX, puntosDeRectaY, label="Ajuste") ax.legend() ax.set_ylim(-7,-1) plt.legend() plt.show() # Lectura de los datos de entrenamiento x, y = readData('datos/X_train.npy', 'datos/y_train.npy', [4,8], [-1,1]) # Lectura de los datos para el test x_test, y_test = readData('datos/X_test.npy', 'datos/y_test.npy', [4,8], [-1,1]) printEjer3(x,y, training=True) input('Pulse cualquier tecla para continuar') printEjer3(x_test,y_test,training=False) input('Pulse cualquier tecla para continuar') # Entreno con algoritmo de regresión logística w = sgd(x,y,0.01,0.01) print("Aplicando SGD logistic regression") # Ein print("Error Ein de regresión logística", errorSgd(x,y,w)) ein_sgd_solo = error(x,y,w) print("Error Ein de clasificación", ein_sgd_solo) printEjer3(x,y,w,True) input('Pulse cualquier tecla para continuar') # Eout print("Error Eout de regresión logística", errorSgd(x_test,y_test,w)) etest_sgd_solo = error(x_test,y_test,w) print("Error Eout de clasificación", etest_sgd_solo) printEjer3(x_test,y_test,w,False) input('Pulse cualquier tecla para continuar') # Aprovecho el w que he obtenido en el paso anterior y lo utilizo como pesos iniciales del PLA-Pocket. w, pasadas = pocket(x,y,1000,w) print("Aplicando PLA-Pocket después de logistic regression") print("Error Ein ", error(x,y,w)) printEjer3(x,y,w,True) input('Pulse cualquier tecla para continuar') print("Error Eout ", error(x_test,y_test,w)) printEjer3(x_test,y_test,w,False) input('Pulse cualquier tecla para continuar') w, pasadas = pocket(x,y,1000,np.zeros(3)) ein_pla_solo = error(x,y,w) print("Aplicando solo PLA-POCKET, arrancando con ceros") print("Error Ein ", ein_pla_solo) printEjer3(x,y,w,True) input('Pulse cualquier tecla para continuar') etest_pla_solo = error(x_test,y_test,w) print("Error Eout ", etest_pla_solo) printEjer3(x_test,y_test,w,False) input('Pulse cualquier tecla para continuar') w = sgd(x,y,0.01,0.01,w) print("Aplicando SGD logistic regression al w obtenido con PLA-Pocket") # Ein print("Error Ein de regresión logística", errorSgd(x,y,w)) ein_pla_sgd = error(x,y,w) print("Error Ein de clasificación", ein_pla_sgd) printEjer3(x,y,w,True) input('Pulse cualquier tecla para continuar') # Eout print("Error Eout de regresión logística", errorSgd(x_test,y_test,w)) etest_pla_sgd = error(x_test,y_test,w) print("Error Eout de clasificación", error(x_test,y_test,w)) printEjer3(x_test,y_test,w,False) input('Pulse cualquier tecla para continuar') N = len(x) N_test = len(x_test) print("Cotas para EOUT") cota_eout_sgd_solo = ein_sgd_solo + np.sqrt(np.log(2/0.05)/(2*N)) cota_etest_sgd_solo = etest_sgd_solo + np.sqrt(np.log(2/0.05)/(2*N_test)) print("Eout para sgd solo (utilizando ein) es: ", cota_eout_sgd_solo) print("Eout para sgd solo (utilizando etest) es: ", cota_etest_sgd_solo) print("\n") cota_eout_pla_solo = ein_pla_solo + np.sqrt(np.log(2/0.05)/(2*N)) cota_etest_pla_solo = etest_pla_solo + np.sqrt(np.log(2/0.05)/(2*N_test)) print("Eout para PLA solo (utilizando ein) es: ", cota_eout_pla_solo) print("Eout para PLA solo (utilizando etest) es: ", cota_etest_pla_solo) print("\n") cota_eout_pla_sgd = ein_pla_sgd + np.sqrt(np.log(2/0.05)/(2*N)) cota_etest_pla_sgd = etest_pla_sgd + np.sqrt(np.log(2/0.05)/(2*N_test)) print("Eout para PLA-SGD (utilizando ein) es: ", cota_eout_pla_sgd) print("Eout para PLA-SGD (utilizando etest) es: ", cota_etest_pla_sgd)
d629a90b679bfe39cbb85b9f46cc697f12024b7a
triggeron/DeepLearningProjects
/porto-seguro-safe-driver-prediction/safe_driver_model.py
2,986
3.546875
4
import torch from torch import nn, optim import torch.nn.functional as F import matplotlib.pyplot as plt import numpy as np class Network(nn.Module): def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5): ''' Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input layer output_size: integer, size of the output layer hidden_layers: list of integers, the sizes of the hidden layers ''' super().__init__() self.input_size = input_size self.output_size = output_size self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Input to a hidden layer self.hidden_layers = nn.ModuleList([nn.Linear(input_size, hidden_layers[0])]) # Add a variable number of more hidden layers layer_sizes = zip(hidden_layers[:-1], hidden_layers[1:]) self.hidden_layers.extend([nn.Linear(h1, h2) for h1, h2 in layer_sizes]) self.relu = nn.ReLU() #hidden to output layer self.output = nn.Linear(hidden_layers[-1], output_size) self.dropout = nn.Dropout(p=drop_p) def forward(self, x): ''' Forward pass through the network, returns the output logits ''' for each in self.hidden_layers: x = F.relu(each(x)) x = self.dropout(x) x = self.output(x) return F.sigmoid(x) def train(model, X, y, epochs=100, print_every = 5): X, y = X.to(model.device), y.to(model.device) optimizer = optim.Adam(model.parameters(), model.learning_rate) criterion = nn.BCELoss() running_loss = 0 steps = 0 costs = [] for epoch in range(epochs): steps += 1 #clear gradients optimizer.zero_grad() output = model.forward(X) loss = criterion(output.float(), y.float()) loss.backward() optimizer.step() running_loss += loss.item() costs.append(loss.item()) if steps % print_every == 0: print("Epoch: {}/{}.. ".format(epoch+1, epochs), "Training Loss: {:.3f}.. ".format(running_loss/print_every)) running_loss = 0 # plot the cost plt.plot(np.squeeze(costs)) plt.ylabel('cost') plt.xlabel('iterations (per hundreds)') plt.title("Learning rate =" + str(model.learning_rate)) plt.show() def predict(model, X_test, y_test): accuracy=0 test_loss=0 model.eval() with torch.no_grad(): X_test, y_test = X_test.to(model.device), y_test.to(model.device) logps = model.forward(X_test) y_pred = torch.round(logps) correct = 0 for i in range(y_pred.shape[0]): if y_pred[i] == y_test[i]: correct += 1 accuracy = ((correct/y_pred.shape[0])*100) model.train() return y_pred, accuracy ## Global parameters learning_rate = 0.02
021b6e2f0cd03ee7e0b708b952c72ed8c2d41058
SOURADEEP-DONNY/WORKING-WITH-PYTHON
/xc.py
76
3.640625
4
n=int(input()) s=0 for i in range(n+1): s=s+i avg=s//n print(avg)
62ffebfe2a1f8845c8349d2095196472c3c87e70
thioaana/DataStructuresAndAlgorithms
/AlgorithmsOnGraphs/Week4PathsInGraphs/NegativeCycle.py
2,555
3.578125
4
#Uses python3 class Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = [] self.count = 0 def importEdge(self, u, v, w): self.graph.append([u, v, w]) # The function detects negative weight cycle def isNegativeCycle3(self, src): # Step 1: Initialization dist = [float("Inf")] * self.V dist[src] = 0 # Step 2: Relax all edges |V| - 1 times for _ in range(self.V - 1): # if not sameValues : return False # Update dist value and parent index of the adjacent vertices of # the picked vertex. Consider only those vertices which are still in # queue for u, v, w in self.graph: self.count += 1 if dist[u] != float("Inf") and dist[u] + w < dist[v]: dist[v] = dist[u] + w # Step 3: check for negative-weight cycles for u, v, w in self.graph: if dist[u] != float("Inf") and dist[u] + w < dist[v]: return True def hasNegativeCycle(self): if self.isNegativeCycle(self.V - 1) : return 1 return 0 if __name__ == '__main__': inp = input().split() n = int(inp[0]) m = int(inp[1]) edges = [] for i in range(m): inp = input().split() edges.append((int(inp[0]), int(inp[1]), int(inp[2]))) myGraph = Graph(n + 1) for (a, b, w) in edges: myGraph.importEdge(a - 1, b - 1, w) for i in range(n): myGraph.importEdge(n + 1 - 1, i, 0) print(myGraph.hasNegativeCycle()) # # Testing ........................... # import random # import time # n = 1000 # m = 10000 # kkk = 0 # # myGraph = Graph(n) # while kkk < n * m : # start = time.time() # myGraph = Graph(n+1) # lList = [] # for i in range(1, m+1) : # r1 = random.randint(1, n) # r2 = random.randint(1, n) # while (r1, r2) in lList or r1==r2: # r1 = random.randint(1, n) # r2 = random.randint(1, n) # lList.append((r1, r2)) # myGraph.importEdge(r1 - 1, r2 - 1, random.randint(-1000, 1000)) # for i in range(n): # myGraph.importEdge(n + 1 - 1, i, 0) # # print(myGraph.hasNegativeCycle3()) # print(myGraph.hasNegativeCycle2()) # Additional node # end = time.time() # print(n, m, myGraph.count, end-start) # kkk = myGraph.count
674bc94ea7171bb2cf1cad0feb41f83e9331d4c6
vegavazquez/2018-19-PNE-practices
/client-server/client.py
539
3.640625
4
import socket # SERVER IP, PORT IP = "212.128.253.64" PORT = 8080 # First, create the socket # We will always use this parameters: AF_INET y SOCK_STREAM s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # establish the connection to the Server (IP, PORT) s.connect((IP, PORT)) # Send data. No strings can be send, only bytes # It necesary to encode the string into bytes s.send(str.encode("HELLO FROM THE CLIENT!!!")) # Receive data from the server msg = s.recv(2048).decode("utf-8") print("MESSAGE FROM THE SERVER:\n") print(msg)
c4e8da0b87f7f28183e19fdb5d12df95304e69ff
jasonusaco/Leetcode-Practice
/DP&Recursion/9.5.py
352
3.5
4
""" """ class Permutation: def getPermutation(self, A): if not A: return [] elif len(A) == 1: return [A] res = [] for i,c in enumerate(A): for s in self.getPermutation(A[:i]+A[i+1:]): res.append(c+s) res.sort(reverse=True) return res
23f5bf3ce3f6c68593039f53ab918bcb946c19f6
yosiasz/myPython
/Excel/math.py
440
3.5625
4
import pandas as pd from IPython.display import display pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.width', None) A = pd.read_excel("./data.xlsx", sheet_name=0) df = A[ (A.Tmax > 0) & (A.Tmin > 0)] #Average df['avg'] = df.iloc[:,1:3].mean(axis=1) #Subtraction df['minus'] = df['Tmax'] - df['Tmin'] #Addition df['Sum'] = df['Tmax'] + df['Tmin'] print(df)
52c94667cfbff24d3cdef69dcf1d1c6724132b04
Bishopbhaumik/python_test
/oop_7.py
773
3.75
4
class Phone: def __init__(self,brand,model_name,price): self.brand=brand self.model_name=model_name # self.__price=price self.price=max(price,0) # self.complete_sp=f"{self.brand} {self.model_name} and price {self.price}" def make_a_call(self,phone_no): print(f"calling {phone_no}......") def full_name(self): return f"{self.brand} {self.model_name}" def __str__(self): return f"{self.brand} {self.model_name} and price is {self.price}" def __repr__(self): return f"Phone(\'{self.brand}' ,\'{self.model_name}',{self.price})" def __len__(self): return len(self.full_name()) Phone1=Phone('Nokia','1150',8000) print(len(Phone1)) print(Phone1)
9eb6603a5e2f9076599d12661b1695b89861f65a
jaresj/Python-Coding-Project
/Check Files Project/check_files_func.py
2,635
3.609375
4
import os import sqlite3 import shutil from tkinter import * import tkinter as tk from tkinter.filedialog import askdirectory import check_files_main import check_files_gui def center_window(self, w, h): # pass in the tkinter frame (master) reference and the w and h # get user's screen width and height screen_width = self.master.winfo_screenwidth() screen_height = self.master.winfo_screenheight() # calculate x and y coordinates to paint the app centered on the user's screen x = int((screen_width/2) - (w/2)) y = int((screen_height/2) - (h/2)) centerGeo = self.master.geometry('{}x{}+{}+{}'.format(w, h, x, y)) # catch if the user's clicks on the windows upper-right 'X' to ensure they want to close def ask_quit(self): if messagebox.askokcancel("Exit program", "Okay to exit application?"): #this closes app self.master.destroy() os._exit(0) def source_directory(self): self.folder1 = askdirectory() self.txt_browse1.insert(0,self.folder1) def destination_directory(self): self.folder2 = askdirectory() self.txt_browse2.insert(0,self.folder2) def move_files(self): for filename in os.listdir(path=self.folder1): if filename.endswith('.txt'): shutil.move(os.path.join(self.folder1, filename), (self.folder2)) create_db(self) continue else: continue #============================================================================ def create_db(self): conn = sqlite3.connect('check_files.db') with conn: cur = conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS tbl_files(\ ID INTEGER PRIMARY KEY AUTOINCREMENT, \ col_txtFiles TEXT, \ col_modFiles TEXT \ )") conn.commit() conn.close() conn = sqlite3.connect('check_files.db') fileList = os.listdir(path=self.folder2) modFiles = os.path.getmtime(self.folder2) with conn: cur = conn.cursor() for items in fileList: if items.endswith('.txt'): cur.execute('INSERT INTO tbl_files(col_txtFiles,col_modFiles) VALUES (?,?)', \ (items,modFiles)) conn.commit conn.close() conn = sqlite3.connect('check_files.db') with conn: cur = conn.cursor() cur.execute("SELECT * FROM tbl_files") varFiles = cur.fetchall() for item in varFiles: print(item) if __name__ == "__main__": pass
1c37469179a06a3d8cff34bacedb29f928db0cac
Titing1234/Titing_Praktikum-Pewarisan
/pewarisan.py
852
3.84375
4
class Buah(object): def __init__ (self, a, k, m): self.apel = a self.kelapa = k self.mangga = m def jumlahBuah(self): return self.apel + self.kelapa + self.mangga def cetakData(self): print("Apel\t: ", self.apel) print("Kelapa\t: ", self.kelapa) print("Mangga\t: ", self.mangga) def cetakJB(self): print("Total dari semua buah diatas\t= ", self.jumlahBuah()) class WarnaBuah(Buah): def __init__(self, a, k, m, w): self.apel = a self.kelapa = k self.mangga = m self.warna = w def cetakData(self): print("Apel\t: ", self.apel) print("Kelapa\t: ", self.kelapa) print("Mangga\t: ", self.mangga) print("Warna dari semua buah tersebut adalah", self.warna) def main(): wb1 = WarnaBuah (16, 4, 40, "biru") wb1.cetakData() wb1.cetakJB() if __name__ == "__main__": main()
5a3e7947d7c4957b25b605b67c2b668d430a18ff
hasnainhs/Data-Science
/Machine Learning for Data Science/Linear Regression/MultipleLinearRegression.py
3,776
3.59375
4
""" @author: Hasnain """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def cost_function(X, y, weights): m = len(y) predictions = np.dot(X,weights) J = np.sum((predictions-y)**2)/(2*m) return J def gradient_descent(X, y, alpha, epochs, weights): costs = np.zeros(epochs) m = len(y) for i in range(epochs): hypothesis = np.dot(X,weights) error = hypothesis - y slope = np.dot(error, X)/m #updating parameters weights = weights - alpha*slope costs[i] = cost_function(X,y,weights) return weights, costs if __name__=='__main__': df = pd.read_csv("ex1data2.txt", sep=",",header=None) df.columns = ["size_ft","bedrooms","price"] df['bias'] = 1 X_ne = np.array(df[['bias','size_ft','bedrooms']].values) y_ne = y = np.array(df[['price']].values).flatten() #feature Normalization mean = df['size_ft'].mean() stdev = df['size_ft'].std() df['size_ft']=(df['size_ft']-mean)/stdev df['price']=df['price']/1000 #splitting X = np.array(df[['bias','size_ft','bedrooms']].values) y = np.array(df[['price']].values).flatten() weights = np.array([0,0,0]) alphas = [0.001, 0.003,0.01,0.03,0.1] max_iter = 50 plt.figure() iter_ = np.arange(max_iter) for lr in alphas: (gd_weights, costs) = gradient_descent(X,y,lr,max_iter,weights) plt.plot(iter_,costs,'-') plt.legend(alphas, loc='upper right') plt.show() # running gradient descent epochs = 1500 alpha = 0.1 (gd_weights, costs) = gradient_descent(X,y,alpha,epochs,weights) # solving with normal equations ne_weights = np.matmul(X_ne.T,X_ne) ne_weights = np.linalg.pinv(ne_weights) ne_weights = np.matmul(ne_weights,X_ne.T) ne_weights = np.matmul(ne_weights,y_ne) ne_weights = ne_weights.flatten() ### prediction ### # with normal equation weights ne_pred = ne_weights[0] + ne_weights[1]*1650 + ne_weights[2]*3 # = 293081.464 # with gradient desscent weights x = (1650 - mean)/stdev gd_pred = gd_weights[0] + gd_weights[1]*x + gd_weights[2]*3 gd_pred = gd_pred*1000 # = 293023.081 x_pred = np.linspace(X[:,1].min(), X[:,1].max(), 30) y_pred = np.linspace(X[:,2].min(), X[:,2].max(), 30) xx_pred, yy_pred = np.meshgrid(x_pred, y_pred) model_viz = np.array([xx_pred.flatten(), yy_pred.flatten()]).T model_viz = np.c_[np.ones(len(model_viz)),model_viz] predicted = np.dot(model_viz,gd_weights) plt.style.use('default') fig = plt.figure(figsize=(10, 3)) ax1 = fig.add_subplot(131, projection='3d') ax2 = fig.add_subplot(132, projection='3d') axes = [ax1, ax2] for ax in axes: ax.plot(X[:,1], X[:,2], y, color='k', zorder=15, linestyle='none', marker='o', alpha=0.5) ax.scatter(xx_pred.flatten(), yy_pred.flatten(), predicted, facecolor=(0,0,0,0), s=20, edgecolor='#70b3f0') ax.set_xlabel('Size of House (Norm)', fontsize=8) ax.set_ylabel('Number of bedrooms', fontsize=8) ax.set_zlabel('Price of House', fontsize=8) ax.locator_params(nbins=4, axis='x') ax.locator_params(nbins=5, axis='x') ax1.text2D(0.2, 0.32, 'aegis4048.github.io', fontsize=13, ha='center', va='center', transform=ax1.transAxes, color='grey', alpha=0.5) ax2.text2D(0.3, 0.42, 'aegis4048.github.io', fontsize=13, ha='center', va='center', transform=ax2.transAxes, color='grey', alpha=0.5) ax1.view_init(elev=28, azim=120) ax2.view_init(elev=4, azim=80) fig.tight_layout()
35b05e8d2855e9ab1774f58665f70ffe3ec9715c
betty29/code-1
/recipes/Python/440657_Determine_functiexecutitime_Pythonic/recipe-440657.py
2,051
3.953125
4
""" Determine function execution time. >>> def f(): ... return sum(range(10)) ... >>> pytime(f) (Time to execute function f, including function call overhead). >>> 1.0/pytime(f) (Function calls/sec, including function call overhead). >>> 1.0/pytime_statement('sum(range(10))') (Statements/sec, does not include any function call overhead). """ import sys # Source code is public domain. if sys.platform == "win32": from time import clock else: from time import time as clock def pytime(f, args=(), kwargs={}, Tmax=2.0): """ Calls f many times to determine the average time to execute f. Tmax is the maximum time to spend in pytime(), in seconds. """ count = 1 while True: start = clock() if args == () and kwargs == {}: for i in xrange(count): f() elif kwargs == {}: for i in xrange(count): f(*args) else: for i in xrange(count): f(*args, **kwargs) T = clock() - start if T >= Tmax/4.0: break count *= 2 return T / count def pytime_statement(stmt, global_dict=None, Tmax=2.0, repeat_count=128): """ Determine time to execute statement (or block) of Python code. Here global_dict is the globals dict used for exec, Tmax is the max time to spend in pytime_statement(), in sec, and repeat_count is the number of times to paste stmt into the inner timing loop (this is automatically set to 1 if stmt takes too long). """ if global_dict is None: global_dict = globals() ns = {} code = 'def timed_func():' + ('\n' + '\n'.join([' '+x for x in stmt.split('\n')])) exec code in global_dict, ns start = clock() ns['timed_func']() T = clock() - start if T >= Tmax/4.0: return T elif T >= Tmax/4.0/repeat_count: return pytime(ns['timed_func'], (), {}, Tmax-T) else: code = 'def timed_func():' + ('\n' + '\n'.join([' '+x for x in stmt.split('\n')]))*repeat_count exec code in global_dict, ns return pytime(ns['timed_func'], (), {}, Tmax-T) / repeat_count
f28beb15cf3f38bb2fd6a3901f6165dea07bd8cc
Boot-Camp-Coding-Test/Programmers
/day9/problem4/[최중훈] 최대공약수와 최소공배수.py
407
3.71875
4
def solution(n, m): def gcd(n, m): # 최대공약수 찾는 재귀함수 if m == 0: return n if n < m: (n, m) == (m, n) return gcd(m, n%m) gcd_num = int(gcd(n, m)) # 최대공약수 함수를 사용해서 구한 gcd lcm_num = int(n*m / gcd_num) # 두 수를 곱하고 gcd로 나누어주면 lcm answer = [gcd_num, lcm_num] return answer
81a647cea375db2e363c14804d5e999728812e04
Spinnerka/Python-Coursera-Assignments
/Ex5_LargestSmallestNumber.py
1,045
4.21875
4
#5.2 Write a program that repeatedly prompts a user for integer numbers until # the user enters 'done'. Once 'done' is entered, print out the largest and # smallest of the numbers. If the user enters anything other than a valid # number catch it with a try/except and put out an appropriate message and # ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below. # test number 9, 41, 12, 3, 74, 15 largest = None smallest = None while True: num = input("Enter a number: ") #to exit the loop when user enters 'done' if num == 'done' : break try: number = int(num) except: print('Invalid input') continue #to find the smallest value if smallest is None: smallest = number elif number < smallest: smallest = number #to find the largest value if largest is None: largest = number elif number > largest: largest = number print("Maximum is", largest) print("Minimum is", smallest)
f8a1ce49c2bd811dfc1f9a59369e983e43031908
sreegayathri/6044_CSPP1
/CSPP1/cspp1-assignments/m5/square_root_bisection.py
219
3.8125
4
num_va = int(input()) epsilon = 0.01 low = 0 high = num_va avg = (low/high)/2 while abs(avg**2-num_va) >= epsilon: if avg**2 < num_va: low = avg else: high = avg avg = (low+high)/2 print(avg)
5bb2cd18d84a087f8419d185798f550694676567
aixiu/myPythonWork
/图灵学院/python基础/ls-15-python.py
4,450
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 变量的三种用法 class A(object): def __init__(self): self.name = 'haha' self.age = 18 a =A # 属性的三种用法 # 赋值 # 读取 # 删除 a.name = '量子' # del a.name # print(a.name) # 类属性 property # 应用场景 # 对变量除了普通的三种操作,还想增加一些附加的操作,可以通过 PROPERTY完成 class A(object): def __init__(self): self.name = 'haha' self.age = 18 # 此功能,是对类变量进行读取操作的时候执行函数功能 def fget(self): print('我被读取了') return self.name # 模拟的是对变量进行写操作的时候执行的功能 def fset(self): print('我被写入了,还有好多') self.name = '图灵学院'.format(name) # fdel 模拟的是删除变量的时候进行的操作 def fdel(self): pass # property 的四个参数顺序是固定的 # 第一个参数代表读取的时候需要调用函数 # 第二个参数代表写入的进候需要调用的函数 # 第三个是删除时需要调用的函数 name2 = property(fget, fset, fdel, '这是一个properyt的例子') a =A() print(a.name) print(a.name2) # 抽象类 # 抽象方法: 没有具体实现内容的方法成为抽象方法 # 抽象方法的主要意义是规范了子类的行为和接口 # 抽象的使用需要借助 abc 模块 # 抽象例子 class Animel(object): def sayHello(self): pass class Dog(Animel): def sayHello(self): print('闻一下对方') class Person(Animel): def sayHello(self): print('Kiss me') d = Dog() d.sayHello() p = Person() p.sayHello() # 抽象类:包含抽象方法的类叫抽象类,通常成为ABC类 # 抽象类的使用: # 抽象类可以包含抽象方法,也可以包含具体方法 # 抽象类中可以有方法,也可以有属性 # 抽象类不允许直接实例化 # 必须继承才可以使用,且继承的子类必须实现所有继承来的抽象方法 # 假定,子类没有实所有继承的抽象方法,则子类也不能实例化 # 抽象类的主要作用是设定类的标准备,以便于开发的时候具有统一的规范 # 抽象类的实现 import abc # 声明一个类并且指定当前类的元类 class Human(metaclass=abc.ABCMeta): # 定义一个抽象方法 @abc.abstractmethod def smoking(self): pass # 定义类抽象方法 @abc.abstractclassmethod def drink(): pass # 定义静态抽象方法 @abc.abstractstaticmethod def play(): pass def sleep(sefl): print('sleep...') # 自定义类 # 类其是一个类定义和各种方法的自由组合 # 可以定义类和函数,然后自己能过类直接赋值 # 借助于 MethodType 实现 # 还可以借助于 type 实现 # 利用元类实现 - MetaClass # 元类是类 # 被用来创造别的类 # 函数名可以当变量使用 def sayHello(name): print('{}你好,来一发?'.format(name)) sayHello('月月') liumang = sayHello liumang('yueyue') # 自己组装一个类 class A(object): pass def say(self): print('Saying....') say(9) A.say = say a = A() a.say() # 利用 type 造一个类 # 先定义类应该具有的成员函数 def say(self): print('Saying...') def talk(self): print('Talking...') # 用 type 来创建类 A = type('AName', (object, ), {'class_say':say, 'class_talk':talk}) # 然后可以像正常访问一样使用类 a = A() dir(a) # 元类的例子 # 元类写法是固定的,它必须继承自 type # 元类一般命名以 MetaClass结尾 class TulingMetaClass(type): # 注意以下写法 def __new__(cls, name, bases, attrs): #自己的功能 print('哈哈,我是元类') attrs['id'] = '000000' attrs['addr'] = '湖北武汉' return type.__new__(cls, name, bases, attrs) # 元类定义完成就可以使用,使用注意写法 class Teacher(object, metaclass=TulingMetaClass): pass t = Teacher() t.id
ef2a30844644e63d0b76084419e4fc174d4560b9
choroba/perlweeklychallenge-club
/challenge-183/lubos-kolouch/python/ch-1.py
519
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def remove_duplicates(lst): # Convert each list to a tuple so it can be added to a set tuples = [tuple(i) for i in lst] # Create a set to remove duplicates, then convert each tuple back to a list return [list(i) for i in set(tuples)] list1 = [[1, 2], [3, 4], [5, 6], [1, 2]] list2 = [[9, 1], [3, 7], [2, 5], [2, 5]] print(remove_duplicates(list1)) # Output: [[1, 2], [3, 4], [5, 6]] print(remove_duplicates(list2)) # Output: [[9, 1], [2, 5], [3, 7]]
764c12b2747c115339cab9ea7c029b6191789ca6
VigneshLearning/SeleniumPythonWorks
/Demo/InheritYMethOveridDemo.py
477
3.890625
4
class Parent: def __init__(self): print("This is Parent Class") def ParFunc(self): print("This is Parent Function") obj = Parent() obj.ParFunc() class Child(Parent): def __init__(self): print("This is Child Class") def ChildFunc(self): print("This is Child Function") # THE BELOW IS METHOD OVER RIDING def ParFunc(self): print("This is Method Overiding") obj1 = Child() obj1.ChildFunc() obj1.ParFunc()
dc460d5b76fed59d1c37b71282e3e6561779607d
MW-2005/print
/print_secondary.py
1,026
4.6875
5
# --------------- Section 2 --------------- # # Relevant Documentation # print() # python.org | https://docs.python.org/3/library/functions.html#print # W3Schools | https://www.w3schools.com/python/ref_func_print.asp # Read about the sep argument on the W3Schools documentation. sep is an optional argument. One that can be set if we # we want to. To set an optional argument, we specify its name, or its identifier. Then we use the equals sign, # followed by a string that will act as the separator. print('Separating', 'words', 'with', 'something', 'new!', sep='@') # When specifying the sep argument, you must set it as the last argument in the function. # Project 2.1 # 1) Print your first and last name separated with _ by using the sep argument. # 2) Print the date in numerical form, using the / as the sep argument for the separator between the numbers. # 3) Print abc separated with ### between each letter. # # Example Output # elia_deppe # 06/13/21 # a###b###c # # WRITE CODE BELOW
f302a726a04443663cd116c69ab50717c370cda6
ruanbekker/simple-etl
/src/etl.py
1,818
3.578125
4
import pandas as pd import logging def score_check(grade, subject, student): """ If a student achieved a score > 90, multiply it by 2 for their effort! But only if the subject is not NULL. :param grade: number of points on an exam :param subject: school subject :param student: name of the student :return: final nr of points """ if pd.notnull(subject) and grade > 90: new_grade = grade * 2 logger.info(f'Doubled score: {new_grade}, Subject: {subject}, Student name: {student}') return new_grade else: return grade def extract(): """ Return a dataframe with students and their grades""" data = {'Name': ['Hermione'] * 5 + ['Ron'] * 5 + ['Harry'] * 5, 'Subject': ['History of Magic', 'Dark Arts', 'Potions', 'Flying', None] * 3, 'Score': [100, 100, 100, 68, 99, 45, 53, 39, 87, 99, 67, 86, 37, 100, 99]} df = pd.DataFrame(data) return df def transform(df: pd.DataFrame()): df["New_Score"] = df.apply(lambda row: score_check(grade=row['Score'], subject=row['Subject'], student=row['Name']), axis=1) return df def load(df): old = df["Score"].tolist() new = df["New_Score"].tolist() return f"ETL finished. Old scores: {old}. New scores: {new}" def main(): # handler(event, context): extracted_df = extract() transformed_df = transform(extracted_df) result = load(transformed_df) logger.info(result) logger.info('Awesome, we built our first CI CD pipeline!') return result if __name__ == '__main__': logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s') logger = logging.getLogger(__name__) main()
b9b3d875bb63bd35b5db8fb876f92ce50409c1c5
t3h2mas/gibson
/plugins/msg_stack.py
465
3.75
4
#!/usr/bin/python2 class MsgStack(object): def __init__(self): self._stack = [] def push(self, msg): self._stack.insert(0, msg) # !lifo def pop(self): return self._stack.pop() def isEmpty(self): return self._stack == [] # test if __name__ == '__main__': ms = MsgStack() for s in "Hi there, what's your name?".split(' '): ms.push(s) while not ms.isEmpty(): print ms.pop()
f9f0354f3376a88bc70da4e14ce689a8c8085539
wmn7/python_project
/python_second_flask/sqlalchemy_test.py
2,823
3.640625
4
from sqlalchemy import create_engine,Column,Integer,String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import relationship from sqlalchemy import ForeignKey engine = create_engine('mysql://root:Wangmaonan1@localhost/shiyanlou') user_data = engine.execute('select * from user').fetchall() print(user_data) ''' 首先导入了 create_engine, 该方法用于创建 Engine 实例,传递给 create_engine 的参数定义了 MySQL 服务器的访问地址,其格式为 mysql://<user>:<password>/<host>/<db_name> 接着通过 engine.execute 方法执行了一条 SQL 语句,查询了 user 表中的所有用户 ''' ''' 如果想使 Python 类映射到数据库表中,需要基于 SQLAlchemy 的 declarative base class,也就是宣言基类创建类。当基于此基类,创建 Python 类时,就会自动映射到相应的数据库表上。创建宣言基类,可以通过 declarative_base 方法进行 ''' Base = declarative_base() ''' 创建基类以后,创建 User 类 ''' class User(Base): __tablename__ = 'user' id = Column(Integer,primary_key=True) name = Column(String) email = Column(String) def __repr__(self): return "<User(name=%s)>" % self.name ''' 如果想通过 User 查询数据库该怎么办呢?需要先引入 Session。Session 是映射类和数据库沟通的桥梁,包含事务管理功能。 ''' Session = sessionmaker(bind=engine) session = Session() print(session.query(User).all()) # 创建数据库表 class Course(Base): __tablename__ = 'course' id = Column(Integer,primary_key=True) name = Column(String) teacher_id = Column(Integer,ForeignKey('user.id')) teacher = relationship('User') def __repr__(self): return '<Course(name=%s)>' % self.name ''' SQLAlchemy 中可以使用 ForeignKey 设置外键。设置外键后,如果能够直接从 Course 的实例上访问到相应的 user 表中的记录会非常方便,而这可以通过 relationship 实现。上面的代码通过 relationship 定义了 teacher 属性,这样就可以直接通过 course.teacher 获取相应的用户记录 ''' class Lab(Base): __tablename__ = 'lab' id = Column(Integer,primary_key=True) name = Column(String(64)) course_id = Column(Integer,ForeignKey('course.id')) course = relationship('Course',backref = 'labs') def __repr__(self): return '<Lab(name=%s)>' % self.name # 创建lab表 Base.metadata.create_all(engine) course = session.query(Course).first() lab1 = Lab(name='ORM 基础', course_id=course.id) lab2 = Lab(name='关系数据库', course=course) # 首先将数据add到session中 session.add(lab1) session.add(lab2) session.commit() # 删除对象 session.delete(lab1) session.commit()
3c77bdb32bb23f5ebc79033fbefbc5ec09588bc0
rohmdk/python-proj1
/goodmorgan.py
156
4.09375
4
#greeting = "Good morning" #print(input("what is your name ? ")) #print(greeting) name = input("Please enter your name : \n") print("Good morning," +name)
a5018330fa7123c7a25585b7d7047f501aecb7bf
kzh980999074/my_leetcode
/src/Tree/110. Balanced Binary Tree.py
1,009
3.984375
4
''' Given a binary tree, determine if it is height-balanced. ''' class TreeNode: def __init__(self,x): self.val=x self.left=None self.right=None 'false' def isbalanced(root): if not root :return True l=-1 i=0 stack=[[],[]] stack[0].append(root) while stack[i%2]: while stack[i%2]: p=stack[i%2].pop() if p!=None: stack[(i+1)%2].append(p.left) stack[(i+1)%2].append(p.right) else: l=i if l==i: print(l) break else: i+=1 for j in stack[(i+1)%2]: if j!=None: if j.right==None and j.left==None: continue else: return False return True root=TreeNode(1) root.left=TreeNode(2) root.right=TreeNode(2) root.left.left=TreeNode(3) root.left.right=TreeNode(3) root.left.left.left=TreeNode(4) root.left.left.right=TreeNode(4) print(isbalanced(root))
d632ff768758195fefc983304238de01272faf05
QinmengLUAN/Daily_Python_Coding
/LC23_mergeKLists_heap.py
1,194
3.734375
4
""" 23. Merge k Sorted Lists Hard: Linked list, heapq My first Hard question. Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 """ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: # from heapq import heappush, heappop dummy = temp = ListNode() hq = [(lists[i].val, i, lists[i]) for i in range(len(lists)) if lists[i]] heapify(hq) ## The above two lines can be replaced to: # if not len(lists): # return None # hq = [] # for i in range(len(lists)): # if lists[i]: # heapq.heappush(hq, (lists[i].val, i, lists[i])) while hq: val, idx, temp.next = heapq.heappop(hq) temp = temp.next if temp.next: heapq.heappush(hq, (temp.next.val, idx, temp.next)) return dummy.next
86bd5697802516c3a7f2b4c9263fed46bf6ff5be
thiagor83/estudos
/PhytonExercicios/ex010.py
200
3.71875
4
n1 = float(input('Quanto dinheiro você tem ai mano? R$')) n2 = float(input('Qual a cotação do dolar hoje?')) print('Com R${:.2f} reais, você consegue comprar ${:.2f} dolares!'.format(n1,(n1/n2)))
19d18d8506d203d04fde4660f71f7fab08120d7a
UnB-KnEDLe/Regex
/regex/atos/cessoes.py
6,098
3.65625
4
import re from typing import List, Match import pandas as pd from atos.base import Atos def case_insensitive(s: str): """Returns regular expression similar to `s` but case careless. Note: strings containing characters set, as `[ab]` will be transformed to `[[Aa][Bb]]`. `s` is espected to NOT contain situations like that. Args: s: the stringregular expression string to be transformed into case careless Returns: the new case-insensitive string """ return ''.join([c if not c.isalpha() else '[{}{}]'.format(c.upper(), c.lower()) for c in s]) def remove_crossed_words(s: str): """Any hyfen followed by 1+ spaces are removed. """ return re.sub(r'-\s+', '', s) LOWER_LETTER = r"[áàâäéèẽëíìîïóòôöúùûüça-z]" UPPER_LETTER = r"[ÁÀÂÄÉÈẼËÍÌÎÏÓÒÔÖÚÙÛÜÇA-Z]" DODF = r"(DODF|[Dd]i.rio\s+[Oo]ficial\s+[Dd]o\s+[Dd]istrito\s+[Ff]ederal)" SIAPE = r"{}\s*(?:n?.?)\s*(?P<siape>[-\d.Xx/\s]+)".format(case_insensitive("siape")) # SIAPE = r"(?i:siape)\s*(?:n?.?)\s*(?P<siape>[-\d.Xx/\s]+)" MATRICULA = r"(?:matr.cul.|matr?[.]?\B)[^\d]+(?P<matricula>[-\d.XxZzYz/\s]+)" # MATRICULA = r"(?i:matr.cul.|matr?[.]?\B)[^\d]+(?P<matricula>[-\d.XxZzYz/\s]+)" MATRICULA_GENERICO = r"(?<![^\s])(?P<matricula>([-\d.XxZzYz/\s]{1,})[.-][\dXxYy][^\d])" MATRICULA_ENTRE_VIRGULAS = r"(?<=[A-ZÀ-Ž]{3})\s*,\s+(?P<matricula>[-\d.XxZzYz/\s]{3,}?)," SERVIDOR_NOME_COMPLETO = r"(servidor.?|empregad.)[^A-ZÀ-Ž]{0,40}(?P<name>[A-ZÀ-Ž][.'A-ZÀ-Ž\s]{6,}(?=[,]))" # SERVIDOR_NOME_COMPLETO = r"(?i:servidor.?|empregad.)[^A-ZÀ-Ž]{0,40}(?P<name>[A-ZÀ-Ž][.'A-ZÀ-Ž\s]{6,}(?=[,]))" NOME_COMPLETO = r"(?P<name>['A-ZÀ-Ž][.'A-ZÀ-Ž\s]{6,}(?=[,.:;]))" PROCESSO_NUM = r"(?P<processo>[-0-9/.]+)" INTERESSADO = r"{}:\s*{}".format(case_insensitive("interessad."), NOME_COMPLETO) # INTERESSADO = r"(?i:interessad.):\s*{}".format(NOME_COMPLETO) # INTERESSADO = r"(?i:interessad.):\s*" + NOME_COMPLETO ONUS = r"(?P<onus>\b[oôOÔ]{}\b[^.]+[.])".format(case_insensitive("nus")) # ONUS = r"(?P<onus>\b[oôOÔ](?i:(nus))\b[^.]+[.])" class Cessoes(Atos): _special_acts = ['matricula', 'cargo'] def __init__(self, file, debug=False, extra_search = True): self._debug = debug self._extra_search = extra_search self._processed_text = remove_crossed_words(open(file).read()) self._raw_matches = [] super().__init__(file) def _act_name(self): return "Cessoes" def _props_names(self): return list(self._prop_rules()) def _rule_for_inst(self): return ( r"([Pp][Rr][Oo][Cc][Ee][Ss][Ss][Oo][^0-9/]{0,12})([^\n]+?\n){0,2}?"\ + r"[^\n]*?[Aa]\s*[Ss]\s*[Ss]\s*[Uu]\s*[Nn]\s*[Tt]\s*[Oo]\s*:?\s*\bCESS.O\b"\ + r"([^\n]*\n){0,}?[^\n]*?(?=(?P<look_ahead>PROCESSO|Processo:|PUBLICAR|pertinentes[.]|autoridade cedente|"\ + case_insensitive('publique-se') + "))" # + r'(?i:publique-se)' + "))" ) def _prop_rules(self): return { 'interessado': INTERESSADO, 'nome': SERVIDOR_NOME_COMPLETO, 'matricula': MATRICULA, 'processo': r"[^0-9]+?{}".format(PROCESSO_NUM), # 'processo': r"[^0-9]+?" + PROCESSO_NUM, 'onus': ONUS, 'siape': SIAPE, 'cargo': r",(?P<cargo>[^,]+)", } def _find_instances(self) -> List[Match]: """Returns list of re.Match objects found on `self._text_no_crosswords`. Return: a list with all re.Match objects resulted from searching for """ self._raw_matches = list( re.finditer(self._inst_rule, self._processed_text, flags=self._flags) ) l = [i.group() for i in self._raw_matches] if self._debug: print("DEBUG:", len(l), 'matches') return l def _get_special_acts(self, lis_matches): for i, match in enumerate(self._raw_matches): act = match.group() matricula = re.search(MATRICULA, act) or \ re.search(MATRICULA_GENERICO, act) or \ re.search(MATRICULA_ENTRE_VIRGULAS, act) nome = re.search(self._rules['nome'], act) if matricula and nome: offset = matricula.end()-1 if 0 <= (matricula.start() - nome.end()) <= 5 \ else nome.end() - 1 cargo, = self._find_props(r",(?P<cargo>[^,]+)", act[offset:]) else: cargo = "nan" lis_matches[i]['matricula'] = matricula.group('matricula') if matricula \ else "nan" lis_matches[i]['cargo'] = cargo def _find_props(self, rule, act): """Returns named group, or the whole match if no named groups are present on the match. Args: match: a re.Match object Returns: content of the unique named group found at match, the whole match if there are no groups at all or raise an exception if there are more than two groups. """ match = re.search(rule, act, flags=self._flags) if match: keys = list(match.groupdict().keys()) if len(keys) == 0: return match.group() elif len(keys) > 1: raise ValueError("Named regex must have AT MOST ONE NAMED GROUP.") if self._debug: print('key: ', keys[0]) return match.group(keys[0]), else: return "nan" def _acts_props(self): acts = [] for raw in self._raw_acts: act = self._act_props(raw) acts.append(act) if self._extra_search: self._get_special_acts(acts) return acts def _extract_instances(self) -> List[Match]: found = self._find_instances() self._acts_str = found.copy() return found def _build_dataframe(self): return pd.DataFrame(self._acts)
64fe3eed495a3516b479fa128d5cc5136f1eef7f
alissonoliveiramartins/Python-Fundamentos-para-Analise-de-Dados
/Resposta_Exercicios/calculadora_v1.py
1,200
4.25
4
# Calculadora em Python # Desenvolva uma calculadora em Python com tudo que você aprendeu nos capítulos 2 e 3. # A solução será apresentada no próximo capítulo! # Assista o vídeo com a execução do programa! print("\n******************* Python Calculator *******************") def menu(): opcao = ['Soma','Subtração','Multiplicação','Divisão'] print('Selecione o numero da operaçao desejada: \n') for i in range(1, len(opcao)+1): print(f'{i} - {opcao[i-1]}') print() soma = lambda x,y : x+y subtracao = lambda x,y : x-y multiplicacaoo = lambda x,y : x*y divisao = lambda x,y : x/y if __name__ == '__main__' : menu() op = int(input('Digite sua opcão (1/2/3/4): ')) n1 = int( input( 'Digite o primeiro número: ')) n2 = int( input( 'Digite o segundo número: ')) if op == 1: print(f'{n1} + {n2} = {soma(n1,n2)}') elif op == 2: print(f'{n1} - {n2} = {subtracao(n1,n2)}') elif op == 3: print(f'{n1} * {n2} = {multiplicacao(n1,n2)}') elif op == 4: print(f'{n1} / {n2} = {divisao(n1,n2)}') else: print('Opção invalida. ')