text
stringlengths
37
1.41M
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/01/08 # @Author : yuetao # @Site : # @File : LeetCode990_等式方程的可满足性.py # @Desc : 查并集,一般公司不会考察 """ https://zhuanlan.zhihu.com/p/93647900 https://leetcode-cn.com/problems/satisfiability-of-equality-equations/solution/shi-yong-bing-cha-ji-chu-li-bu-xiang-jiao-ji-he-we/ """ class Solution(object): class UnionFind: def __init__(self): self.parent = list(range(26)) def find(self, index): if index == self.parent[index]: return index self.parent[index] = self.find(self.parent[index]) return self.parent[index] def merge(self, index1, index2): self.parent[self.find(index1)] = self.find(index2) def equationsPossible(self, equations): """ :type equations: List[str] :rtype: bool """ uf = Solution.UnionFind() for equation in equations: if equation[1] == "=": index1 = ord(equation[0]) - ord("a") index2 = ord(equation[3]) - ord("a") uf.merge(index1, index2) for equation in equations: if equation[1] == "!": index1 = ord(equation[0]) - ord("a") index2 = ord(equation[3]) - ord("a") if uf.find(index1) == uf.find(index2): return False return True if __name__ == '__main__': solve = Solution() equations = ["a==b","b!=c","c==a"] result = solve.equationsPossible(equations) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/12/30 # @Author : yuetao # @Site : # @File : 合并两个排序的链表.py # @Desc : class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if not l1 and l2: return l2 if not l2 and l1: return l1 res = ListNode(None) p = res if l1.val <= l2.val: p.next = ListNode(l1.val) l1 = l1.next p = p.next else: p.next = ListNode(l2.val) l2 = l2.next p = p.next while l1 and l2: if p.val <= l1.val and l1.val < l2.val: p.next = ListNode(l1.val) p = p.next l1 = l1.next else: p.next = ListNode(l2.val) p = p.next l2 = l2.next if l1: p.next = l1 if l2: p.next = l2 return res.next if __name__ == '__main__': solve = Solution() a = ListNode(-10) b = ListNode(-10) c = ListNode(-9) d = ListNode(-4) e = ListNode(1) f = ListNode(6) g = ListNode(6) h = ListNode(-7) a.next = b b.next = c c.next = d d.next = e e.next = f f.next = g result = solve.mergeTwoLists(a, h) while result: print(result.val) result = result.next
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/8/30 0030 11:40 # @Author : Letao # @Site : # @File : LeetCode5000.py # @Software: PyCharm # @desc : """ 设 f[i] 是以 nums[i] 结尾,乘积为正的最长子数组的长度。 设 g[i] 是以 nums[i] 结尾,乘积为负的最长子数组的长度。 """ class Solution(object): def getMaxLen(self, nums): """ :type nums: List[int] :rtype: int """ length = len(nums) f = [0] * length g = [0] * length if nums[0]>0: f[0] = 1 elif nums[0] < 0: g[0] = 1 res = f[0] for i in range(1, length): if nums[i] > 0: f[i] = f[i-1] + 1 if g[i-1] > 0: g[i] = g[i-1] + 1 elif nums[i] < 0: if g[i-1] > 0: f[i] = g[i-1] + 1 g[i] = f[i-1] + 1 res = max(res, f[i]) return res if __name__ == "__main__": solve = Solution() nums = [-1] result = solve.getMaxLen(nums) print(result)
def changeChar(string,ch1,ch2,begin=0,end=-1): if(end ==-1): end=len(string) i,newstring=0,"" while(i<len(string)): if(string[i]==ch1 and i>=begin and i<=end ): newstring = newstring+ ch2 else: newstring = newstring + string[i] i+=1 return newstring phrase = 'Python is really magic' print(changeChar(phrase,' ', '*')) print(changeChar(phrase,' ', '*', 8, 12)) print(changeChar(phrase,' ', '*',12)) print(changeChar(phrase,' ', '*',end=12))
from turtle import * def triangle(tsize,tcolor,tangle): color(tcolor) i=0 while (i<3): forward(tsize) right(120) i+=1 def stars5(scolor,ssize): i=0 angle=72 while (i<5): forward(ssize) right(144) i += 1
#Associate the month with the corresponding number of day t1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] t2 = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin','Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'] t3 = [] i=0 while i <12: t3.append(t2[i]) t3.append(t1[i]) print(t2[i],end=' ') i= i +1 print('\n',t3)
def MonthName(n): "Function to find a month name" mname=['January','February','March','April','May','June','July','August','September','October','November','December'] z=mname[n-1] return z #Usage print(MonthName(1))
#This program count the number of char in a name name = [ 'Jean-Michel' , 'Marc' , 'Vanessa' , 'Anne' , 'Maximilien ' , 'Alexandre-Benoît' , 'Louise' ] i = 0 while i < len(name): charcount=len(name[i]) print(name[i],' : ',charcount) i += 1
# Add numbers between 'a' and 'b' which are multiple of 3 or 5 a,b = 0,32 i = a z = 0 while i<=b: #check if number is multiple of 3 or 5 if not(i%3) or not(i%5): z = z + i else: print("ignoring",i) i = i + 1 print("Result is",z)
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth, error). """ import numpy as np cleaned_data = [] N=10/100 ### my code goes here #(Y-truth-prediction)^2 R2_Error=(predictions-net_worths)**2 # sort on descending score sort_index = np.argsort(R2_Error, axis=0) #np.sort(R2_Error, axis=0) #combine data dataArray=np.concatenate((ages, net_worths,R2_Error), axis=1) data=list(map(tuple, dataArray)) # throw away the Nth percent from dada based on last Nth index d=round(N*len(R2_Error)) #elements need to be deleted l=len(R2_Error) IndexTo_remove=sort_index[l-d:].tolist() cleaned_data=np.delete(data,IndexTo_remove, axis=0) return cleaned_data ## loop to find N largest def Nmaxelements(list1, N): final_list = [] for i in range(0, N): max1 = 0 for j in range(len(list1)): if list1[j] > max1: max1 = list1[j]; list1.remove(max1); final_list.append(max1) print(final_list)
"""Rafaela tem uma loja de antiguidade e decidiu avaliar quanto vale o seu estoque de 1500 peças. Escreva um programa que receba como entrada a descrição, o valor e o ano de cada item presente na loja""" #A quantidade de items produzidos antes de 1827 #o valor médio dos intens # a descrição e o ano do objeto mais valiosos """n=int(input("Qual a Quantidade de Peças")) antesAno=0 valioso=0 valorTotal=0 desValor=0 anoValor=0 for i in range(n): des=input("Qual o produto? ") valor=float(input("Qual o valor? ")) ano=int(input("Qual ano? ")) if ano < 1827: antesAno+=1 if valioso < valor: valioso=valor desValor=des anoValor=ano valorTotal+=valor media=(valorTotal/n) print("a média é %.2f R$" % (media)) print("Quantidade de produtos antes de 1827:",antesAno) print("O Produto mais caro é" ,desValor,"do ano de ",anoValor)""" """2. Uma lavanderia oferece ao cliente duas opções de cobrança: R$ 7,00 por peça de roupa ou R$ 5,00 por quilo. Caso a lavagem seja a seco, é acrescentada uma taxa de R$ 3,50. Escreva um programa que receba como entrada os dados dos últimos 50 pedidos de lavagem e exiba o valor a ser pago por cada um, o total arrecadado pela lavanderia e a quantidade de lavagens a seco solicitadas.""" """pedidos = int(input("Quantos pedidos? ")) peca = 7.00 quilo = 5.00 seco=3.50 Total=0 contSeco=0 for i in range(pedidos): FormC=str.lower(input("Qual forma de cobrança ? \n>Peça \n>Peso \n>")) if FormC == "peça": QntPeca=int(input("Quantidade de Peças? ")) PrecoPeca=QntPeca*peca print("Valor do pedido",PrecoPeca) Total+=PrecoPeca elif FormC == "peso": QntQuilo=int(input("Quantos Quilos? ")) PrecQuilo=QntQuilo*quilo print("Valor do pedido",PrecQuilo) Total+=PrecQuilo lavaSeco=str.lower(input("Lavagem à Seco ?")) if lavaSeco == "sim": Total+=seco contSeco+=1 print("Total Arrecadado %.2f R$" % Total,"\nQuantidades de lavagens à seco =",contSeco) """ """3. Escreva um programa para receber como entrada dois números e exibir a quantidade de múltiplos de 4 entre eles (os extremos do intervalo não devem ser considerados).""" """n1 = int(input("Digite o primeiro número? ")) n2 = int(input("Digite o segundo número? ")) count=0 for i in range (n1+1,n2): if i%4 == 0: count+=1 print(count,"Múltiplos")""" """4. Uma grande loja de produtos para o lar deseja fazer um levantamento de todas as 7000 vendas realizadas nos últimos meses para descobrir as preferências de seus clientes. São vendidos móveis nas cores marfim e branco, e eletrodomésticos das marcas Brastemp e Electrolux, além de objetos de decoração em geral. Escreva um programa que receba como entrada os dados das vendas realizadas (os dados variam de acordo com o tipo de produto) e exiba ao final:  o percentual de móveis de cada cor vendidos (Dica: para saber o percentual, é preciso analisar a quantidade em relação ao total)  a marca de eletrodomésticos mais vendida  o preço médio dos artigos de decoração""" """ n = int(input("Qual a quantidade de itens? ")) CountB=0 CountM=0 MarcaB=0 MarcaE=0 PrecoT=0 CountP=0 for i in range(n): item=str.lower(input("Qual o objeto? ")) if item == "móvel": cor=str.lower(input("Qual cor? \n>Branco \n>Marfim \n>")) if cor == "branco": CountB+=1 elif cor == "marfim": CountM+=1 elif item == "eletrodoméstico": marca=str.lower(input("Qual marca? \n>Brastemp \n>Electrolux \n>")) if marca == "brastemp": MarcaB+=1 else: MarcaE+=1 else: preco=int(input("Qual preço do produto? R$")) PrecoT+=preco CountP+=1 if CountB + CountM > 0: pMarfim = 100*CountM//(CountM+CountB) pBranco = 100 - pMarfim print("Percentuais =",pMarfim,"%Marfim",pBranco,"%Branco") else: print("Nenhum móvel vendido") if MarcaB+MarcaE>0: if MarcaB > MarcaE: print("Marca mais vendida é Brastemp") elif MarcaB > MarcaE: print("Marca mais vendida é Eletrolux") else: ("Ambas as marcas foram vendidas igualmente") else: print("Nenhum eletrodoméstico vendido") if PrecoT == 0: print("Nenhum objeto de decoração vendido") else: print("O preço médio de decoração é %.0f R$" %(PrecoT/CountP)) """ pessoas=int(input("Quantas pessoas? ")) opBom=0 opReRu=0 opCount=0 Pes30=0 MaiorIdade=0 for i in range(pessoas): idade=int(input("Qual sua idade? ")) opniao=str.lower(input("Qual sua opnião? \nRuim \nRegular \nBom \nExcelente \n>")) if opniao == "bom": opBom+=idade opCount+=1 opMedia=(opBom//opCount) if opniao == "regular" or opniao=="ruim": opReRu+=1 if idade >30 and opniao == "excelente": Pes30+=1 if idade>MaiorIdade: MaiorIdade=idade print("Média de idade Bom =",opMedia, "\nQuantidade respostas Ruim/Regular =",opReRu, "\nPessoas acima de 30 Excelente =",Pes30, "\nMaior idade =",MaiorIdade)
import gpioRap as gpioRap import RPi.GPIO as GPIO #Create GpioRap class using BCM pin numbers gpioRapper = gpioRap.GpioRap(GPIO.BCM) #Create an LED, which should be attached to pin 17 led = gpioRapper.createLED(17) #Create a button, which should be monitored by pin 4, where a False is read when the button is pressed button = gpioRapper.createButton(4, False) #Turn the led on led.on() buttonPressed = False #Loop until exception (ctrl c) while buttonPressed == False: #Wait for the button to be pressed if button.waitForPress(3) == True: buttonPressed = True #turn led off led.off() #Cleanup gpioRapper.cleanup()
from Board import Board from GameTree import AI import sys import time import random from Input import Input WHITE = True BLACK = False #player gets to choose which side to play #default player is black def chooseSide(): playerChoiceInput = input( "Would you like to be white(w) or Black(B)? ").lower() if 'w' in playerChoiceInput: print("You chose white") return WHITE else: print("You chose black") return BLACK #player chooses depth of game tree #default is 2 def treeDepth(): depthInput = 2 try: depthInput = int(input("How many levels should the game tree search?\n" "Levels deeper than 3 will be very slow as no pruning was implemented" )) except: print("Invalid input, defaulting to 2") return depthInput #gives player command options def listOfChoises(): move = 'a3, Nc3, Qxa2, etc = make the move' legalMoves = 'l = show all legal moves' undo = 'u = undo last move' randomMove = 'r = make a random move' advantage = 'a = point advantage' quit = 'quit' options = [undo, legalMoves, randomMove, quit, move, advantage, '', ] print('\n'.join(options)) #gets all legal moves in short notation def legalMoves(board, parser): for move in parser.getMoves(board.currentSide): print(move.notation) #checks all legal moves and makes a random nonAI choice def getRandomMove(board, parser): legalMoves = board.AllLegalMoves(board.currentSide) randomMove = random.choice(legalMoves) randomMove.notation = parser.notForMove(randomMove) return randomMove def makeMove(move, board): print() print("Making move : " + move.notation) board.makeMove(move) #this works based off of the minimax point system def printPointAdvantage(board): print("Currently, the point difference is : " + str(board.getPAdvantageOfSide(board.currentSide))) #will only work if more than two moves have been made def undoLastTwoMoves(board): if len(board.history) >= 2: board.undoLastMove() board.undoLastMove() def startGame(board, playerSide, ai): parser = Input(board, playerSide) while True: print(board) print() if board.isCheckmate(): if board.currentSide == playerSide: print("Checkmate, you lost") else: print("Checkmate! You won!") return if board.isStalemate(): if board.currentSide == playerSide: print("Stalemate") else: print("Stalemate") return if board.currentSide == playerSide: move = None command = input("It's your move." " Type '?' for options.").lower() if command == 'u': undoLastTwoMoves(board) continue elif command == '?': listOfChoises() continue elif command == 'a': printPointAdvantage(board) continue elif command == 'l': legalMoves(board, parser) continue elif command == 'r': move = getRandomMove(board, parser) elif command == 'quit': return else: move = parser.shortNotForMove(command) if move: makeMove(move, board) else: print("Sorry input entered could not be passed, please enter a valid command or move.") else: print("AI thinking...") start = time.clock() move = ai.getBestMove() move.notation = parser.notForMove(move) stop = time.clock() print(stop-start) makeMove(move, board) board = Board() playerSide = chooseSide() print() aiDepth = treeDepth() opponentAI = AI(board, not playerSide, aiDepth) try: startGame(board, playerSide, opponentAI) except KeyboardInterrupt: sys.exit()
def getFormattedInput(filename): return [[isTree == "#" for isTree in x] for x in open(filename, "r").read().split("\n")] def solve3a(inputMatrix, slope): i, j = [0, 0] numTrees = 0 while i <= len(inputMatrix) - 1: if inputMatrix[i][j]: numTrees += 1 j = (j + slope[0]) % len(inputMatrix[0]) i += slope[1] return numTrees def solve3b(inputMatrix, slopeList): product = 1 for x in slopeList: product = product * solve3a(inputMatrix, x) return product print(solve3a(getFormattedInput("input.txt"), [3, 1])) slopeList = [[1, 1], [3, 1], [5, 1], [7, 1], [1, 2]] print(solve3b(getFormattedInput("input.txt"), slopeList))
#iterācija - kādas darbības atkārtota izpildīšana (iterable) mainigais = [1, 2, 3] #list for elements in mainigais: print(elements) myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] for x in myList: print(x) for _ in myList: #var nerakstīt cikla mainīgo print("Sveiki") #atrast pāra skaitļus for skaitlis in myList: if (skaitlis % 2 == 0): print(skaitlis) else: print(f"Nepāra skaitlis: {skaitlis}") #aprēķināt summu summa = 0 for sk in myList: summa = summa + sk print(f"Pēc {sk} skaitļu saskaitīšanas summa ir {summa}") print(summa) #drukā tekstu myString = "Sveika pasaule!" for burts in myString: print(burts, end = " ") for burts in "programma": print(burts, end = " ") #drukā tuple tup = (1, 2, 3, 4) for elements in tup: print(elements) myList = [(1, 2),(3,4),(5,6),(7,8)] #sapakotie tuples / packed tuples print(len(myList)) for elements in myList: print(elements) for (a,b) in myList: #atpako - tuple unpacking print(a) myList = [(1,2,3),(4,5,6),(7,8,9)] for (a,b,c) in myList: print(c) #vārdnīcas d = {"k1":11, "k2":12, "k3":13} for elements in d: print(elements) #izdrukā atslēgas for elements in d.items(): print(elements) #izdrukā atslēgu/vērtību pārus for atslega,vertiba in d.items(): print(vertiba) #izdrukā skaitļus ar range for skaitlis in range(15): #intervāls no [0;15) print(skaitlis +1) for skaitlis in range(4,15): #intervāls [4;15) print(skaitlis) for skaitlis in range(4,15,3):#sākot ar 4, beidzot ar 15, izdrukā katru trešo print(skaitlis)
#Nosacījums: Aprēķini ievadīto naturālo skaitļu faktoriālo summu. n = int(input("Ievadi naturālu skaitli: ")) while True: if n<1: n = (input("Ievadi naturālu skaitli: ")) else: break faktorials = 1 summa = 0 for i in range(n): faktorials = faktorials*(i+1) summa = summa + faktorials print(faktorials, summa) #pārbaudīt print (f"Pirmo {n} skaitļu faktoriālu summa ir {summa}.")
#pirmais uzdevums a = 15 b = 2.5 c = 4.78 #lielākais skaitlis if (a > b) and (a > c): print("15 ir lielākais skaitlis") elif(b > a) and (b > c): print ("2.5 ir lielākais skaitlis") else: print("4.78 ir lielākais skaitlis") #mazākais skaitlis if (a < b) and (a < c): print("15 ir mazākais skaitlis") elif (b < a) and (b < c): print("2.5 ir mazākais skaitlis") else: print("4.8 ir mazākais skaitlis") #risinājums ar list myList = [a, b, c] myList.sort() print( f"Lielākais skaitlis ir {myList[-1]}, bet mazākais skaitlis ir {myList[0]}" ) #otrais uzdevums gradi = float(input("Ievadi tavu ķermeņa temperatūru skaitļos: ")) if (gradi < 35): print("Vai nav par aukstu?") elif (gradi >= 35) and (gradi <= 37): print("Viss kārtībā") else: print("Iespējams drudzis") #stundas uzdevums atr = "" if (atr == "banka"): print ("Te ir daudz naudas") elif (atr == "veikals"): print("Jānopērk āboli") elif (atr == "aptieka"): print("Man ir iesnas") else: print ("Ābolu nav")
from matplotlib import pyplot as plt import numpy as np x=np.arange(1,11) y=x//2 plt.plot(x,y) plt.xlabel("X-axis") plt.ylabel("y-axis") plt.title("y=x/2 graph") plt.show()
def cocktail(a): for i in range(len(a)//2): swap = False for j in range(1+i, len(a)-i): # test whether the two elements are in the wrong order if a[j] < a[j-1]: # let the two elements change places a[j], a[j-1] = a[j-1], a[j] swap = True # we can exit the outer loop here if no swaps occurred. if not swap: break swap = False for j in range(len(a)-i-1, i, -1): if a[j] < a[j-1]: a[j], a[j-1] = a[j-1], a[j] swap = True if not swap: break num_list = [75, 16, 55, 19, 48, 14, 2, 61, 22, 100] print("Before: ", num_list) cocktail(num_list) print("After: ", num_list)
# Check internet connection import urllib.request as urllib2 def check_network(): try: urllib2.urlopen("http://google.com", timeout=2) return True except urllib2.URLError: return False print( 'connected' if check_network() else 'no internet!' )
# coding=utf-8 """ Program Name: Battleship Author: blackk100 License: MIT License Description: A Python3 based, CLI implementation of the board game, Battleship. Current Version: Alpha """ # Imports import os from time import sleep from random import randint as rand # Generic Functions def cls(): """Clears the terminal screen""" sleep(0.1) os.system("cls" if os.name == "nt" else "clear") def fancy_print(li, flag_): """Conditional aesthetically pleasing printing""" if flag_ is True: for _ in li: # Line-by-line with time gap sleep(0.09) print(_, end="", flush=True) else: # No time gap for _ in li: print(_, end="", flush=True) def title_art(flag_): """Prints the titular battleship""" t = [ "\n |__", "\n |\\/", "\n ---", "\n / | [", "\n ! | |||", "\n _/| _/|-++'", "\n + +--| |--|--|_ |-", "\n { /|__| |/\\__| |--- |||__/", "\n +---------------___[}-_===_._____'", "\n ____`-' ||___-{]_| _[}- | |_[___\\==-- \\/ _", "\n __..._____--==/___]_|__|_____________________________[___\\==--____,------'' .7", "\n | /", "\n | BATTLESHIP /", "\n | Alpha |", "\n \\_________________________________________________________________________|\n"] fancy_print(t, flag_) def menu(flag_): """Prints the menu""" menu_ = [ "\n Press CTRL + C anytime to force exit if the game gets stuck.", "\n 1. Play", "\n 2. Credits", "\n 3. Exit"] fancy_print(menu_, flag_) def menu_nav(flag1, flag2): """Menu navigation""" cls() title_art(flag1) menu(flag1) fancy_print("\n Option:", flag1) if flag2 == 1: fancy_print("\n Please enter a valid number! (1 <= option <= 3)\n", True) return input(" ") def credits_(flag_): """Prints the credits""" credit = [ "\n\n Pre-Alpha Version", "\n\n Programming & Design - blackk100 - https://github.com/blackk100/", "\n ASCII Battleship Art - ASCII Art - http://ascii.co.uk/art/battleship", "\n Hope you enjoyed it! Read README.md/README.txt for the changelog and future goals.", "\n\n Back to menu or exit? (M / E)?\n"] fancy_print(credit, flag_) # Game functions # TODO: Switch to OOP (Object-Oriented Programming) # TODO: Add various difficulty levels (no. of moves, movement of ships, how smart the AI is, etc.) # TODO: Add local "hotseat" multiplayer # TODO: Add AI vs AI mode (player watches it step by step, and sees both AI's grids) # TODO: Add local LAN multiplayer # TODO: Add TCP/IP multiplayer # TODO: Add profiles # Generic Functions def map_gen(size): """Generates map""" map_ = [] for _ in range(size): map_.append([" ~"] * size) return map_ def base_print(map_, ships_, turns_, flag_): """Basic print statements""" def map_print(): """Prints the map.""" for i in map_: for j in i: fancy_print(j, False) fancy_print("\n", False) fancy_print( "\n\n The map starts from (1, 1) (top-left) and ends at (" + str(len(map_)) + ", " + str(len(map_)) + ") (bottom-right).", flag_) fancy_print("\n\n Legend:\n\n ~ - Calm Water\n # - Disturbed Water (Fired at)\n $ - Sunken Ship", flag_) fancy_print("\n\n Number of hostile ships left: " + str(len(ships_)), flag_) fancy_print("\n Total number of shots: " + str(turns_[0]), flag_) fancy_print("\n Number of shots left: " + str(turns_[1]) + "\n\n\n", flag_) map_print() # DEBUG STATEMENT # fancy_print("\n\n" + str(ships_) + "\n\n", False) # AI function(s) def ship_gen(size): """AI function, for generating the ships""" ships, _ = [], 0 while _ < int(size * 1.25): ship = [int(rand(1, size) - 1), int(rand(1, size) - 1)] # 1st element - Y-Coordinate; 2nd element - # X-Coordinate if ship not in ships: ships.append(ship) _ += 1 return ships # Player function(s) def player_input(map_, ships, turns): """ Player function for getting the player's input (where the player shot at for now) 1st value returned - Y-Coordinate 2nd value returned - X-Coordinate """ def func(flag1, flag2, flag3): """ Internal function for adhering to the 'Stay DRY' (Don't Repeat Yourself) rule. 1st Parameter is for fancy_print() 2nd is for X-/Y-Coordinate 3rd is for error start """ if flag2: if flag3 == 0: fancy_print(" Fire at column (X-Coordinate):", flag1) elif flag3 == 1: cls() base_print(map_, ships, turns, not flag1) cls() fancy_print(" Fire at column (X-Coordinate)", not flag1) fancy_print(" That's not on the map Captain! (0 < coord <= " + str(len(map_)) + ").", flag1) else: if flag3 == 0: fancy_print(" Fire at row (Y-Coordinate):", flag1) elif flag3 == 1: cls() base_print(map_, ships, turns, not flag1) fancy_print(" Fire at row (Y-Coordinate)", not flag1) fancy_print(" That's not on the map Captain! (0 < coord <= " + str(len(map_)) + ").", flag1) coord = int(input(" ")) if coord < 1 or coord > len(map_): raise ValueError else: return coord - 1 flag_1, flag_2, g_x, g_y = True, 0, 0, 0 while flag_1: try: g_x = func(True, True, flag_2) flag_1 = False except ValueError: flag_2 = 1 flag_1 = True while flag_1: try: g_y = func(True, False, flag_2) flag_1 = False except ValueError: flag_2 = 1 return [g_y, g_x] def turns_gen(size): """ Generates the number of turns the player has left 1st value returned - total no. of turns 2nd value returned - no. of turns over """ if int(size ** 2) < int(size * 2.5): # Only true for size == 1, 2 return [size, size] else: return [int(size * 2.25), int(size * 2.25)] def play(): """Runs the game""" def game_print(print_flag, flag__1): """Dynamic game scene printing""" cls() base_print(map_, ships, turns, flag__1) if print_flag == 0: pass elif print_flag == 1: fancy_print("\n\n Captain! We already shot there!", True) elif print_flag == 2: fancy_print("\n\n Captain! Hit reported!\n", True) elif print_flag == 3: fancy_print("\n\n No hit reported Captain!\n", True) return player_input(map_, ships, turns) def game_gen(flag__1, flag__2): """Game generation""" cls() fancy_print("\n\n Enter the board size:", flag__1) if flag__2 == 0: pass elif flag__2 == 1: fancy_print("\n Please enter a valid number! (1 <= size)\n", True) elif flag__2 == 2: fancy_print("\n Board size too large! (size <= 50)\n", True) return input(" ") flag_1, flag_2 = True, 0 while True: try: size = game_gen(flag_1, flag_2) if int(size) <= 0: raise ValueError elif int(size) > 50: raise TypeError else: break except ValueError: flag_1, flag_2 = False, 1 except TypeError: flag_1, flag_2 = False, 2 map_ = map_gen(int(size)) # The game map ships = ship_gen(int(size)) # Contains the coordinates of all hostile ships turns = turns_gen(int(size)) # 1st value - total no. of turns; 2nd value - no. of turns over shots = [] # Contains the coordinates of wherever the player has fired # Game start flag1, flag2, win_flag = 0, True, 0 while turns[1] > 0 and len(ships) > 0: # Making sure there are enough turns and enemy ships guess = game_print(flag1, flag2) flag2 = False if guess in shots: # Checks whether the player already shot there flag1 = 1 elif guess in ships: # Hit reported! shots.append(guess) ships.remove(guess) map_[guess[0]][guess[1]] = " $" flag1 = 2 else: # No hit reported! shots.append(guess) map_[guess[0]][guess[1]] = " #" flag1 = 3 turns[1] -= 1 # Victory / Loss Screen for ship in ships: # For displaying ships on the map map_[ship[0]][ship[1]] == " S" if len(ships) != 0: # Checks if there are ships left win_flag = 2 elif len(ships) == 0: # No ships left (VICTORY!) if turns[1] != 0: # Checks if turns are left win_flag = 1 elif turns[1] == 0: # Checks if turns are over win_flag = 3 cls() base_print(map_, ships, turns, False) if win_flag == 0: fancy_print("\n\n Not sure what happened Captain!\n", True) # ERROR! win_flag doesn't change it's value elif win_flag == 1: fancy_print("\n\n All hostiles down Captain!\n", True) elif win_flag == 2: fancy_print("\n\n Ammunition depleted Captain! We need to go back to the harbour!\n", True) elif win_flag == 3: fancy_print( "\n\n All hostiles down Captain! But our ammunition is depleted! We need to go back to the harbour!\n", True) if win_flag == 1 or win_flag == 3: score = (turns[1] - len(ships)) * 100 fancy_print("\n SCORE: " + score, True) sleep(2.5) return win_flag # Game end flag, menu_op = True, 0 while True: # Menu navigation menu_flag_1, menu_flag_2 = True, 0 while menu_op == 0: try: menu_ans = menu_nav(menu_flag_1, menu_flag_2) if int(menu_ans) < 1 or int(menu_ans) > 3: raise ValueError else: menu_op = int(menu_ans) except ValueError: menu_flag_1, menu_flag_2 = False, 1 if menu_op == 1: cls() play() cls() fancy_print("\n\n Thanks for playing!\n", True) credits_(True) while True: credits_op = input(" ") try: if credits_op.lower() == "m": menu_op = 0 break elif credits_op.lower() == "e": menu_op = 3 break else: raise ValueError except ValueError: cls() fancy_print("\n\n Thanks for playing!\n", False) credits_(False) fancy_print("\n Please enter a valid character (M / E)\n", True) elif menu_op == 2: cls() credits_(True) while True: credits_op = input(" ") try: if credits_op.lower() == "m": menu_op = 0 break elif credits_op.lower() == "e": menu_op = 3 break else: raise ValueError except ValueError: cls() credits_(False) fancy_print("\n Please enter a valid character (M / E)\n", True) elif menu_op == 3: break cls() fancy_print("\n\n Thanks for playing!", True) fancy_print("\n Cleaning up stuff and exiting.", True) sleep(2) fancy_print("\n Bye!", True) sleep(0.5) exit()
import time import sys print("Приветствую вас в своем калькуляторе!\nЗдесь вы сможете сложить/вычесть/умножить/разделить два числа.") a = (input("Введите первое число и нажмите ENTER.\n")) try: a = float(a) except (ValueError) as a: print("до связи.") time.sleep(1.5) sys.exit() b = (input("Введите второе число и нажмите ENTER.\n")) try: b = float(b) except (ValueError) as b: print("до связи.") time.sleep(1.5) sys.exit() znak = input("Введите знак и нажмите ENTER.(+,-,*,/)\n") if znak != '+' and znak != '-' and znak != '*' and znak != '/': print("до связи") time.sleep(1.5) sys.exit() if b == 0 and znak == "/": print("хорошая попытка.") time.sleep(3) sys.exit() if znak == "+": c = (a+b) if str(c)[-2:] == ".0": print("Результат равен:", str(c)[:-2]) else: print("Результат равен:", (c)) if znak == "-": c = (a-b) if str(c)[-2:] == ".0": print("Результат равен:", str(c)[:-2]) else: print("Результат равен:", (c)) if znak == "*": c = (a*b) if str(c)[-2:] == ".0": print("Результат равен:", str(c)[:-2]) else: print("Результат равен:", (c)) if znak == "/": c = (a/b) if str(c)[-2:] == ".0": print("Результат равен:", str(c)[:-2]) else: print("Результат равен:", (c)) input("Работа программы завершена.\nЧтобы выйти из программы,нажмите ENTER.\n")
# Decorators # All Decorators are clousures # demo is decorators function # sayhi is decorated function def demo(a): def inner(b): def innermost(): print("This is innermost -> ", a, b) return innermost return inner @demo("Testing it") def sayhi(): print("Hi from sayhi!") sayhi()
class Animal(): def __init__(self): print("Animal Created!") def who_am_i(self): print("I am an Animal!") class Dog(Animal): def __init__(self, breed): Animal.__init__(self) print("Dog of {}".format(breed)) self.breed=breed def bark(self): print("Woof.. Woof..") def who_am_i(self,var): print("I am Dog.. {}".format(var)) dog = Dog("Mudhol") dog.who_am_i(12) dog.bark()
mdarray=[[3,8],[1,2],[2,1],[1,3],[3,6],[2,4]] print(mdarray) for i in range(len(mdarray)-1,0,-1): for j in range(i): if mdarray[j][1] > mdarray[j+1][1]: temp=mdarray[j+1] mdarray[j+1]=mdarray[j] mdarray[j]=temp print(mdarray)
def main(): A = ['a','d','c','b'] _quicksort(A, 0, len(A)-1) print(A) def partition(xs, start, end): follower = leader = start while leader < end: if xs[leader] <= xs[end]: xs[follower], xs[leader] = xs[leader], xs[follower] follower += 1 leader += 1 xs[follower], xs[end] = xs[end], xs[follower] return follower def _quicksort(xs, start, end): if start >= end: return p = partition(xs, start, end) _quicksort(xs, start, p-1) _quicksort(xs, p+1, end) if __name__ == "__main__": main()
def main(): arr=[3,6,7,4,2,1,8,9,5] print("Array Before Sorting :",arr) bubblesort(arr) print("Array After Sorting :", arr) def bubblesort(args): for i in range(len(args)-1,0,-1): print(i) for j in range(i): if args[j]<args[j+1]: temp=args[j] args[j]=args[j+1] args[j+1]=temp if __name__ == "__main__": main()
# URL :- https://www.hackerearth.com/practice/math/number-theory/basic-number-theory-2/practice-problems/algorithm/sum-of-primes-7/ import math def prime_or_not(num): pr=True if num == 1: return False if num == 2: return True if num % 2 == 0: pr = False else: for k in range(3, int(math.sqrt(num))+2, 2): if num % k == 0: pr = False break return pr testcount = int(input()) for i in range(testcount): myrange = input().split() sum = 0 for n in range(int(myrange[0]), int(myrange[1])+1): if prime_or_not(n): sum += n print(sum)
def switchCase(ltr): if ltr.islower(): return ltr.upper() elif ltr.isupper(): return ltr.lower() else : return ltr mystring="This is 2 PyThOnIc.." cstr=str().join([switchCase(x) for x in mystring]) print(cstr)
words = [ 'word1', 'word2', 'foo'] daSearch = open("foo.txt", "r").read() for word in words: if word in daSearch: print(word) else: print("not found") print("\nDone")
user=str(input("enter the string")) string=input("enter string to be counted") upper=string.upper() lower=string.lower() big=(user.count(upper)) small=(user.count(lower)) Total=big+small print(Total)
# -*- coding: utf-8 -*- """ Created on Mon Oct 21 08:31:46 2019 @author: Michael ODonnell """ # Question: # write a method to replace all spaces in a string with '%20' # You may assume that the string has sufficient space at the end to # hold the addition characters, and that you are given the "true" # length of the string. def replace_spaces(s): # using python's built-in replace function to replace spaces # this question may be more difficult in other languages.. s = s.replace(' ', '%20') print(s) replace_spaces("test string here..")
# -*- coding: utf-8 -*- """ Created on Mon Oct 21 08:33:26 2019 @author: Michael ODonnell """ # Question: # Given a string, write a function to check if it is a permutation of a palindrome. # A palindrome is a word or phrase that is the same forwards and backwards. # A permutation is a rearrangement of the letters. The palindrome does not # need to be limited to only dictionary words. # ex: "Tact Coa" is True, permutation: "taco cat" and "atco cta" def palindrome_perm(s): # first, remove spaces from s and convert to lowercase s = s.replace(' ', '') s = s.lower() # next, make a dict with a key for each char in s s_dict = {} for i in s: if i not in s_dict.keys(): s_dict[i] = 1 else: s_dict[i] = s_dict[i]+1 print(s_dict) # next, make a dict for even and odd values of s_dict even_odd = {'even': 0, 'odd': 0} for j in s_dict.values(): if j%2 == 0: even_odd['even'] = even_odd['even'] + 1 else: even_odd['odd'] = even_odd['odd'] + 1 if even_odd['odd'] <= 1 and len(s)>0: print("Yes, string is a permutation of a palindrome!") else: print("No, string is not a permutation of a palindrome") palindrome_perm("Tact Coa")
# -*- coding: utf-8 -*- """ Created on Thu Oct 24 22:48:26 2019 @author: Michael ODonnell """ # Question # You are given two sorted arrays, A and B. # Write a method to merge B into A in sorted order. A = [] B = [] import random for x in range(10): A.append(random.randint(1,100)) B.append(random.randint(1,100)) print("A:", A) print("B:", B) def merge_sort(A): # for error checking, print each time we're splitting the list print("splitting", A, "into 2 pieces") if len(A)>1: # find the middle of the list middle = len(A) // 2 left_half = A[:middle] right_half = A[middle:] # run this function on the halves recursively merge_sort(left_half) merge_sort(right_half) # create three counters i = 0 j = 0 k= 0 while i < len(left_half) and j < len(right_half): if left_half[i] < right_half[j]: A[k] = left_half[i] i = i+1 else: A[k] = right_half[j] j = j+1 k = k+1 while i < len(left_half): A[k] = left_half[i] i = i+1 k = k+1 while j < len(right_half): A[k] = right_half[j] j = j+1 k = k+1 print("Merging", A) # add list B to list A for y in B: A.append(y) merge_sort(A) print(A)
# Adam Shaat # Check if one number divides another. p = 8 m = 2 if (p % m) == 0: print(p, "divided by", m, "leaves the remainder of zero.") print("I'll be run too if the condition is true.") else: print(p, "divided by", m, "does not leave the remainder of zero.") print("I'll be run too if the condition is false.") print("I'll run no matter what.")
# Adam Shaat # a function to sqaure numbers import math def power(x, y): ans = x y = y - 1 while y > 0: ans = ans * x y = y - 1 return ans def f(x): ans = (100 * power(x, 2) + 10 * power(x, 3)) // 100 ans = ans - (power(x, 3) // 10) return ans def isprime(i): # loop through all values from 2 up to # but not including i. for j in range(2, math.floor(math.sqrt(i))): if i % j == 0: # if it does, i isn't a prime so exit # the loop and indicate it's not prime. return False return True
""" """ # Should do earlier itself def investigate(data)->None: print(data.shape) print(data.info()) print(data.describe()) def drop_nan_columns(data, ratio=1.0)->pd.DataFrame: """ From an initial look at the data it seems like some columns are entirely nan columns (e.g. id, there are 24 such columns) The ratio parameter (0.0<=ratio<1.0) lets you drop columns which has 'ratio'% of nans. (i.e if ratio is 0.8 then all columns with 80% or more entries being nan get dropped) Returns a new dataframe """ col_list = [] na_df = data.isna() total_size = na_df.shape[0] for col in na_df: a = na_df[col].value_counts() if False not in a.keys(): col_list.append(col) elif True not in a.keys(): pass else: if a[True]/total_size >= ratio: col_list.append(col) print(f"{len(col_list)} columns dropped- {col_list}") return data.drop(col_list, axis=1) data = drop_nan_columns(data, ratio=0.5) # Now we've taken out the really useless columns, let's check the other ones so that we get a sense of how many NaN entries the rest of our data has def investigate_nan_columns(data)->None: """ Prints an analysis of the nans in the dataframe Tells us that employment title and length have very few nans, title has barely any nans Upon further looking at the data it seems for employment nans are all unemployed (there is no unemployed category otherwise), length nans is also unemployed """ col_dict = {} na_df = data.isna() total_size = na_df.shape[0] for col in na_df: a = na_df[col].value_counts() if False not in a.keys(): col_dict[col] = 1.0 elif True not in a.keys(): pass else: col_dict[col] = a[True]/total_size print(f"{col_dict}") return investigate_nan_columns(data) # Tells us that employment title and length have very few nans, title has barely any nans # Upon further looking at the data it seems for employment nans are likely all unemployed (there is no unemployed category otherwise), length nans we will use mode filling def handle_nans(data)->None: """ Handle the nans induvidually per column emp_title: make Nan -> Unemployed emp_length: make Nan - > 10+ years this is both mode filling and value filing title: make Nan -> Other """ data['emp_title'] = data['emp_title'].fillna("Unemployed") data['title'] = data['title'].fillna('Other') mode_cols = ['emp_length', 'annual_inc', 'mort_acc'] for col in mode_cols: data[col] = data[col].fillna(data[col].mode()[0]) return handle_nans(data) # Now we're done with handling the NaN values we can check that the dataframe truly has no Nan values any(data.isna().any()) # Now we can look at the data again and actually understand it investigate(data) # Looking at the datatypes it's easy to tell there are a lot of categorical columns (e.g. grade) but right now these are only being read as object or strings. We convert them # We can also safely convert employment length to numbers so that the model can use it as a numerical column # We also need to convert date to a datetime datatype to best use it def handle_types(data, numericals, strings, categoricals): def helper_emp_length(x): if x == "10+ years": return 10 elif x == "2 years": return 2 elif x == "< 1 year": return 0 elif x == "3 years": return 3 elif x == "1 year": return 1 elif x == "4 years": return 4 elif x == "5 years": return 5 elif x == "6 years": return 6 elif x == "7 years": return 7 elif x == "8 years": return 8 elif x == "9 years": return 9 else: return 10 data['emp_length'] = data['emp_length'].apply(helper_emp_length) for category in categoricals: try: data[category] = data[category].astype('category') except: pass data['issue_d'] = data['issue_d'].astype('datetime64') handle_types(data, numericals, strings, categoricals) # And that's it. We have finished an extremely basic cleaning of the dataset. We can now start Exploratory Data Analysis to find deeper patterns in the data. # Now just copy paste each graph function and run it immediately """ Correlation Heatmap Correlation Heatmaps are a great way to spot linear relations between numerical columns in your dataset. The basic theory is that you use an inbuilt pandas function corr to calculate each variables correlation to every other variable Plotting this resulting correlation matrix in a heatmap gives you a sense of which features are correlated to the target variables, hinting at the features you should select or are more important in the model you will make. """ """ From this plot we can clearly see that there is a huge correlation (nearly one to one) with the loan_amnt (Which is the amount requested by the borrower), and the funded amounts (amount funded by investors). This suggests that we probably want to merge these columns as they add dimensionality but do not provide that much extra information From looking at the variables related to interest rates the first observation is that some variables like mortgage account balance and (surprisingly) annual income seem to have nearly no correlation In general the most correlated variable seems to be employment length, we could plot these two variables against each other to get a clearer sense of their relationship Unfortunately overall it seems the numerical variables are not the most correlated, either there is a non-linear relationship in the data or our categorical features are where the bulk of our useful features will be """ """ Distribution Plot Distribution Plots are very similar to histograms and essentially show how data is distributed across its different values. They are extremely useful in finding skews in the data. Most models perform best when the data they deal with is normally distributed (especially linear models). So if we find a skew we may want to apply a skew solution function the variable in order to make it resemble a normal distribution """ """ The extended tail forward gives a clear sign of a positive skew in our interest rate. This means that there are much more lower values than there are high values. Possible solutions we could apply include the square root and log functions """ """ Boxplots Boxplots are an extremely useful way to plot outliers, while also seeing how numerical data varies across different categories. {Read up and insert what boxplots represent} """ """ The insights we can take from each plot (0,0) - This graph tells us nothing about the relation to interest rates, but gives us interesting insights on the economy from which the data was extracted, namely it is likely not a savings based economy. You can tell this by looking at how people who own their houses are not that much wealthier than those who have it on a mortgage. This implies that even when induviudals have enough income to perhaps save an eventually buy a house or a buy a lower grade house they could afford they are opting to take a loan and commit to this expenditure. (0,1) - This graph tells us the intutive idea that cash loans on average are of a smaller sum than DirectPay loans, presumably for security reasons. The suprising observation is the lack of any outliers, implying that this lending institution is a relatively safe one which caps the loans it gives, meaning there isn't a single loan so high that it would count as an outlier. (1,0) - This graph suggests that verification status does seem to have a relationship with interest rate. The average steadily increases the more verfified the borrower is. (1,1) - This graph is interesting as it seems like the grade of the borrower is low if they either worked in a particular job for very little (less than 1 year or 1 year) or if they have worked the same job for very long (9, 10 years). This suggest some sort of aversion to inexperience, but also stagnation in one job, considering both to be factors that make a loan more risky. """ """ LinePlots Good for seeing trends in data between induvidual variables """ """ It seems interest rate vs employment length mirrors the relationship between grade and enployment length witnessed in the boxplot above, presumably for the same reasons. The interest rate for people who have worked less than a year seems low though, possibly this is because these are small buisness or enterprise loans that are valued at a lower interest rate so that the buisness itself has a greater chance of success and thus repaying the loan. """ """ Scatter Plot The most basic type of plot, but we will scatter averages because otherwise the graph will be too dense for us to actually learn anything """ """ Clearly there is a massive relationship between subgrade and interest rate. This makes it the best feature we have seen so far, and understandably so because the interest rate is in most cases a function of the risk of a loan. """ """ Etc. The rest of the plots are various different plots which show relationships in the data 3D scatter Violin Plot Bubble plot """ # Exploratory Data Analysis done. Now we will prepare our data for the model # First let us define a function to split data and return it to us. This is useful because we want to be very sure of what manipulations we are doing to test data, in order to ensure we aren't cheating def load_split_data(number_of_rows=None, purpose=None, column='int_rate', test_size=0.2): from sklearn.model_selection import train_test_split data = load_data(number_of_rows=number_of_rows, purpose=purpose) target = data[column] data.drop(column, axis=1, inplace=True) return train_test_split(data, target, test_size=test_size) X_train, X_test, y_train, y_test = load_split_data(size, purpose="time_of_issue") X_train = drop_nan_columns(X_train, ratio=0.5) X_test = drop_nan_columns(X_test, ratio=0.5) handle_nans(X_train) handle_nans(X_test) handle_types(X_train, numericals, strings, categoricals) handle_types(X_test, numericals, strings, categoricals) # For this notebook we will ignore the string variables, however there are ways to use them using other prepreocessing techniques if desired X_train = X_train.drop(strings, axis=1) X_test = X_test.drop(strings, axis=1) timing.timer("Cleaned Data") # First, let us fix the skew that we saw in the distribution plot using the square root transformation def manage_skews(train_target, test_target): """ Applying Square Root in order """ return np.sqrt(train_target), np.sqrt(test_target) y_train, y_test = manage_skews(y_train, y_test) # Next, we should normalize all of our data, this once again simply makes most models more effective and speeds up convergence def scale_numerical_data(X_train, X_test, numericals): from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train[numericals] = sc.fit_transform(X_train[numericals]) X_test[numericals] = sc.transform(X_test[numericals]) return scale_numerical_data(X_train, X_test, numericals) timing.timer("Scaled Data") """ Finally we will encode all of our categorical variables so that models can process them, but before we do that, we need to realize something about the size of our dataset i.e if you look at the columns such as employment title you can already see a whole bunch of different occupations """ data['emp_title'].value_counts() """ There are other columns, like purpose, that have this same issue. When there are so many different categories the model is likely to get extremely confused or is just unlikely to generalize well. Additionally there is also a harm that once we fit an encoder onto our categorical columns, then there will be a completely new profession in the test set that the encoder hasn't seen before, this would throw an exception To solve this problem we keep only the instances that make up the top 15 categories of that variable, and cast the rest to a standard value like "Other" """ def shrink_categoricals(X_train, X_test, categoricals, top=25): """ Mutatues categoricals to only keep the entries which are the top 25 of the daframe otherwise they become other """ for category in categoricals: if category not in X_train.columns: continue tops = X_train[category].value_counts().index[:top] def helper(x): if x in tops: return x else: return "Other" X_train[category] = X_train[category].apply(helper) X_test[category] = X_test[category].apply(helper) shrink_categoricals(X_train, X_test, categoricals) timing.timer("Shrunk Categories") data['emp_title'].value_counts() # Now we can encode and transform our categorical data safely def encode_categorical_data(X_train, X_test, categoricals): from sklearn.preprocessing import LabelEncoder for category in categoricals: if category not in X_train.columns: continue le = LabelEncoder() X_train[category] = le.fit_transform(X_train[category]) X_test[category] = le.transform(X_test[category]) #X_test[category] = le.transform(X_test[category]) return encode_categorical_data(X_train, X_test, categoricals) timing.timer("Encoded Data") """ We are nearly done with our data processing. The final step is to run a dimensionality reduction algorithm. Having many dimensions to data can make training models significantly slower and also sometimes less accurate as well. We will use PCA, an algorithm which tries to project data into lower dimensions while preserving as much entropy as possible. Instead of stating how many dimensions the PCA algorithm should project down to, we will simply state what percentage of entropy we would like preserved, 95% is a good standard bar. The reason we are doing the step last is because after the PCA it is virtually impossible to figure out what each column represents in terms of the original data. s """ def dimensionality_reduction(X_train, X_test): from sklearn.decomposition import PCA pca = PCA(n_components=0.95) X_train = pca.fit_transform(X_train) X_test = pca.transform(X_test) return X_train, X_test X_train, X_test = dimensionality_reduction(X_train, X_test) X_train.shape() """ From over 20 columns to only 4! While it may seem like we ought to have lost a lot of data the 95% of entropy being saved ensures we have preserved most core patterns. You could do the notebook without the above step to see how much slower the training of the models is without this step """ # We are finally onto the modelling stage. We will create 4 different models - Random Forest, Support Vector Machine, Linear Regression, KNearestNeighbors and fine-tune them using scikit-learn Literally copy paste all of the models # Now we find the best hyperparameters for each model """ From these models, while all of them have a decent mse loss the SVM clearly performs best, let us use an averaging ensemble technique to combine the models and see if it improves the loss Unfortunately the ensemble doesn't perform any better than the SVM in this case. Finally we will try to use a Boosting technique -Gradient Boosting, Gradient Boosting has a simple theory a prelimnary model is trained on a dataset, and its residual errors are recorded. Another model is then trained to model these residual errors, the sum of the induvidual predictions is considered the prediction of the overall system. Scikit-Learn has an inbuilt GradientBoostingRegressor, but this uses Decision trees as its fundamental unit. We would rather use the SVM that is performing so well induvidually, so we will have to manually define the class Now we can train and test all of these models to compare them. Unfortunately even Gradient Boosting could not reduce the error beyond the SVM. Let us visualize our models accuracy now to get a sense of how close we are to the true interest rate. Thank you for viewing this Kernel. The notebook is a work in progress and will be updated as per feedback and future ideas. """ Check All docstrings All plot legends
# File: integrate_parsed_data.py # Purpose: to combine the county level data produced by the other two python scripts, adn potentially do some analysis # Date: 2/23/2021 import pandas import itertools # Calculate the pearson correlation coefficient, and draw a graph if the coefficient value is less than -0.5 or greater than 0.5 # - column1: the name of the first column we will use to calculate the pearson correlation coefficient # - column2: the name of the second column we will use to calculate the pearson correlation coefficient # - data: the dataframe you are calculating the coefficient and drawing the graph from # - isOregon: a boolean indicating if the data is Oregon data (as opposed to national USA data) def calculateR(column1, column2, data, isOregon): R = data[column1].corr(data[column2]) if (R > 0.5 or R < -0.5): plotName = column1 + "-" + column2 + ".png" if (isOregon == True): plotName = "Oregon-" + plotName data.plot.scatter(column1, column2).get_figure().savefig("graphs/" + plotName) # Read in CSVs censusData = pandas.read_csv("data/parsed_census_data.csv") covidData = pandas.read_csv("data/parsed_covid_data.csv") # Combine data combined_data = censusData.merge(covidData, how='inner') #combined_data.to_csv("data/combined_data.csv", index=False) # Calculate the correlation between columns for all counties in the state of Oregon oregon_data = combined_data[combined_data['State'] == "Oregon"] calculateR("TotalCases", "Poverty", oregon_data, True) calculateR("TotalDeaths", "Poverty", oregon_data, True) calculateR("TotalCases", "IncomePerCapita", oregon_data, True) calculateR("TotalDeaths", "IncomePerCapita", oregon_data, True) calculateR("Dec2020Cases", "Poverty", oregon_data, True) calculateR("Dec2020Deaths", "Poverty", oregon_data, True) calculateR("Dec2020Cases", "IncomePerCapita", oregon_data, True) calculateR("Dec2020Deaths", "IncomePerCapita", oregon_data, True) # Calculate the correlation between columns for all counties calculateR("TotalCases", "Poverty", combined_data, False) calculateR("TotalDeaths", "Poverty", combined_data, False) calculateR("TotalCases", "IncomePerCapita", combined_data, False) calculateR("TotalDeaths", "IncomePerCapita", combined_data, False) calculateR("Dec2020Cases", "Poverty", combined_data, False) calculateR("Dec2020Deaths", "Poverty", combined_data, False) calculateR("Dec2020Cases", "IncomePerCapita", combined_data, False) calculateR("Dec2020Deaths", "IncomePerCapita", combined_data, False)
arr = input() arr = arr.split() sums = 0 set = [] x = 0 set.append(sums) for i in range(len(arr)): sums = sums + int(arr[i]) if (sums in set): x = 1 break else: set.append(sums) if (x == 1): print('exists') else: print('not exists') ''' Explaination: We create a set which stores sum of the elemnents at each iteration. First element of that set is 0. It is kept in order to find wether sum at any stage ever gets to zero or not. Problem-Statement:https://www.techiedelight.com/check-subarray-with-0-sum-exists-not/ '''
""" Hello, I'm a Python program for suggesting words based on Project Gutenberg books. Before you start using me please do: $ python3 -m nltk.downloader punkt To use me type: $ python3 whats_next.py --book-id <book id> --query <your query> For example: $ python3 whats_next.py --book-id 46 --query god bless I seem to return ['us'] in these conditions. I also accept more than one parameter foor book id. You can consult my help documentation: python3 whats_next.py --help I wanted to be much more, but I'm a Python program. Without the comments I'm not that big - you can combine me in one method, in around 100 lines of code. Also I wanted to have threads but I'm more slow with them. Don't ask me why... Have fun! """ import argparse from gutenberg.acquire import load_etext from gutenberg.cleanup import strip_headers from argparse_validators import required_length from text_indexer import TextIndexer def main(): """ The main method. """ parser = argparse.ArgumentParser( description='Word suggestion based on Project Gutenberg books.') parser.add_argument('--book-id', dest='book_ids', nargs='+', type=int, required=True, help='the book id of the Project Gutenberg') parser.add_argument('--query', nargs='+', type=str, required=True, help='suggest next word for list of string', action=required_length(1, 5)) try: args = parser.parse_args() text_indexer = TextIndexer(len(args.query)) for book_id in list(dict.fromkeys(args.book_ids)): text = strip_headers(load_etext(book_id)).strip() text_indexer.add_text(book_id, text) print(text_indexer.suggest(*args.query)) except Exception as exc: # pylint: disable=W0703 print(exc) if __name__ == "__main__": main()
# Joan Quintana Compte-joanillo. Assignatura CNED (UPC-EEBE) ''' ZF-52: xln(x)-1, trobar el 0 pel mètode de la bisecció https://www.math.ubc.ca/~pwalls/math-python/roots-optimization/bisection/ cd /home/joan/UPC_2021/CNED/apunts/python/T1/ PS1="$ " python3 biseccio1.py ''' import matplotlib import matplotlib.pyplot as plt import numpy as np import os # ============== os.system("clear") titol = 'script ' + os.path.basename(__file__) + '\n' for i in range(0,len(titol)-1): titol = titol + '=' print(titol) # ============== def bisection(f,a,b,N): '''Approximate solution of f(x)=0 on interval [a,b] by bisection method. Parameters ---------- f : function The function for which we are trying to approximate a solution f(x)=0. a,b : numbers The interval in which to search for a solution. The function returns None if f(a)*f(b) >= 0 since a solution is not guaranteed. N : (positive) integer The number of iterations to implement. Returns ------- x_N : number The midpoint of the Nth interval computed by the bisection method. The initial interval [a_0,b_0] is given by [a,b]. If f(m_n) == 0 for some midpoint m_n = (a_n + b_n)/2, then the function returns this solution. If all signs of values f(a_n), f(b_n) and f(m_n) are the same at any iteration, the bisection method fails and return None. ''' if f(a)*f(b) >= 0: print("Bisection method fails.") return None a_n = a b_n = b for n in range(0,N): m_n = (a_n + b_n)/2 f_m_n = f(m_n) print ('-----') print ('it',n) print ('a',m_n) print('fxk =',f_m_n) if f(a_n)*f_m_n < 0: a_n = a_n b_n = m_n elif f(b_n)*f_m_n < 0: a_n = m_n b_n = b_n elif f_m_n == 0: print("Found exact solution.") return m_n else: print("Bisection method fails.") return None return (a_n + b_n)/2 # ============================== f = lambda x: x*np.log(x)-1 approx_phi = bisection(f,.5,2,5) print('=====') print('resultat:',approx_phi) # ============================== x = np.arange(0.5, 2.0, 0.005) y = x*np.log(x) - 1 fig, ax = plt.subplots() ax.plot(x, y) ax.set(xlabel='x', ylabel='y', title='xln(x) - 1') ax.grid() fig.savefig("../img/T1/ZF-52_biseccio1.png") plt.show()
import codecs import json import re # import matplotlib.pyplot as plt import pylab as plt import numpy as np class TextAnalyses: """ Use this once the text tokens have been extracted; e.g. on the readability_tokens.json file. The most important thing we need to do is document frequency generation """ @staticmethod def print_doc_histogram_tokens_count(tokens_file): """ get tokens count in each doc in tokens file and plot histogram. Will display file. """ count = 1 tokens_count = dict() tokens_count[0] = 0 tokens_count[1000] = 0 tokens_count[5000] = 0 tokens_count[10000] = 0 keys = [0,1000,5000,10000] with codecs.open(tokens_file, 'r', 'utf-8') as f: for line in f: obj = json.loads(line) for k, val in obj.items(): if len(val) >= keys[-1]: tokens_count[keys[-1]] += 1 break for i in range(0, len(keys)-1): if len(val)>=keys[i] and len(val)<keys[i+1]: tokens_count[keys[i]] += 1 if count % 10000 == 0: print count count += 1 # plt.hist(np.array(tokens_count)) print tokens_count # plt.title("Docs histogram per tokens-count") # plt.xlabel("Value") # plt.ylabel("Frequency") # # fig = plt.gcf() # plt.show() @staticmethod def print_word_statistics(tokens_file, limit=None): """ :param tokens_file: The tokens file that is also used for generating the embeddings :param limit: If not none, we will count statistics over only the first limit objects in tokens_file :return: None """ count = 1 unique_words = 0 total_words = 0 with codecs.open(tokens_file, 'r', 'utf-8') as f: for line in f: obj = json.loads(line) v = None for k, val in obj.items(): v = val print 'In document ' + str(count) count += 1 if limit and count>limit: break unique_words += len(set(v)) total_words += len(v) print 'num total words: ', print total_words print 'num unique words: ', print unique_words @staticmethod def read_in_and_prune_idf(df_file, lower_prune_ratio=0.0005, upper_prune_ratio=0.5): """ :param idf_file: e.g. readability_tokens_df.txt :param lower_prune_ratio: any token with ratio strictly below this gets discarded :param upper_prune_ratio: any token with ratio strictly above this gets discarded :return: A dictionary of tokens with their idfs """ idf = dict() with codecs.open(df_file, 'r', 'utf-8') as f: for line in f: fields = re.split('\t',line[:-1]) if len(fields) != 3: print 'error in splitting df file' print line elif float(fields[2])>lower_prune_ratio and float(fields[2])<upper_prune_ratio: idf[fields[0]] = fields[2] print 'total number of words in idf dict : ', print len(idf) return idf # @staticmethod # def convolve_idf_dicts(): @staticmethod def generate_document_frequencies(tokens_list_file, output_file, inner_field = None): """ In the output_file, each line contains three tab delimited fields: the first field is the token, the second field is the count of documents in which that token occurred, the third field is a percentage. IMP.: We increase df count of every token by one, and increase the total number of documents by one. The idea is that there is a 'mega' document that contains all possible tokens. This avoids uncomfortable issues like dividing by zero. :param tokens_list_file: Each line in the file is a json, with an identifier referring to a list of tokens :param output_file: :param inner_field: if None, then each read-in dictionary is a single key-value pair, with the value being the list of tokens. Otherwise, the 'value' itself is a dictionary and we reference the inner field of that dictionary. This distinction is particularly useful for phone embeddings e.g. :return: None """ df = dict() # the key is the token, the value is the count total = 0 with codecs.open(tokens_list_file, 'r', 'utf-8') as f: for line in f: total += 1 obj = json.loads(line) if not inner_field: for k, v in obj.items(): forbidden = set() for token in v: if token in forbidden: continue if token not in df: df[token] = 1 forbidden.add(token) else: df[token] += 1 forbidden.add(token) elif inner_field: forbidden = set() v =obj.values()[0][inner_field] for token in v: if token in forbidden: continue if token not in df: df[token] = 1 forbidden.add(token) else: df[token] += 1 forbidden.add(token) out = codecs.open(output_file, 'w', 'utf-8') print 'num objects processed: ', print total for k,v in df.items(): string = k+'\t'+str(v)+'\t'+str((v+1)*1.0/(total+1))+'\n' out.write(string) out.close() # RWP_path = '/Users/mayankkejriwal/ubuntu-vm-stuff/home/mayankkejriwal/Downloads/lorelei/reliefWebProcessed-prepped/tokens/' # data_path = '/Users/mayankkejriwal/datasets/companies/' # bioInfoPath = '/Users/mayankkejriwal/datasets/bioInfo/2016-11-08-intact_mgi_comparison/' # path='/Users/mayankkejriwal/datasets/memex-evaluation-november/persona-linking/' # companiesPath = '/Users/mayankkejriwal/datasets/companies/' # TextAnalyses.print_doc_histogram_tokens_count(companiesPath+'result-prepped.jl') # TextAnalyses.print_word_statistics(path+'readability_tokens-part-00000-onlyLower.json', 100000) # data_path = '/Users/mayankkejriwal/datasets/nyu_data/' # CP1SummerPath = '/Users/mayankkejriwal/datasets/memex-evaluation-november/CP-1-november/' # TextAnalyses.generate_document_frequencies(path+'tokens-all.jl', # path+'tokens-all-df.txt') # path+'all_tokens-part-00000-onlyLower-1-df.txt', inner_field='tokens_list')
import math def logcount(arr, a, b): # Check base case if len(arr) == 0: return 0 middle = math.floor(len(arr)/2) if arr[middle] > b: # print('greater' + str(arr)) return logcount(arr[:middle], a, b) elif arr[middle] < a: # print('less' + str(arr)) return logcount(arr[middle + 1:], a, b) else: # print('equal' + str(arr)) return 1 + logcount(arr[:middle], a, b) + logcount(arr[middle + 1:], a, b) def main(): # Testing arr = [2, 3, 5, 5, 6, 9, 12] arr1 = [10] arr2 = [5,5,5,5,5] a = 3.7 b = 6.1 print(logcount(arr2, a, b)) if __name__ == '__main__': main()
import collections import itertools import operator operators = { "<": operator.lt, "<=": operator.le, "==": operator.eq, "is": operator.eq, # Note: not pure python `is`! "iis": lambda x, y: x.lower() == y.lower(), "!=": operator.ne, "<>": operator.ne, "not": operator.ne, "inot": lambda x, y: x.lower() != y.lower(), ">=": operator.ge, ">": operator.gt, "has": operator.contains, "ihas": lambda x, y: y.lower() in x.lower(), "nothas": lambda x, y: not operator.contains(x, y), "in": lambda x, y: operator.contains(y, x), "notin": lambda x, y: not operator.contains(y, x), # No iin because in normally doesn't take string inputs "len": lambda x, y: len(x) == y, } def try_op(f, x, y): try: return f(x, y) except: return False class Dictionaries: """Pretends to be a single dictionary when applying a ``Query`` to multiple databases. Usage: first_database = Database(...).load() second_database = Database(...).load() my_joined_dataset = Dictionaries(first_database, second_database) search_results = Query(filter_1, filter_2)(my_joined_dataset) """ def __init__(self, *args): self.dicts = args def items(self): return itertools.chain(*[x.items() for x in self.dicts]) class Result: """A container that wraps a filtered dataset. Returned by a calling a ``Query`` object. A result object functions like a read-only dictionary; you can call ``Result[some_key]``, or ``some_key in Result``, or ``len(Result)``. The dataset can also be sorted, using ``sort(field)``; the underlying data is then a ``collections.OrderedDict``. Args: * *result* (dict): The filtered dataset. """ def __init__(self, result): self.result = result if not isinstance(result, dict): raise ValueError("Must pass dictionary") def __str__(self): return "Query result with %i entries" % len(self.result) def __repr__(self): if not self.result: return "Query result:\n\tNo query results found." data = list(self.result.items())[:20] return "Query result: (total %i)\n" % len(self.result) + "\n".join( ["%s: %s" % (k, v.get("name", "Unknown")) for k, v in data] ) def sort(self, field, reverse=False): """Sort the filtered dataset. Operates in place; does not return anything. Args: * *field* (str): The key used for sorting. * *reverse* (bool, optional): Reverse normal sorting order. """ self.result = collections.OrderedDict( sorted( self.result.items(), key=lambda t: t[1].get(field, None), reverse=reverse, ) ) # Generic dictionary methods def __len__(self): return len(self.result) def __iter__(self): return iter(self.result) def keys(self): return self.result.keys() def items(self): return self.result.items() def items(self): return self.result.items() def __getitem__(self, key): return self.result[key] def __contains__(self, key): return key in self.result class Query: """A container for a set of filters applied to a dataset. Filters are applied by calling the ``Query`` object, and passing the dataset to filter as the argument. Calling a ``Query`` with some data returns a ``Result`` object with the filtered dataset. Args: * *filters* (filters): One or more ``Filter`` objects. """ def __init__(self, *filters): self.filters = list(filters) def add(self, filter_): """Add another filter. Args: *filter_* (``Filter``): A Filter object. """ self.filters.append(filter_) def __call__(self, data): for filter_ in self.filters: data = filter_(data) return Result(data) class Filter: """A filter on a dataset. The following functions are supported: * "<", "<=", "==", ">", ">=": Mathematical relations * "is", "not": Identity relations. Work on any Python object. * "in", "notin": List or string relations. * "iin", "iis", "inot": Case-insensitive string relations. * "len": Length relation. In addition, any function which defines a relationship between an input and an output can also be used. Examples: * All ``name`` values are *"foo"*: ``Filter("name", "is", "foo")`` * All ``name`` values include the string *"foo"*: ``Filter("name", "has", "foo")`` * Category (a list of categories and subcategories) includes *"foo"*: ``Filter("category", "has", "foo")`` Args: * *key* (str): The field to filter on. * *function* (str or object): One of the pre-defined filters, or a callable object. * *value* (object): The value to test against. Returns: A ``Result`` object which wraps a new data dictionary. """ def __init__(self, key, function, value): self.key = key self.function = function self.value = value if not callable(function): self.function = operators.get(function, None) if not self.function: raise ValueError("No valid function found") def __call__(self, data): return dict( ( (k, v) for k, v in data.items() if try_op(self.function, v.get(self.key, None), self.value) ) ) def NF(value): """Shortcut for a name filter""" return Filter("name", "has", value) def PF(value): """Shortcut for a reference product filter""" return Filter("reference product", "has", value)
from collections import Counter occurrences = Counter(input().strip()) sorted_occurrences = sorted(occurrences.items(), key=lambda x: (-x[1], x[0])) print(sep='\n', *['{} {}'.format(symbol, count) for symbol, count in sorted_occurrences[:3]])
import sys def sub_strings_count(string, sub_string): sub_strings_count = 0 string_length = len(string) sub_string_length = len(sub_string) for i in range(0, string_length): if i + sub_string_length > string_length: break all_matched = True for sub_i in range(0, sub_string_length): if not string[i + sub_i] == sub_string[sub_i]: all_matched = False if all_matched: sub_strings_count += 1 return sub_strings_count [string, sub_string] = list(sys.stdin) print(sub_strings_count(string, sub_string))
import re N = int(input()) emails = (input().strip() for _ in range(0, N)) valid_email = re.compile(r''' # It must have the [email protected] format type. # The username can only contain letters, digits, dashes and underscores. # The website name can only have letters and digits. # The maximum length of the extension is 3. ^ [\w-]+ # username @ [^\W_]+ # websitename \. .{,3} # extension $ ''', re.X) print(sorted(filter(lambda email: valid_email.search(email), emails)))
def sub_string_count(string, predicate): sub_string_count = 0 string_len = len(string) for i in range(0, string_len): if predicate(string[i]): sub_string_count += string_len - i return sub_string_count def is_vowel(letter): return letter in 'AEIOU' def is_consonant(letter): return not is_vowel(letter) string = input() stuart = sub_string_count(string, is_consonant) kevin = sub_string_count(string, is_vowel) if stuart > kevin: print('Stuart {}'.format(stuart)) elif kevin > stuart: print('Kevin {}'.format(kevin)) else: print('Draw')
def multiplication_table(x = 1): x = int(x) for i in range(1,11,1): print(x,"X",i,'=',x*i) y = input("Write an Integer and Press Enter") multiplication_table(y) multiplication_table()
saarc = ["Afganistan", "Bangladesh", "Bhutan", "Nepal", "India", "Pakistan", "Sri Lanka"] country = input("Type a Country name and press Enter ") if country in saarc: print(country, "is in Saarc!") else: print(country, "is not in Saarc!") print(type(country)) print("Program Terminated!")
import turtle height = 5 width = 5 turtle.speed(2) turtle.penup() for y in range(height): for x in range(width): turtle.dot() turtle.forward(20) turtle.backward(20*width) turtle.right(90) turtle.forward(20) turtle.left(90) turtle.exitonclick()
""" Functions for handling pareto fronts """ import itertools import collections def dominates(a, b): return (a[1] > b[1] or a[2] > b[2]) and a[1] >= b[1] and a[2] >= b[2] def not_dominates(a, b): return a[1] <= b[1] or a[2] <= b[2] def generate_zipped_from_fronts(fronts): """ Not only does this function flatten the fronts into a single list, it also tags the individuals with an index corresponding to which front they are in, higher being better """ zipped = list() top = len(fronts) for front_index, front in enumerate(fronts): zipped += [(top - front_index, individual[1], individual[2], individual[3]) for individual in front] return zipped def generate_fronts(zipped): """ Generates a list of pareto fronts from a possibly unsorted list of zipped individuals """ fronts = list() zipped = list(zipped) zipped.sort(key=lambda x: -x[1]) while zipped: best_secondary = -999999 front = list() new_zipped = collections.deque() for individual in zipped: if individual[2] > best_secondary or (individual[2] == best_secondary and individual[1] == front[-1][1]): best_secondary = individual[2] front.append(individual) else: new_zipped.append(individual) fronts.append(front) zipped = new_zipped return fronts def verify_fronts(fronts): for front_index, front in enumerate(fronts): for lesser_front in itertools.islice(fronts, front_index, None): for better, lesser in itertools.product(front, lesser_front): if dominates(lesser, better): return False return True def add_to_pareto_fronts(fronts, individual): for front_index, front in enumerate(fronts): alive_mask = [True] * len(front) for member_index, member in enumerate(front): if individual[1] > member[1] and individual[2] > member[2]: alive_mask[member_index] = False if front_index >= len(fronts) - 1: fronts.append(list()) fronts[front_index + 1].append(member) elif individual[1] < member[1] and individual[2] < member[2]: break else: front.append(individual) front[:] = itertools.compress(front, alive_mask) break # TODO: Insert into fronted zipped list def get_best_front(zipped): best_front = zipped[0][0] return itertools.takewhile(lambda x: x[0] == best_front, zipped) def compare_fronts(a, b): # Label the two fronts assert len(a[0]) == 4 a = [(0, x[1], x[2], x[3]) for x in a] b = [(1, x[1], x[2], x[3]) for x in b] # Generate a new set of fronts from the combination of them combined = generate_fronts(a + b) # Count tags in top front from_a = sum(1 for x in combined[0] if x[0] == 0) return from_a / float(len(combined[0])) def fronts_equal(a, b): if len(a) != len(b): return False for a_x, b_x in itertools.izip(a, b): if a_x[1] != b_x[1] or a_x[2] != b_x[2]: return False return True
from collections import deque class queue: def __init__(self): super().__init__() self.queue = deque() def enqueue(self, item): self.queue.append(item) def dequeue(self): if len(self.queue) == 0: return None else: return self.queue.popleft() def __str__(self): return str(self.queue) my_queue = queue() my_queue.enqueue(1) my_queue.enqueue(2) my_queue.enqueue(3) my_queue.enqueue(4) print(my_queue.dequeue()) print(my_queue)
def sortboxes(boxes): for i in range(len(boxes)): mid = sum(boxes[i]) - min(boxes[i]) - max(boxes[i]) low = min(boxes[i]) high = max(boxes[i]) boxes[i][0] = low boxes[i][1] = mid boxes[i][2] = high # Input: box_list is a list of boxes that have already been sorted # sub_set is a list that is the current subset of boxes # idx is an index in the list box_list # all_box_subsets is a 3-D list that has all the subset of boxes # Output: generates all subsets of boxes and stores them in all_box_subsets def sub_sets_boxes (box_list, sub_set, idx, all_box_subsets): ln = len(box_list) if idx == ln: all_box_subsets.append(sub_set) return else: sub_set2 = sub_set[:] sub_set.append(box_list[idx]) sub_sets_boxes(box_list, sub_set, idx + 1, all_box_subsets) sub_sets_boxes(box_list, sub_set2, idx + 1, all_box_subsets) def clean(lst): i = 1 while i < len(lst): if lst[i][0] == lst[i - 1][0]: if lst[i][1] < lst[i - 1][1]: a = lst[i] lst[i] = lst[i - 1] lst[i - 1] = a elif lst[i][1] == lst[i - 1][1]: if lst[i][2] < lst[i - 1][2]: a = lst[i] lst[i] = lst[i - 1] lst[i - 1] = a i += 1 # goes through all the subset of boxes and only stores the # largest subsets that nest in the 3-D list all_nesting_boxes # largest_size keeps track what the largest subset is def largest_nesting_subsets(all_box_subsets,largest_size, all_nesting_boxes): anb = all_nesting_boxes largest_size = 0 for i in all_box_subsets: length = len(i) if (largest_size > length): continue x = 1 for j in range(length - 1): if not does_fit(i[j], i[j + 1]): x = 0 if (x == 1): if (largest_size < length): largest_size = length anb.clear() anb.append(i) elif (largest_size == length): anb.append(i) # Input: box1 and box2 are the dimensions of two boxes # Output: returns True if box1 fits inside box2 def does_fit (box1, box2): return ((box1[0] < box2[0]) and (box1[1] < box2[1]) and( box1[2] < box2[2])) #Sort each box by dimension, then sort boxes by the first dimension #return all largest nesting subsets def main(boxes): sortboxes(boxes) boxes.sort(key = lambda x: x[0]) clean(boxes) clean(boxes) box_list = [] sub_set = [] sub_sets_boxes (boxes, sub_set, 0, box_list) largest_size = 0 all_nesting_boxes = [] largest_nesting_subsets(box_list, 0, all_nesting_boxes) return all_nesting_boxes
def greedy (grid): summ=grid[0][0] leng=len(grid) i=1 j=0 while i<leng: if grid[i][j]>=grid[i][j+1]: summ+=grid[i][j] else: j+=1 summ+=grid[i][j] i+=1 return summ def main(grid): return greedy(grid)
# Schoenfinkeling decorator def schoenfinkeled(fun): def new_fun(args): try: return fun(args) except TypeError: # Returns a function with n-1 arguments aux = lambda *myArgs: fun(args, *myArgs) # Recursively applies schoenfinkeling return schoenfinkeled(aux) return new_fun @schoenfinkeled def myfun(a,b,c): return a + b + c # TypeError #print(myfun(1, 2, 3)) f = myfun(11)(1)(2) print (f) g = myfun(77) h = g(1) i = h(4) print (i)
# Generator function which acts as an iterator over ngrams of a string. def ngrams (size, s): a, b = 0, size i = 0 while i <= (len(s)-size): yield s[a:b] a += 1 b += 1 i += 1 s = "the quick red fox jumps over the lazy brown dog" for x in ngrams(3, s.split()): print (x)
import turtle as t import random score = 0 playing = False counter = 0 shadow = False booster = 1 def create_turtle(name, color,x,y,role): global test if role == 0: name.shape("turtle") else: name.shape("circle") name.color(color) name.speed(0) name.up() name.goto(x,y) ta = t.Turtle() create_turtle(ta,"red",-100,200,0) ta2 = t.Turtle() create_turtle(ta2,"red",100,200,0) ts = t.Turtle() create_turtle(ts,"green",0,-200,1) sh = t.Turtle() create_turtle(sh,"blue",100,-200,1) def turn_right(): t.setheading(0) def turn_up(): t.setheading(90) def turn_left(): t.setheading(180) def turn_down(): t.setheading(270) def boost(): global booster if booster > 0: t.forward(100) booster = booster - 1 def start(): global playing if playing == False: playing = True t.clear() play() def atta(atk): global score global counter global shadow global booster if random.randint(1, 5) == 2: ang = atk.towards(t.pos()) atk.setheading(ang) speed = score + 5 if speed > 15: speed = 15 atk.forward(speed) if t.distance(ts) < 12: score = score + 1 t.write(score) star_x = random.randint(-230, 230) star_y = random.randint(-230, 230) ts.goto(star_x, star_y) shadow = False booster=booster + 1 if t.distance(sh) <12: score = score + 1 star_x = random.randint(-230, 230) star_y = random.randint(-230, 230) sh.goto(star_x, star_y) shadow = True booster= booster + 1 def play(): global playing global score global shadow global booster t.forward(10) atta(ta) atta(ta2) if shadow : t.bgcolor("red") else: t.bgcolor("purple") if t.distance(ta) <= 12 or t.distance(ta2) <= 12: text = "Score : "+str(score) message("You are caught.", text, "if you want to do it again, pressthe space key") playing = False score = 0 booster = 0 t.onkeypress(start, "space") if playing : t.ontimer(play, 100) def message(m1, m2, m3): t.clear() t.goto(0, 100) t.write(m1, False, "center", ("", 20)) t.goto(0, -100) t.write(m2, False, "center", ("", 15)) t.goto(0, -150) t.write(m3, False, "center", ("", 10)) t.home() t.setup(500, 500) t.bgcolor("purple") t.shape("turtle") t.speed(0) t.up() t.color("white") t.onkeypress(turn_right,"Right") t.onkeypress(turn_up, "Up") t.onkeypress(turn_left, "Left") t.onkeypress(turn_down, "Down") t.onkeypress(start, "space") t.onkeypress(boost, "b") t.listen() t.mainloop()
def bubble(x, ascending=True): if len(x) == 0: # X의 요소가 없는 경우 함수 실행 안함 return False try: x = list(x) # X를 리스트로 변환할 수 없는 경우 함수 실행 안함 except: return False if ascending: # ascending 인자의 값이 True인 경우 오름차순 정렬 for i in range(0, len(x)-1): for j in range(0, len(x)-i-1): if x[j] > x[j+1]: temp = x[j] x[j] = x[j+1] x[j+1] = temp return x else: # ascending 인자의 값이 True인 경우 내림차순 정렬 for i in range(0, len(x)-1): for j in range(0, len(x)-i-1): if x[j] < x[j+1]: temp = x[j] x[j] = x[j+1] x[j+1] = temp return x if __name__ == '__main__': import random before = random.sample(range(1, 100), 10) print(before) after = bubble(before) print(after) before = random.sample(range(1, 100), 10) print(before) after = bubble(before, False) print(after)
import bubble import insertion import merge_sort import quick import selection def unsorted(): import random before = random.sample(range(1, 1000000), 10000) return before if __name__ == '__main__': import time before = unsorted() print(before) # bubble start_b = time.time() sorted_bubble = bubble.bubble(before) print(sorted_bubble) end_b = time.time() print('bubble', end_b - start_b) # selection start_s = time.time() sorted_selection = selection.selection(before) print(sorted_selection) end_s = time.time() print('selection', end_s - start_s) # insertion start_i = time.time() sorted_insertion = insertion.insertion(before) print(sorted_insertion) end_i = time.time() print('insertion', end_i - start_i) # quick start_q = time.time() sorted_quick = quick.quick(before) print(sorted_quick) end_q = time.time() print('quick', end_q - start_q) # merge start_m = time.time() sorted_merge = merge_sort.devide(before) print(sorted_merge) end_m = time.time() print('merge', end_m - start_m)
## ahmed saad saleh import random import time ############################# INSERTION SORT RANDOM ############################ def insertionSort(alist): for index in range(1,len(alist)): currentvalue = alist[index] position = index while position>0 and alist[position-1]>currentvalue: alist[position]=alist[position-1] position = position-1 alist[position]=currentvalue ################################################################################ ############################## MERGE SORT RANDOM ############################### def mergeSort(alist): #print("Splitting ",alist) if len(alist)>1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: alist[k]=lefthalf[i] i=i+1 else: alist[k]=righthalf[j] j=j+1 k=k+1 while i < len(lefthalf): alist[k]=lefthalf[i] i=i+1 k=k+1 while j < len(righthalf): alist[k]=righthalf[j] j=j+1 k=k+1 #print("Merging ",alist) ################################################################################ ##################### IN-PLACE QUICK SORT RANDOM ############################### def quickSort(items): def sort(lst, l, r): # base case if r <= l: return # choose random pivot pivot_index = random.randint(l, r) # move pivot to first index lst[l], lst[pivot_index] = lst[pivot_index], lst[l] # partition i = l for j in range(l+1, r+1): if lst[j] < lst[l]: i += 1 lst[i], lst[j] = lst[j], lst[i] # place pivot in proper position lst[i], lst[l] = lst[l], lst[i] # sort left and right partitions sort(lst, l, i-1) sort(lst, i+1, r) if items is None or len(items) < 2: return sort(items, 0, len(items) - 1) ################################################################################ ##################### MODIFIED QUICK SORT RANDOM ############################### def quickSortM(alist): quickSortHelper(alist,0,len(alist)-1) def quickSortHelper(alist,first,last): if first<last: splitpoint = partition(alist,first,last) quickSortHelper(alist,first,splitpoint-1) quickSortHelper(alist,splitpoint+1,last) def partition(alist,first,last): pivotindex = median(alist, first, last, (first + last) // 2) alist[first], alist[pivotindex] = alist[pivotindex], alist[first] pivotvalue = alist[first] leftmark = first rightmark = last done = False while not done: while leftmark <= rightmark and \ alist[leftmark] <= pivotvalue: leftmark = leftmark + 1 while alist[rightmark] >= pivotvalue and \ rightmark >= leftmark: rightmark = rightmark -1 if rightmark < leftmark: #if ((leftmark<=10)|(rightmark<=10)): #print("Now calling insertion sort as last subset has 10 numbers", leftmark,rightmark) #insertionSort(alist) done = True else: temp = alist[leftmark] alist[leftmark] = alist[rightmark] alist[rightmark] = temp temp = pivotvalue alist[alist.index(pivotvalue)] = alist[rightmark] alist[rightmark] = temp return rightmark def median(a, i, j, k): if a[i] < a[j]: return j if a[j] < a[k] else k else: return i if a[i] < a[k] else k ################################################################################ alist = [] print("Please enter the random number range to sort") new=input() print('\n-----------------------------------------------------------------------') numbers = random.sample(range(1, 100000), int(new)) alist = numbers ####################### CALLING INSERTION SORT RANDOM ########################## print('Sorting using Insertion Sort\n') t1=time.time() insertionSort(alist) print(alist) t2=time.time() print ("The algorithm took " + str((t2-t1) * 1000) + " ms of time.") print('\n-----------------------------------------------------------------------') ########################### CALLING MERGE SORT RANDOM ########################## print('Sorting using Merge Sort\n') t3=time.time() mergeSort(alist) print('Using the same Dataset...') t4=time.time() print ("The algorithm took " + str((t4-t3) * 1000) + " ms of time.") print('\n-----------------------------------------------------------------------') ################## CALLING IN-PLACE QUICK SORT RANDOM ########################## print('Sorting using In-Place Quick Sort\n') t5=time.time() quickSort(numbers) t6=time.time() print('Using the same Dataset...') print ("The algorithm took " + str((t6-t5) * 1000) + " ms of time.") print('\n-----------------------------------------------------------------------') ##################### CALLING MODIFIED QUICK SORT ############################## print('Sorting using Modified Quick Sort\n') if(int(new)<=10): print("Since number of elements to be sorted is lesser than 10, insertion sort needs to be implemented") t7=time.time() insertionSort(alist) else: print("Since number of elements to be sorted is greater than 10, quick sort needs to be implemented") t7=time.time() quickSortM(alist) t8=time.time() print('Using the same Dataset...') print ("The algorithm took " + str((t8-t7) * 1000) + " ms of time.") print('\n-----------------------------------------------------------------------')
x = object() y = object() x_list = [x] * 5 y_list = [y] * 2 big_list = x_list + y_list print ("x_list contains %d objects" % len(x_list)) print ("y_list contains %d objects" % len(y_list)) print ("big_list contains %d objects" % len(big_list)) if x_list.count(x) <= 8 and y_list.count(y) <= 6: print ("Almost there.....") if big_list.count(x) == 10 and big_list.count(y) == 10: print("Great!")
# making a list of lists to form a matrix lst_1= [1,2,3] lst_2=[4,5,6] lst_3=[7,8,9] matrix =[lst_1,lst_2,lst_3] print (matrix[0]) # sort for lists new_list = ['a','e','x','b','c'] # reverse list new_list.reverse() print (new_list) # sort list new_list.sort() print (new_list) # list comprehesions # matrix2 = [[1,2,3]] first_col =[row[2] for row in matrix] print(first_col)
if __name__ == '__main__' : N = int(input()) L = [] for i in range(0, N) : Str = input() tempStr = Str.strip().split(" ") cond = tempStr[0] if (cond == "print") : print(L) elif (cond == "sort") : L.sort() elif (cond == "pop") : L.pop() elif (cond == "reverse") : L.reverse() elif (cond == "remove") : tempNumb = int(tempStr[1]) L.remove(tempNumb) elif (cond == "append") : tempNumb = int(tempStr[1]) L.append(tempNumb) elif (cond == "insert") : pos = int(tempStr[1]) val = int(tempStr[2]) L.insert(pos, val)
#-*- coding:utf-8 -*- #Python 输入框写法 hieght = input('请输入你的身高:') print("你的身高是%s"%hieght) print('=====================\n') #Python 输入框写法 age = 21 #定义年龄21岁 print("我的年龄是:%d"%age)
#-*- coding=utf-8 -*- import os str_name = input('请你输入要处理的字符串名称:') folder_name = input('请你输入要处理的目录:') # 获取某个目录下的所有文件名称 old_file_names = os.listdir(folder_name) for name in old_file_names: print(name.rfind(str_name)) # if name.find(str_name):
val1, val2, upper, lower = 0, 0, 100, 0 while True: print(upper, lower) val1 = raw_input("Upper: ") val2 = raw_input("Lower: ") if float(val1) == 0: break if float(val1) < float(upper): upper = val1 if float(val2) > float(lower): lower = val2
supplies = ['pens', 'staplers', 'flamethrowers', 'binders'] for index, item in enumerate(supplies): print(f'Index {index} in supplies is: {item}')
import random pets = ['dog', 'cat', 'squid', 'spider', 'hamster', 'human', 'zombie'] for i in range(2): print(random.choice(pets)) pets = ['dog', 'cat', 'squid', 'spider', 'hamster', 'human'] random.shuffle(pets) print(pets)
import pandas as pd X = pd.read_csv("data_2d.csv", header=None) print(type(X)) print(X.info()) print(X.head()) #default is set to 5 rows try: print(X[0,0]) except: pass M = X.values # no longer as_matrix print(type(M)) print(X[0]) # pandas X[0] -> column with name 0 # numpy X[0] -> 0th row print(type(X[0])) print(X.iloc[0]) print(X[[0,2]]) print(X[ X[0] < 5 ]) print(X[0] < 5) print(type(X[0] < 5))
""" quiz.py example of a quiz game using objects for data """ from tkinter import * # from tkMessageBox import * class Problem(object): def __init__(self, qtype="", question="", a="", b=""): object.__init__(self) self.qtype = qtype self.question = question self.a = a self.b = b class App(Tk): def __init__(self): Tk.__init__(self) self.problems = [] self.counter = 0 self.addComponents() self.loadProblems() self.showProblem(0) self.mainloop() def addComponents(self): """ add components to the GUI """ self.title("Confidence Elicitation") # force app to a fixed width self.grid() self.columnconfigure(0, minsize=100) self.columnconfigure(1, minsize=200) self.columnconfigure(2, minsize=100) self.lblQuestion = Label(self, text="Question") self.lblQuestion.grid(columnspan=3, sticky="we") self.selection = StringVar() self.btnA = Radiobutton(self, text="A", anchor="w", variable=self.selection, value="Yes", command=self.checkA) self.btnA.grid(columnspan=3, sticky="we") self.btnB = Radiobutton(self, text="B", anchor="w", state="active", variable=self.selection, value="No", command=self.checkB) self.btnB.grid(columnspan=3, sticky="we") self.Confidence = Scale(self, from_=50, to=100, tickinterval=10, label="How confident are you? (%)", orient=HORIZONTAL, troughcolor="white", fg="#33CFC6") self.Confidence.grid(row=4, columnspan=2, sticky="we") self.lblCounter = Label(self, text="0") self.lblCounter.grid(row=5, column=1) self.btnPrev = Button(self, text="Previous <<", command=self.prev) self.btnPrev.grid(row=5, column=0) self.btnNext = Button(self, text="Next >>", command=self.next) self.btnNext.grid(row=5, column=2) def checkA(self): self.check("A") def checkB(self): self.check("B") def check(self, guess): # compares the guess to the correct answer if guess == "": print("Quiz", "Please answer the question!") else: print("") def prev(self): self.counter -= 1 if self.counter < 0: self.counter = 0 self.showProblem(self.counter) def next(self): self.counter += 1 if self.counter >= len(self.problems): self.counter = len(self.problems) - 1 self.showProblem(self.counter) def showProblem(self, counter): self.lblQuestion["text"] = self.problems[counter].question self.btnA["text"] = self.problems[counter].a self.btnB["text"] = self.problems[counter].b self.lblCounter["text"] = self.counter def loadProblems(self): self.problems.append(Problem( "TEXT", "INSTRUCTIONS HERE", "", "")) self.problems.append(Problem( "Q1", "Did the Patriots won Super Bowl LI?", "Yes", "No")) self.problems.append(Problem( "Q1", "Will we land on Mars by 2020?", "Yes", "No")) self.problems.append(Problem( "Q2", "Duke will win the NCAA Basketball Championship.", "Yes", "No")) def main(): a = App() if __name__ == "__main__": main()
""" This is a data structure to define a game map At start we will use only one map, but later we wil add more maps """ """ Default Map The symbol # is a door. 0 1 2 3 +-----+-----+-----+-----+ 0 | A | | | +--#--+--#--------+--#--+ 1 | | C # | | # | | + B +-----------+ E + 2 | | D | | | # | | +--#--+-----------+-----+ 3 | | G | | | # | | + F +-----------+ I + 4 | # H # | | | | | +--#--+--#--------+--#--+ 5 | J | | | +-----+-----+-----+-----+ We represent this map with the following structure: """ class GameMap(): default_data = {'max_x': 4, 'max_y': 6, 'rooms': {'A': {'wall_color': (0.7, 0.8, 0.7)}, 'B': {'wall_color': (0.8, 0.8, 0.6)}, 'C': {'wall_color': (0.6, 0.6, 1)}, 'D': {'wall_color': (0.7, 0.8, 0.7)}, 'E': {'wall_color': (0.8, 0.8, 0.6)}, 'F': {'wall_color': (0.7, 0.8, 0.7)}, 'G': {'wall_color': (0.3, 0.4, 0.3)}, 'H': {'wall_color': (0.8, 0.8, 0.6)}, 'I': {'wall_color': (0.7, 0.8, 0.7)}, 'J': {'wall_color': (0.8, 0.8, 0.6)}}, 'cells': ['AAAA', 'BCCE', 'BDDE', 'FGGI', 'FHHI', 'JJJJ'], # walls are defined by the cell position x,y and the direction # N,S,E,W 'walls': [{'position': [0, 0, 'S'], 'doors': ['door_1']}, {'position': [1, 0, 'S'], 'doors': ['door_2']}, {'position': [3, 0, 'S'], 'doors': ['door_3']}, {'position': [0, 1, 'E'], 'doors': ['door_4']}, {'position': [2, 1, 'E'], 'doors': ['door_6']}, {'position': [0, 2, 'S'], 'doors': ['door_7']}, {'position': [0, 2, 'E'], 'doors': ['door_8']}, {'position': [4, 2, 'S'], 'doors': ['door_11']}, {'position': [0, 3, 'E'], 'doors': ['door_12']}, {'position': [3, 3, 'E'], 'doors': ['door_13']}, {'position': [0, 4, 'S'], 'doors': ['door_14']}, {'position': [0, 4, 'E'], 'doors': ['door_15']}, {'position': [1, 4, 'S'], 'doors': ['door_16']}, {'position': [2, 4, 'E'], 'doors': ['door_17']}, {'position': [3, 4, 'S'], 'doors': ['door_18']}]} def __init__(self, data=None): if data is None: self.data = self.default_data else: self.data = data def get_room(self, x, y): """ Return room key and the dictionary based in the position x,y in the map""" room_key = self.data['cells'][y][x] return room_key def set_room_name(self, room_key, room_name): self.data['rooms'][room_key]['room_name'] = room_name def get_room_name(self, room_key): if 'room_name' in self.data['rooms'][room_key]: return self.data['rooms'][room_key]['room_name'] else: return '' def get_door_info(self, door_name, direction): if not 'doors' in self.data: self.data['doors'] = {} key = door_name + '_' + direction if not key in self.data['doors']: self.data['doors'][key] = {} return self.data['doors'][key] def set_door_info(self, door_name, direction, door_info): if not 'doors' in self.data: self.data['doors'] = {} key = door_name + '_' + direction self.data['doors'][key] = door_info def get_next_coords(self, x, y, direction): if direction == 'N': y -= 1 if direction == 'S': y += 1 if direction == 'W': x -= 1 if direction == 'E': x += 1 if x < 0 or y < 0 or \ x > (self.data['max_x'] - 1) or \ y > (self.data['max_y'] - 1): return -1, -1 return x, y def get_next_room(self, x, y, direction): x, y = self.get_next_coords(x, y, direction) if x == -1 and y == -1: return None return self.get_room(x, y) def get_reversed_direction(self, direction): if direction == 'N': return 'S' if direction == 'S': return 'N' if direction == 'E': return 'W' if direction == 'W': return 'E' def get_direction_cw(self, direction): """Return the direction if the user turn clock wise""" if direction == 'N': return 'E' if direction == 'S': return 'W' if direction == 'E': return 'S' if direction == 'W': return 'N' def get_direction_ccw(self, direction): """Return the direction if the user turn reverse clock wise""" if direction == 'N': return 'W' if direction == 'S': return 'E' if direction == 'E': return 'N' if direction == 'W': return 'S' def get_wall_info(self, x, y, direction): """ Return the array of objects associated to a defined wall or None if there are not a wall in this cell and direction""" # verify if there are a wall in the requested position actual_room = self.get_room(x, y) next_room = self.get_next_room(x, y, direction) # if the two rooms are the same, there are no wall if next_room is not None and actual_room == next_room: return None # Search in walls data for wall in self.data['walls']: if wall['position'] == [x, y, direction]: if not 'objects' in wall: wall['objects'] = [] return wall['objects'] return [] def add_object_to_wall(self, x, y, direction, wall_object): """ Add a object to the array of objects associated to a defined wall """ # verify if there are a wall in the requested position actual_room = self.get_room(x, y) next_room = self.get_next_room(x, y, direction) # if the two rooms are the same, there are no wall if next_room is not None and actual_room == next_room: return None # Search in walls data found = False for wall in self.data['walls']: if wall['position'] == [x, y, direction]: if not 'objects' in wall: wall['objects'] = [] wall['objects'].append(wall_object) found = True if not found: wall_info = {'position': [x, y, direction], 'objects': []} wall_info['objects'].append(wall_object) self.data['walls'].append(wall_info) def del_object_from_wall(self, x, y, direction, wall_object): for wall in self.data['walls']: if wall['position'] == [x, y, direction]: # locate the object: for order, existing_object in enumerate(wall['objects']): if existing_object == wall_object: del wall['objects'][order] break def get_wall_color(self, x, y): room = self.get_room(x, y) return self.data['rooms'][room]['wall_color'] def go_right(self, x, y, direction): """ Return next position if the user go to the right""" # check if there are a wall direction_cw = self.get_direction_cw(direction) wall_right = self.get_wall_info(x, y, direction_cw) if wall_right is not None: return x, y, direction_cw if direction == 'N': return x + 1, y, direction if direction == 'E': return x, y + 1, direction if direction == 'S': return x - 1, y, direction if direction == 'W': return x, y - 1, direction def go_left(self, x, y, direction): """ Return next position if the user go to the left""" # check if there are a wall direction_ccw = self.get_direction_ccw(direction) wall_left = self.get_wall_info(x, y, direction_ccw) if wall_left is not None: return x, y, direction_ccw if direction == 'N': return x - 1, y, direction if direction == 'E': return x, y - 1, direction if direction == 'S': return x + 1, y, direction if direction == 'W': return x, y + 1, direction def cross_door(self, x, y, direction): """ Return next position if the user go to the left""" # verify is the door is in the right position/direction if not self.have_door(x, y, direction): return x, y, direction else: new_x, new_y, new_dir = self.go_forward(x, y, direction) if self.get_wall_info(new_x, new_y, new_dir) is None: new_x, new_y, new_dir = self.go_forward(new_x, new_y, new_dir) return new_x, new_y, new_dir def go_forward(self, x, y, direction): if direction == 'N': return x, y - 1, direction if direction == 'E': return x + 1, y, direction if direction == 'S': return x, y + 1, direction if direction == 'W': return x - 1, y, direction def have_door(self, x, y, direction): """ Return if the wall have a door or None if there are not a wall in this cell and direction""" # verify if there are a wall in the requested position actual_room = self.get_room(x, y) next_room = self.get_next_room(x, y, direction) # if the two rooms are the same, there are no wall if next_room is not None and actual_room == next_room: return None # Search in walls data for wall in self.data['walls']: if wall['position'] == [x, y, direction]: if 'doors' in wall and len(wall['doors']) > 0: return wall['doors'] else: return [] # look for information in the other side of the room too. if next_room is not None: reversed_direction = self.get_reversed_direction(direction) x2, y2 = self.get_next_coords(x, y, direction) if x2 == -1 and y2 == -1: return [] for wall in self.data['walls']: if wall['position'] == [x2, y2, reversed_direction]: if 'doors' in wall and len(wall['doors']) > 0: return wall['doors'] else: return [] # Nothing found return [] # testing if __name__ == '__main__': game_map = GameMap() print "test get_room" print game_map.get_room(0, 0) print game_map.get_room(3, 2) print game_map.get_room(1, 4) print game_map.get_room(3, 5) print "test get_next_room" print game_map.get_next_room(3, 5, 'N') print game_map.get_next_room(3, 3, 'W') print game_map.get_next_room(2, 1, 'S') print "test get_wall_info" print game_map.get_wall_info(0, 3, 'N') print game_map.get_wall_info(0, 3, 'E') print game_map.get_wall_info(0, 3, 'S') print game_map.get_wall_info(0, 3, 'W') print "test go_right" print game_map.go_right(1, 1, 'N') print game_map.go_right(2, 1, 'N') print "test go_left" print game_map.go_left(1, 1, 'N') print game_map.go_left(2, 1, 'N') print "test cross_door" print game_map.cross_door(1, 1, 'N') print game_map.cross_door(2, 1, 'N')
import pandas as pd from collections import defaultdict #load into data frame df = pd.read_csv("data/mobile_price.csv", sep=',') # check if any null or missing values in entire CSV file if df.isnull().values.any(): print('Data has missing values') else: # file has no null values thus set default data type as str df = pd.read_csv("data/mobile_price.csv", sep=',', dtype=str) categorical_columns = ["blue", "dual_sim", "four_g", "three_g", "touch_screen", "wifi", "price_category"] # map 'has' and 1 to 'Yes' and any other value to 'No' replacements_dict = defaultdict(lambda: "No") replacements_dict.update({"has": "Yes", "1": "Yes", "yes": "Yes"}) for column in categorical_columns: df[column] = df[column].str.lower() df[column] = df[column].map(replacements_dict) # drop id column df = df.drop("id", axis=1) df.to_csv("data/cleaned_mobile_price.csv", index = False)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv("ex1data1.csv") data.plot.scatter('population','profit') X = data['population'] y = data['profit'] theta = np.zeros(2) alpha = 0.01 num_iters = 1500 def predict(X, theta): return theta[0] + theta[1] * X def cost(X, y, theta): return np.sum((predict(X, theta) - y) ** 2) def fit(X, y, theta, alpha, num_iters): m = X.size for i in range(num_iters): tmp = np.zeros(2) p = predict(X, theta); tmp[0] = - np.sum(p - y) * alpha / m tmp[1] = - np.sum((p - y) * X) * alpha / m theta = theta + tmp return theta def fit_with_cost(X, y, theta, alpha, num_iters): m = X.size J_history = np.empty(num_iters) for i in range(num_iters): J_history[i] = cost(X, y, theta) tmp = np.zeros(2) p = predict(X, theta); tmp[0] = - np.sum(p - y) * alpha / m tmp[1] = - np.sum((p - y) * X) * alpha / m theta = theta + tmp return theta, J_history def visualize(theta): fig = plt.figure() ax = plt.axes() ax.set_xlim([4.5,22.5]) ax.set_ylim([-5, 25]) ax.scatter(X, y) line_x = np.linspace(0,22.5, 20) line_y = theta[0] + line_x * theta[1] ax.plot(line_x, line_y) plt.show() theta, J_history = fit_with_cost(X, y, theta, alpha, num_iters) visualize(theta) fig = plt.figure() ax = plt.axes() ax.plot(J_history)
def binarySearch(arr, key): l = 0 h = len(arr)-1 while(l<=h): mid = (l+h)//2 if arr[mid]==key: return mid + 1 elif arr[mid]>key: h = mid - 1 else: l = mid+1 return 0 arr = [3,6,8,12,14,17,25,29,31,36,42,47,53,55,6] key = 3 print(binarySearch(arr,key))
import math class Point: def __init__(self, x = 0, y = 0): self.x = x self.y = y @staticmethod def from_tuple(t): return Point(t[0], t[1]) def copy(self): return Point(self.x, self.y) def clone(self): return self.copy() def as_int_tuple(self): return (int(self.x), int(self.y)) def add(self, p): self.x += p.x self.y += p.y return self def sum(self, p): return Point(self.x + p.x, self.y + p.y) def difference(self, p): return Point(self.x - p.x, self.y - p.y) def diff(self, p): return self.difference(p) def scaled(self, factor, shift = 0): return Point(self.x * factor + shift, self.y * factor + shift) def affine_r(self, factor, shift = 0): return Point((self.x - shift) / factor, (self.y - shift) / factor) def as_int(self): return Point(int(self.x), int(self.y)) def point_along_a_line(start_x, start_y, end_x, end_y, distance): dx = end_x - start_x dy = end_y - start_y x = 0 y = 0 if dx != 0: k = float(dy) / float(dx) point_dx = math.sqrt(distance**2 / (1 + k**2)) if dx < 0: point_dx *= -1 point_dy = point_dx * k if distance < 0: point_dx = -point_dx point_dy = -point_dy x = start_x + point_dx y = start_y + point_dy else: x = start_x if dy < 0: y = start_y - distance else: y = start_y + distance return (x, y) def point_along_a_line_p(p1, p2, distance): (x, y) = point_along_a_line(p1.x, p1.y, p2.x, p2.y, distance) return Point(x, y) def point_along_a_perpendicular(start_x, start_y, end_x, end_y, p_start_x, p_start_y, distance): dx = end_x - start_x dy = end_y - start_y x = 0 y = 0 if dx != 0: k = float(dy) / float(dx) point_dx = math.sqrt(distance**2 / (1 + k**2)) if dx < 0: point_dx *= -1 point_dy = point_dx * k if distance < 0: point_dx *= -1 point_dy *= -1 x = p_start_x - point_dy y = p_start_y + point_dx else: y = p_start_y if dy < 0: x = p_start_x - distance else: x = p_start_x + distance return (x, y) def point_along_a_perpendicular_p(s, e, p, distance): return point_along_a_perpendicular(s.x, s.y, e.x, e.y, p.x, p.y, distance) def point_along_a_line_eq(k, start_x, start_y, distance): x = 0 y = 0 if k != 0: point_dx = math.sqrt(distance**2 / (1 + k**2)) if distance < 0: point_dx *= -1 point_dy = point_dx * k x = start_x + point_dx y = start_y + point_dy else: x = start_x y = start_y + distance return (x, y) def distance(start_x, start_y, end_x, end_y): return math.sqrt((start_x - end_x)**2 + (start_y - end_y)**2) def distance_p(p1, p2): return distance(p1.x, p1.y, p2.x, p2.y) def line_equation(start_x, start_y, end_x, end_y): dx = end_x - start_x k = 0 if dx != 0: k = float(end_y - start_y) / (end_x - start_x) return (k, start_y) def cosine(x1, y1, x2, y2, x3, y3) : sx1 = x1 - x2 sy1 = y1 - y2 sx2 = x3 - x2 sy2 = y3 - y2 dot = sx1 * sx2 + sy1 * sy2 a = math.sqrt(sx1**2 + sy1**2) b = math.sqrt(sx2**2 + sy2**2) prod = a * b if prod != 0: cos = dot / prod if cos > 1.0: cos = 1.0 elif cos < -1.0: cos = -1.0 return cos else: return 0 def cosine_p(p1, p2, p3): return cosine(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y) def sgn(x): if x < 0: return -1 else: return 1 def intersection_with_circle(p1, p2, center, radius): p1s = p1.difference(center) p2s = p2.difference(center) # http://mathworld.wolfram.com/Circle-LineIntersection.html dx = p2s.x - p1s.x dy = p2s.y - p1s.y dr = math.sqrt(dx**2 + dy**2) D = p1s.x*p2s.y - p2s.x*p1s.y r = radius det = (r**2) * (dr**2) - (D**2) if det <= 0: return (None, None) else: p1 = Point() p2 = Point() p1.x = (D * dy + sgn(dy) * dx * math.sqrt(det)) / (dr ** 2) p2.x = (D * dy - sgn(dy) * dx * math.sqrt(det)) / (dr ** 2) p1.y = (- D * dx + abs(dy) * math.sqrt(det)) / (dr ** 2) p2.y = (- D * dx - abs(dy) * math.sqrt(det)) / (dr ** 2) return (p1.add(center), p2.add(center)) def angle(x1, y1, pivot_x, pivot_y, x2, y2): x1 -= pivot_x y1 -= pivot_y x2 -= pivot_x y2 -= pivot_y dot = x1*x2 + y1*y2 det = x1*y2 - y1*x2 if det == 0 and dot == 0: return 0 return math.atan2(det, dot) # anticlockwise (clockwise if inverted y) def rotate_p(point, pivot, angle): s = math.sin(angle); c = math.cos(angle); p = point.difference(pivot); x = p.x * c - p.y * s + pivot.x y = p.x * s + p.y * c + pivot.y return Point(x, y)
import math def is_powed(a, b, c): p = (a+b+c) / 2 return math.sqrt(p*(p-a)*(p-b)*(p-c)) a = float(input()) b = float(input()) c = float(input()) S = is_powed(a, b, c) print(S)
# min # # The tool min returns the minimum value along a given axis. # # import numpy # # my_array = numpy.array([[2, 5], # [3, 7], # [1, 3], # [4, 0]]) # # print numpy.min(my_array, axis = 0) #Output : [1 0] # print numpy.min(my_array, axis = 1) #Output : [2 3 1 0] # print numpy.min(my_array, axis = None) #Output : 0 # print numpy.min(my_array) #Output : 0 # By default, the axis value is None. Therefore, it finds the minimum over all the dimensions of the input array. # # max # # The tool max returns the maximum value along a given axis. # # import numpy # # my_array = numpy.array([[2, 5], # [3, 7], # [1, 3], # [4, 0]]) # # print numpy.max(my_array, axis = 0) #Output : [4 7] # print numpy.max(my_array, axis = 1) #Output : [5 7 3 4] # print numpy.max(my_array, axis = None) #Output : 7 # print numpy.max(my_array) #Output : 7 # By default, the axis value is None. Therefore, it finds the maximum over all the dimensions of the input array. # Sample Input # # 4 2 # 2 5 # 3 7 # 1 3 # 4 0 # Sample Output # # 3 import numpy as np a, b = map(int, input().split()) arr = np.array([input().split() for _ in range(a)], dtype=np.int) print(np.max(np.min(arr, axis=1), axis=None)) # print(arr.min(axis=1).max()) # но можно сделать и так # print(np.max(np.min((np.array([input().split() for _ in range(a)], dtype=int)), axis=1)))
# identity # # The identity tool returns an identity array. An identity array is a square matrix with all the main diagonal elements as and the rest as . The default type of elements is float. # # import numpy # print (numpy.identity(3)) #3 is for dimension 3 X 3 # # #Output # [[ 1. 0. 0.] # [ 0. 1. 0.] # [ 0. 0. 1.]] # eye # # The eye tool returns a 2-D array with 's as the diagonal and 's elsewhere. The diagonal can be main, upper or lower depending on the optional parameter . A positive is for the upper diagonal, a negative is for the lower, and a (default) is for the main diagonal. # # import numpy # print numpy.eye(8, 7, k = 1) # 8 X 7 Dimensional array with first upper diagonal 1. # # #Output # [[ 0. 1. 0. 0. 0. 0. 0.] # [ 0. 0. 1. 0. 0. 0. 0.] # [ 0. 0. 0. 1. 0. 0. 0.] # [ 0. 0. 0. 0. 1. 0. 0.] # [ 0. 0. 0. 0. 0. 1. 0.] # [ 0. 0. 0. 0. 0. 0. 1.] # [ 0. 0. 0. 0. 0. 0. 0.] # [ 0. 0. 0. 0. 0. 0. 0.]] # # print numpy.eye(8, 7, k = -2) # 8 X 7 Dimensional array with second lower diagonal 1. # Sample Input # # 3 3 # Sample Output # # [[ 1. 0. 0.] # [ 0. 1. 0.] # [ 0. 0. 1.]] import numpy a,b = map(int, input().split()) print (str(numpy.eye(a, b)).replace('1', ' 1').replace('0', ' 0'))
def removeDuplicado(grafo, inicio, vizinho): # remove arestas duplicadas while grafo[inicio].count((vizinho, 1)) > 1: grafo[inicio].remove((vizinho, 1)) while (inicio, 1) in grafo[vizinho]: grafo[vizinho].remove((inicio, 1)) return grafo def criaGrafo(quant_v): # cria um grafo (floresta) sem vertices, somente arestas grafo = list() for _ in range(quant_v): grafo.append(list()) return grafo def lerGrafo(v, a, grafo): # le o grafo e adiciona as arestas for _ in range(a): v1, v2 = input().split() v1 = int(v1) v2 = int(v2) grafo[v1].append((v2, 1)) grafo[v2].append((v1, 1)) return grafo def passeio(grafo, inicio): # percorre o grafo contando quantos movimentos foram efetuados(visinhos alcançaveis) global count for aresta in grafo[inicio]: count += 1 verticeVizinho = aresta[0] removeDuplicado(grafo, inicio, verticeVizinho) passeio(grafo, verticeVizinho) count += 1 return count if __name__ == "__main__": quant_teste = int(input()) for x in range(quant_teste): count = 0 vertice_inicial = int(input()) quantVertices, quantArestas = input().split() quantVertices = int(quantVertices) quantArestas = int(quantArestas) grafo = criaGrafo(quantVertices) lerGrafo(quantVertices, quantArestas, grafo) print(passeio(grafo, vertice_inicial))
# Fibonacci def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) #Lucas def lucas(n): if n == 0: return 2 elif n == 1: return 1 else: return lucas(n - 1) + lucas(n - 2) #Sum Series def sum_series(n, n1=0, n2=1): if n == 0: return n1 if n == 1: return n2 else: return sum_series(n - 1, n1, n2) + sum_series(n - 2, n1, n2)
import tkinter as tk import sqlite3 """Payment management system Written by Hawkins647""" root = tk.Tk() root.title("Payment Management System") root.geometry("600x600") root.resizable(0, 0) inbound_db = sqlite3.connect("inbound.sqlite") outbound_db = sqlite3.connect("outbound.sqlite") def delete_entry_inbound(scrollbox): """Deletes the selected entry from the inbound_payments database PARAMETERS: scrollbox: The tkinter Scrollbox widget that is on the main frame.""" for i in scrollbox.curselection(): # Split the selection into a list value_list = scrollbox.get(i).split() # Delete the selection using the name and amount to identify the chosen value inbound_db.execute('DELETE FROM inbound_payments WHERE "name"=' + '"' + value_list[1].strip(",") + '"' + ' AND "amount"=' + value_list[3].strip(",")) # Call the inbound_menu function to refresh the page, updating the deletion inbound_menu() def delete_entry_outbound(scrollbox): """Deletes the selected entry from the outbound_payments database PARAMETERS: scrollbox: The tkinter Scrollbox widget that is on the main frame.""" for i in scrollbox.curselection(): # Split the selection into a list value_list = scrollbox.get(i).split() # Delete the selection using the name to identify the chosen value outbound_db.execute('DELETE FROM outbound_payments WHERE "name"=' + '"' + value_list[1].strip(",") + '"' + ' AND "amount"=' + value_list[3].strip(",")) # Call the inbound_menu function to refresh the page, updating the deletion outbound_menu() def register_new_inbound(name, amount, vat): """Registers a new entry in the inbound database PARAMETERS: name: str - The name of the payer amount: int (will be given in str form, but must contain an int) - The amount paid vat: str - Whether VAT was used or not""" inbound_db.execute("CREATE TABLE IF NOT EXISTS inbound_payments (name TEXT, amount INTEGER, vat TEXT)") inbound_db.execute("INSERT INTO inbound_payments (name, amount, vat) VALUES('{}', {}, '{}')".format(name, amount, vat)) inbound_db.commit() inbound_menu() def register_new_outbound(name, amount, vat): """Registers a new entry in the outbound database PARAMETERS: name: str - The name of the payer amount: int (will be given in str form, but must contain an int) - The amount paid vat: str - Whether VAT was used or not""" outbound_db.execute("CREATE TABLE IF NOT EXISTS outbound_payments (name TEXT, amount INTEGER, vat TEXT)") outbound_db.execute("INSERT INTO outbound_payments (name, amount, vat) VALUES('{}', {}, '{}')".format(name, amount, vat)) outbound_db.commit() outbound_menu() def reset_frame(): """Reset the frame, in order to reset widgets or refresh a page to update information""" global main_frame main_frame.destroy() main_frame = tk.Frame(root) main_frame.pack() def inbound_menu(): """Create the inbound payments menu on the main frame""" reset_frame() title_frame = tk.Frame(main_frame) title_frame.grid(row=0, column=0) title_label = tk.Label(title_frame, text="Inbound Payments") title_label.pack() warning_label = tk.Label(main_frame, text="WARNING: PLEASE FILL OUT ALL BOXES TO ENSURE NO ERRORS ARE MADE") warning_label.grid(row=1, column=0) button_frame = tk.Frame(main_frame) button_frame.grid(row=2, column=0) tk.Label(button_frame, text="(Company) Name of Payer").grid(row=2, column=0) name_entry = tk.Entry(button_frame) name_entry.grid(row=2, column=1, padx=5, pady=5) tk.Label(button_frame, text="Amount of money paid").grid(row=3, column=0) amount_entry = tk.Entry(button_frame) amount_entry.grid(row=3, column=1, padx=5, pady=5) tk.Label(button_frame, text="VAT included? (Y/N)").grid(row=4, column=0) vat_entry = tk.Entry(button_frame) vat_entry.grid(row=4, column=1, pady=5) register_new_button = tk.Button(main_frame, text="Register new payment", command=lambda:register_new_inbound(name_entry.get(), amount_entry.get(), vat_entry.get().upper())) register_new_button.grid(row=5, column=0, padx=3, pady=3) current_payments_label = tk.Label(main_frame, text="Current Inbound Payments") current_payments_label.grid(row=6, column=0, padx=3, pady=20) inbound_payments_list = tk.Listbox(main_frame) inbound_payments_list.grid(row=7, column=0, sticky='nsew', rowspan=2) inbound_payments_list.config(border=2, relief='sunken') inbound_db_cursor = inbound_db.cursor() inbound_db_cursor.execute("SELECT * FROM inbound_payments") for row in inbound_db_cursor: inbound_payments_list.insert(tk.END, "Name: " + row[0] + ", Price: " + str(row[1]) + ", VAT: " + row[2]) listScroll = tk.Scrollbar(main_frame, orient=tk.VERTICAL, command=inbound_payments_list.yview) listScroll.grid(row=7, column=1, sticky='nsw', rowspan=2) inbound_payments_list['yscrollcommand'] = listScroll.set tk.Label(main_frame, text="Please select the entry you want to delete from the options above").grid(row=9, column=0, padx=5, pady=5) delete_button = tk.Button(main_frame, text="Delete an entry", command=lambda:delete_entry_inbound(inbound_payments_list), width=20) delete_button.grid(row=10, column=0, pady=10) def outbound_menu(): """Create the outbound menu on the main frame""" reset_frame() title_frame = tk.Frame(main_frame) title_frame.grid(row=0, column=0) title_label = tk.Label(title_frame, text="Outbound Payments") title_label.pack() warning_label = tk.Label(main_frame, text="WARNING: PLEASE FILL OUT ALL BOXES TO ENSURE NO ERRORS ARE MADE") warning_label.grid(row=1, column=0) button_frame = tk.Frame(main_frame) button_frame.grid(row=2, column=0) tk.Label(button_frame, text="(Company) Name of Payee").grid(row=2, column=0) name_entry = tk.Entry(button_frame) name_entry.grid(row=2, column=1, padx=5, pady=5) tk.Label(button_frame, text="Amount of money paid").grid(row=3, column=0) amount_entry = tk.Entry(button_frame) amount_entry.grid(row=3, column=1, padx=5, pady=5) tk.Label(button_frame, text="VAT included? (Y/N)").grid(row=4, column=0) vat_entry = tk.Entry(button_frame) vat_entry.grid(row=4, column=1, pady=5) register_new_button = tk.Button(main_frame, text="Register new payment", command=lambda:register_new_outbound(name_entry.get(), amount_entry.get(), vat_entry.get())) register_new_button.grid(row=5, column=0, padx=3, pady=3) current_payments_label = tk.Label(main_frame, text="Current Inbound Payments") current_payments_label.grid(row=6, column=0, padx=3, pady=20) outbound_payments_list = tk.Listbox(main_frame) outbound_payments_list.grid(row=7, column=0, sticky='nsew', rowspan=2) outbound_payments_list.config(border=2, relief='sunken') outbound_db_cursor = outbound_db.cursor() outbound_db_cursor.execute("SELECT * FROM outbound_payments") for row in outbound_db_cursor: outbound_payments_list.insert(tk.END, "Name: " + row[0] + ", Price: " + str(row[1]) + ", VAT: " + row[2]) listScroll = tk.Scrollbar(main_frame, orient=tk.VERTICAL, command=outbound_payments_list.yview) listScroll.grid(row=7, column=1, sticky='nsw', rowspan=2) outbound_payments_list['yscrollcommand'] = listScroll.set tk.Label(main_frame, text="Please select the entry you want to delete from the options above").grid(row=9, column=0, padx=5, pady=5) delete_button = tk.Button(main_frame, text="Delete an entry", command=lambda:delete_entry_outbound(outbound_payments_list), width=20) delete_button.grid(row=10, column=0, pady=10) top_button_frame = tk.Frame(root, bg="grey") top_button_frame.pack(pady=3, fill=tk.BOTH) main_frame = tk.Frame(root) main_frame.pack() inbound_window_button = tk.Button(top_button_frame, text="Inbound Payments", bg="red", width=40, command=inbound_menu) inbound_window_button.grid(row=0, column=0, padx=3) outbound_window_button = tk.Button(top_button_frame, text="Outbound Payments", bg="red", width=40, command=outbound_menu) outbound_window_button.grid(row=0, column=1, padx=3) root.mainloop() inbound_db.close() outbound_db.close()
while True: p=raw_input("ingresa la operacion\n") a=p.lower() if a=="": break a+=";" estado="q0" for entrada in a: if entrada=="a" or entrada=="b" or entrada=="c" or entrada=="d" or entrada=="e" or entrada=="f" or entrada=="g" or entrada=="h" or entrada=="i" or entrada=="j" or entrada=="k" or entrada=="l" or entrada=="m" or entrada=="n" or entrada=="o" or entrada=="p" or entrada=="q" or entrada=="r" or entrada=="s" or entrada=="t" or entrada=="u" or entrada=="v" or entrada=="w" or entrada=="x" or entrada=="y" or entrada=="z": for entrada in p: if estado=="q0": if entrada=="a" or entrada=="b" or entrada=="c" or entrada=="d" or entrada=="e" or entrada=="f" or entrada=="g" or entrada=="h" or entrada=="i" or entrada=="j" or entrada=="k" or entrada=="l" or entrada=="m" or entrada=="n" or entrada=="o" or entrada=="p" or entrada=="q" or entrada=="r" or entrada=="s" or entrada=="t" or entrada=="u" or entrada=="v" or entrada=="w" or entrada=="x" or entrada=="y" or entrada=="z": estado="q1" pal1=entrada if entrada=="1" or entrada=="2" or entrada=="3" or entrada=="4" or entrada=="5" or entrada=="6" or entrada=="7" or entrada=="8" or entrada=="9" or entrada=="10" or entrada=="0"or entrada==";";: print "no ingresaste letra" estado = "qr" else: print entrada break elif entrada=="1" or entrada=="2" or entrada=="3" or entrada=="4" or entrada=="5" or entrada=="6" or entrada=="7" or entrada=="8" or entrada=="9" or entrada=="10" or entrada=="0": print entrada break else: print "error"
x = int(input()) y = int(input()) ans = 0 if x>0 and y>0: ans = 1 elif x>0 and y<0: ans = 4 elif x<0 and y>0: ans = 2 elif x<0 and y<0: ans = 3 print(ans)
N = int(input()) arr = [] for i in range(0,N): arr.append(input()) arr = list(set(arr)) arr = sorted(arr) arr.sort(key=len) for i in range(len(arr)): print(arr[i])
#!/usr/bin/env python # Presenting menu of options print ("What would you like to do? ") # User selects option from menu option = input("(1) Translate a protein-coding nucleotide sequence to amino acids OR (2) Randomly draw a codon from the sequence? ") # If user selects option 1. if option == "1": dnaSeq = input("Enter protein-coding nucleotide sequence here (IN ALL CAPS): ") # Option 1: Transcription of nucleotide sequence rnaSeq = dnaSeq.replace("T","U") print("Resulting transcription sequence: ") print(rnaSeq) # Creating amino acid dictionary AminoDic = {"UUU":"F", "UUC":"F", "UUA":"L", "UUG":"L", "CUU":"L", "CUC":"L", "CUA":"L", "CUG":"L", "AUU":"I", "AUC":"I", "AUA":"I", "AUG":"M", "GUU":"V", "GUC":"V", "GUA":"V", "GUG":"V", "UCU":"S", "UCC":"S", "UCA":"S", "UCG":"S", "CCU":"P", "CCC":"P", "CCA":"P", "CCG":"P", "ACU":"T", "ACC":"T", "ACA":"T", "ACG":"T", "GCU":"A", "GCC":"A", "GCA":"A", "GCG":"A", "UAU":"Y", "UAC":"Y", "UAA":"stop", "UAG":"stop", "CAU":"H", "CAC":"H", "CAA":"Q", "CAG":"Q", "AAU":"N", "AAC":"N", "AAA":"K", "AAG":"K", "GAU":"D", "GAC":"D", "GAA":"E", "GAG":"E", "UGU":"C", "UGC":"C", "UGA":"stop", "UGG":"W", "CGU":"R", "CGC":"R", "CGA":"R", "CGG":"R", "AGU":"S", "AGC":"S", "AGA":"R", "AGG":"R", "GGU":"G", "GGC":"G", "GGA":"G", "GGG":"G" } # Option 1: Translation of transcription sequence rnaSeq = dnaSeq.replace("T","U") dnaSeq = input("Enter transcription sequence here for translation: ") proteinSeq = "" AminoDic ={} for i in range(0, len(rnaSeq), 3): if rnaSeq[i:i+3] in AminoDic: proteinSeq += AminoDic[rnaSeq[i:i+3]] print("Protein Sequence: ") print(proteinSeq) # If user selects option 2, input nucleotide sequence elif option == "2": dnaSeq = input("Enter protein-coding nucleotide sequence here (IN ALL CAPS): ") codon = [dnaSeq[i:i+3] for i in range(0, len(dnaSeq), 3)] print(codon) # Report random codon import random ranCodon = random.choice(codon) print(ranCodon)
# -*- coding: utf-8 -*- A, DA, B, DB = input().split() result_a = A.count(DA) * DA result_b = B.count(DB) * DB print(int(result_a and result_a or 0) + int(result_b and result_b or 0))
# -*- coding=utf-8 -*- n = int(input()) # 接收参数 step_number = 0 while n != 1: # 直到n=1返回步数 if n % 2 == 0: # 判断奇偶 n /= 2 else: n = (3 * n + 1) / 2 step_number += 1 # 步数+1 print(step_number)
x = input("Number : ") list_of_digits = [i for i in x] list_1 = [] sum1 = 0 for i in range(len(x) - 2, -1, -2): a = str(2 * (int(list_of_digits[i]))) list_1.append(a) for j in range(len(a)): sum1 += int(a[j]) sum2 = sum1 for i in range(len(x) - 1, -1, -2): sum2 += int(list_of_digits[i]) if (sum2) % 10 == 0: if len(x) == 15: print("AMEX") elif (len(x) == 16 or len(x) == 13) and x[0] == '4': print("VISA") else: print("MASTERCARD") else: print("INVALID")
"""Faça um Programa que peça as 4 notas bimestrais e mostre a média.""" nota1 = float(input("Digite a primeira nota do aluno --> ")) nota2 = float(input("Digite a segunda nota do aluno --> ")) nota3 = float(input("Digite a terceira nota do aluno --> ")) media = (nota1 + nota2 + nota3) / 3 print(f"A media do aluno é {media:.2f}")
number = int(input('Enter a 4 digits number: ')) number = number // 10 second_digit = number % 10 print('The second number from the right is: ' + str(second_digit))
# insert a number (float / integer) and print the closest even integer number = float(input('Enter a number: ')) closest_integer = number // 1 if closest_integer % 2 == 0: closest_even_integer = closest_integer + 2 else: closest_even_integer = closest_integer + 1 closest_even_integer = int(closest_even_integer) print('The closest even integer for the number you chose is: ' + str(closest_even_integer))
#07 - Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha separados # os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente. #Resposta numeros = [[], []] for i in range(0,7): num = int(input("Digite um número inteiro: ")) if num % 2 == 0: numeros[0].append(num) else: numeros[1].append(num) print(f"Os números digitados são: {numeros} pares: {numeros[0]} impares: {numeros[1]} ")
def sortRGB( arr): lo = 0 hi = len(arr) - 1 mid = 1 while mid <= hi: if arr[mid] == 'R': arr[lo],arr[mid] = arr[mid],arr[lo] lo = lo + 1 mid = mid + 1 elif arr[mid] == 'G': mid = mid + 1 else: arr[mid],arr[hi] = arr[hi],arr[mid] hi = hi - 1 return arr arr = ['G','B','R','R','B','R','G'] arr = sortRGB( arr) print ("Array after segregation :") print (arr)
# Пользователь вводит строку из нескольких слов, разделённых пробелами. # Вывести каждое слово с новой строки. Строки необходимо пронумеровать. # Если в слово длинное, выводить только первые 10 букв в слове. # insert = str(input('Веедите несколько слов:')) # num = 0 # for i in insert.split(" "): # num += 1 # print(num, i[:10]) line = input() words = line.split() for i, word in enumerate(words, 1): print(i, word[:10])
# 3. Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц # (зима, весна, лето, осень). Напишите решения через list и через dict. dict_data = { 1: 'зима', 2: 'зима', 3: 'весна', 4: 'весна', 5: 'весна', 6: 'лето', 7: 'лето', 8: 'лето', 9: 'осень', 10: 'осень', 11: 'осень', 12: 'зима', } list_data = ['', 'winter', 'winter', 'spring', 'spring', 'spring', 'sumer', 'sumer', 'sumer', 'autemn', 'autemn', 'autemn', 'winter', ] data = int(input('Веедите номер месяца: ')) print(dict_data[data]) print(list_data[data])
# Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. # Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369. n = 10 while n > 9: n = int(input('введите цифру:')) print(n) n_2 = n*10 + n n_3 = n * 100 + n_2 print(f'{n} + {n_2} + {n_3} = {n + n_2+n_3}')
#!/usr/bin/python3.4 import sys import argparse import json from datetime import datetime #this class is the primary object for holding information #class Birthday(object): # def __init__(self, name='', date='', comment=''): # self.name = name # self.date = date # self.comment = comment #def listBdays(all): def main(): #define the parser parser = argparse.ArgumentParser(description='Read and Write a birthday calendar.') #defining cli arguments parser.add_argument('-j', dest='jsonFile', required=False, help='JSON file for storing/reading birthdays') parser.add_argument('-l', dest='listMonthlyOption', action='store_true', help='List this week\'s birthdays') parser.add_argument('-ll', dest='listAllOption', action='store_true', help='List all birthdays') parser.add_argument('-a', dest='addBirthdayOption', nargs=3, help='Add new birthday ("Some N. Ame", MM-DD, "Comment")') args = parser.parse_args() with open(args.jsonFile, mode='r', encoding='utf-8') as input: bdayList = json.load(input) if args.addBirthdayOption: name = args.addBirthdayOption[0] date = args.addBirthdayOption[1].split('-', 1) month = int(date[0]) day = int(date[1]) comment = args.addBirthdayOption[2] with open(args.jsonFile, 'a') as output: json.dump({'name': name, 'date': {'month': month, 'day': day}, 'comment': comment}, output) output.write('\n') if args.listAllOption: with open(args.jsonFile) as input: bday = json.load(input) print('name') print(bday) if args.listMonthlyOption: currentDay = datetime.now().day currentMonth = datetime.now().month print([bday for bday in bdayList if bday['date']['month']==currentMonth]) print(currentDay) print(currentMonth) if __name__ == "__main__": sys.exit(main())
friends = {'chuck': 23, 'fred': 25, 'eugene': 23} for name, age in friends.items(): print(name, age)
from art import logo print(logo) alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n").lower() #TODO-2: Inside the 'encrypt' function, shift each letter of the 'text' forwards in the alphabet by the shift amount and print the encrypted text. #e.g. #plain_text = "hello" #shift = 5 #cipher_text = "mjqqt" #print output: "The encoded text is mjqqt" ##HINT: How do you get the index of an item in a list: #https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list ##🐛Bug alert: What happens if you try to encode the word 'civilization'?🐛 def directionToGo(direction): if direction in "": print("You type nothing") elif (direction == "encode") or (direction == "decode"): should_continue = True while should_continue: text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) shift = shift % 26 ## if the user insert a number major like 26 caesar(direction = direction, plain_text = text, shift_amount = shift) result = input("Type 'Yes' if you want to go again. Otherwise type 'no'. ").lower() if result == 'no': should_continue = False print("Goodbye!") else: print("Rong answer!") def caesar(direction, plain_text, shift_amount): cipher_text = "" new_position = -1 for letter in plain_text: if letter in alphabet: position = alphabet.index(letter) if direction == "encode" or direction == "decode": new_position = encryptDecrypt(direction, position, shift_amount) else: print("Something go rong!") new_letter = alphabet[new_position] cipher_text += new_letter else: cipher_text += letter print(f"The {direction} test is {cipher_text}") #TODO-1: Create a function called 'encrypt' that takes the 'text' and 'shift' as inputs. def encryptDecrypt(direction, position, shift_amount): if direction == "encode": if position == 25: #last letter new_position = 0 + (shift_amount - 1) else: new_position = position + shift_amount elif direction == "decode": if position == 25: #last letter new_position = 25 - shift_amount else: new_position = position - shift_amount else: new_position = position - shift_amount return new_position #TODO-3: Call the encrypt function and pass in the user inputs. You should be able to test the code and encrypt a message. directionToGo(direction = direction)