text
stringlengths
37
1.41M
def arraySum(numbers): # Write your code here length = len(numbers) sum = 0 if(isinstance(numbers,list)): for number in numbers: sum = sum + number return sum else: return #TEST CASE ONE numbers = [1,2,3,4,5] print(arraySum(numbers))
#Indra Ratna #CS-UY 1114 #05 Oct 2018 #Lab 5 #Problem 4 terms = int(input("Enter a positive integer: ")) v1 = 1 v2 = 1 count = 0 while(count<terms): print(v1,end=" ") new = v1+v2 v1=v2 v2=new count+=1
from input_functions import validate, convert_to_rpn, find_minterms from Quine_McCluskey import minimize def main(): while True: print("\nOperators:\n and: &\n or: |\n xor: ^\n not: ~\n implication: >\n equivalence: =\n") print("Use: ( x | y ) > ( ~ a ) & b\nor: Me&You > You&(~Him)|(Him^You)\n") sentence = input("Input:\n") if validate(sentence): minterms = [] rpn, variables = convert_to_rpn(sentence) print("\tRPN:\t", rpn) print("\tVariables:\t", variables) answers = find_minterms(rpn,variables) for i in range(len(answers)): if answers[i]: minterms.append(i) print("\tMinterms: ", minterms) if len(minterms) == 0: print('Always false') else: minimize(variables, minterms) else: print("Wrong sentence, try again") if input("\nWant to continue? press [y]\nDon't want to continue? press [anything else]\n") == 'y': continue else: return if __name__ == "__main__": main()
import matplotlib.pyplot as plt import numpy as np def Bisection(f,a,b,tol,max_iteration): iter = 0 while True: c = (a+b)/2 x = f(c) y = f(a) if x == 0: return(c) elif (x * y) <0: b = c else: a = c iter = iter + 1 z = (b-a)/2 if iter > max_iteration: return (c, iter) if z < tol: return (c, iter) def f(x): return(32*x**6-48*x**4+18*x**2-1) var,iteract = Bisection(f, 1, 2, (5*(10**-4)), 100) print(var , iteract) t = np.arange(1,2,.1) plt.figure(1) plt.plot(t,f(t), "visual") plt.savefig("Figure_1_Lab2.eps") plt.show() #iteration counter |x*-C| <= #only matplotlib
def add1(): x = 1 return lambda y: x+y a = add1() b = add1() print a(9) print b(99) def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def hello(): return "hello" hello = makebold(hello) print(hello())
n1 = int(input('Valor:')) n2 = int(input('Valor_:')) s = n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 //n2 e = n1 ** n2 print('A Soma É {} \n A multiplicação é:{} \n Divisão é {:.3f} ' .format(s, m, d)) print('Divisão Inteira é: {} \n A Potencia é: {}' .format(di, e))
''' from math import factorial n = int(input("Digite Um Numero Para Fatorial: ")) f = factorial(n) print("O Fatorial de {} é {}".format(n,f)) ''' n = int(input("Digite Numero: ")) c = n f = 1 print("Calculando {}!= ".format(n), end="") # Esclamação Significa Fatorial while c > 0: print("{} ".format(c), end="") # Com END="" Ende Igual á Vazio -> Ele não pula linha P/ Mostrar os Resultados. print(" X " if c> 1 else "=", end="") f = f * c # Ou também -> f *= c c -= 1 print("{}".format(f))
n1 = int(input('Nota_1')) n2 = int(input('Nota_2')) n3 = int(input('Nota_3')) n4 = int(input('Nota_4')) n5 = int(input('Nota_5')) R = (n5+ n4+ n3 + n2 + n1) / 5 print ('A media é igual a:{}'.format(R))
Sal = float(input('Qual Seu Salário?? R$: ')) R_ = (Sal / 100 * 15) + Sal print ('Almento Salarial de 15% {:.2f}R$ Para -> Novo Salário: {:.2f}R$'.format(Sal, R_))
print('Gerador de PA') print(78*"=*=") primeiro = int(input('Primeiro Termo: ')) #VAI SER SOMADO AO SEGUNDO razão = int(input("Razão PA: ")) #SEGUNDO TERMO VAI SENDO SOMADO A ELE MESMO+ O PRIMEIRO TERMO termo = primeiro cont = 1 tot = 0 mais = 10 #A quantidade de termos\numeros que é mostrada quando o usuario comanda. while mais != 0: tot = tot + mais #ou 0 + 10 while cont <=tot: print("{} -> ".format(termo), end="") #eSTE END="" FAZ TUDO APARECER NA MESMA LINHA EM SEQUENCIA, E NÃO UM EM BAIXO DO OUTRO. termo += razão cont += 1 print("PAUSA") mais = int(input("Quantos termos você quer mostrar a mais? ")) print("Progressão finalizada com {} termos mostrados.".format(tot)) print("Fim")
from datetime import date ano = int(input('Que Ano Quer Analizar? Coloque 0 para Analisar o Ano Atual: ')) if ano == 0: ano = date.today().year if ano % 4 == 0 and ano % 100 !=0 or ano % 400 ==0: '''O Sinal de ! na linha acima significa: Que se o que estiver antes dele(!) for falso, então execute o que estiver depois''' '''Ele retorna o contrário da resolução da operação o qual ele precede. Ou seja: !true == false !false == true !(2 == 2) == false !(2 == 1) == true''' print('O Ano {} É BISSEXTO'.format(ano)) else: print('O Ano{} Não É BISSEXTO'.format(ano))
# 09-01-19 from collections import OrderedDict #Nesta nova vdersão Tuplas podem ser usadas SEM Parenteses: lanche = ("Burg","Suco",'pizza','Pudim') #__________________ for La in lanche[0:4]: #Se eu Especificar O Fatiamento na Tupla\Lista etc, #..Ele Omite\ Mostra Itens da Tupla. #Se eu usar o fatiamento no indice, Neste caso La, ele omite\Mostra Letras dos Itens. print(La.capitalize() ,end=" - ") #Printa Um Item Por Linha SEM as ASPAS. #MAS o ,end=" - " Faz eles Ficarem na mesma Linha print("\n") #___________________ print("Indice\Item 3 Da Tupla:\t" + lanche[3]) print(lanche[0:2] , "Mostra todos Os Elementos Antes do Indice 2: Ou 0 & 1") print(lanche[1:], "Do UM ao Penultimo da Tupla") print(len(lanche)," Itens Na Tupla") print(lanche[-2] + "-> Penultimo Item ou [-2]") #lanche = OrderedDict comida = {"Inhoque"} #OLHA O QUE EU DESCOBRI !!!!!!! comida.add(lanche[:]) #COMIDA Recebeu\Concatenou Lanche com Seu Prorpio Conteudo. #comida = OrderedDict() print(comida, "+++") eat = ('Arroz', 'Jaca', 'Maça') #Para "Concatenar" Tuplas, Ou Add novos valores nelas: eat = ('Arroz', 'Jaca', 'Maça', 'Soja') print(eat) #Continua em: # https://youtu.be/q8Z1cRdJnfk?list=PLHz_AreHm4dksnH2jVTIVNviIMBVYyFnH
from math import hypot #import math co = float(input('Comprimento do Cateto Oposto:')) ca = float(input('Comprimento do Cateto Adjacente:')) '''hi = (co ** 2 +ca ** 2 ) ** (1/2) print('A Hipotenusa Vai Medir {:.3f}'.format(hi))''' hi = hypot(co,ca) #hi = math.hypot(co,ca) print('A Hipotenusa Vai Medir {:.2f}'.format(hi))
#22-07-2020 """ #Minha Tentativa :/ qtd = 6 store = [] for qtd in range(0, 6): entrada = int(input("Digite Um numero: ")) store.append(entrada) print(store) for x in store: print("Maior Valor =", max(x)) print("Menor Valor = ", min(x)) """ #https://youtu.be/q8Z1cRdJnfk?list=PLHz_AreHm4dksnH2jVTIVNviIMBVYyFnH
frase = str(input('Digite Uma Frase: ')).strip().upper() #Colocou o UPPER Aqui Para não ter problemas com tamanho de letras palavras = frase.split() junto = ''.join(palavras) #Este comando junta todas as palavras com o simbolo que estiver (ou não) entre as Aspas print('Você digitou a frase {} '.format(frase)) print('Frase Juntada {}' .format(junto)) #inverso = '' # Esta variavel pertense ao esquema do FOR inverso = junto[::-1] #Ou: O inverso valerá junto do inicio (:) até o fim (:), mas de trás p frente (-1) .Solução usando Fatiamento. '''for letra in range(len(junto)-1,-1, -1): print(junto[letra]) inverso += junto[letra]''' # LEN-> Vai até a ultima Letra com o -1. #Segundo -1 -> Ir até a primeira letra (Que não é Zero e Sim o 1 ou -1). O ultimo -1 Indica que é Pra voltar, ou andar da ultima á primeira. #Sem o -1 ficaria Ex: em 20 -> do 0 ao 19. Com o -1 ele tira o ZERO e fica do 1 ao 20 print('O Inverso de {} é {}'.format(junto,inverso)) print(inverso) if inverso == junto: print('Temos um Palindromo') else: print('A Frase Digitada Não É Um Palindromo! ')
''' Coded triangle numbers Problem 42 The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? Answer: 162 Completed on Tue, 26 Dec 2017, 09:26 ''' file = open("p042_words.txt", "r") data = file.read() file.close() import math triangleNums = list(range(1, 20)) for c, value in enumerate(triangleNums, 1): triangleNums[c-1] = int(value * (value + 1) / 2) triangleNums = set(triangleNums) print(triangleNums) numCount = 0 dataList = data.split(',') print(len(dataList)) for s in dataList: ss = list(s) sumof = 0 for c in ss: if c == '"': continue sumof += ord(c) - ord('A') + 1 ''' sumof *= 2 num1 = int(math.sqrt(sumof)) num2 = num1 + 1 if num1 * num2 != sumof: continue ''' if sumof not in triangleNums: continue numCount += 1 print("numCount: %d" % (numCount))
''' Cyclical figurate numbers Problem 61 Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formulae: Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ... Square P4,n=n2 1, 4, 9, 16, 25, ... Pentagonal P5,n=n(3n−1)/2 1, 5, 12, 22, 35, ... Hexagonal P6,n=n(2n−1) 1, 6, 15, 28, 45, ... Heptagonal P7,n=n(5n−3)/2 1, 7, 18, 34, 55, ... Octagonal P8,n=n(3n−2) 1, 8, 21, 40, 65, ... The ordered set of three 4-digit numbers: 8128, 2882, 8281, has three interesting properties. The set is cyclic, in that the last two digits of each number is the first two digits of the next number (including the last number with the first). Each polygonal type: triangle (P3,127=8128), square (P4,91=8281), and pentagonal (P5,44=2882), is represented by a different number in the set. This is the only set of 4-digit numbers with this property. Find the sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and octagonal, is represented by a different number in the set. Answer: [1281, 8128, 2882, 8256, 5625, 2512] 28684 Completed on Fri, 9 Feb 2018, 10:58 ''' from math import sqrt def is3Triangle(num:int): return -0.5 + sqrt(0.25 + 2 * num) def is4Square(num:int): return sqrt(num) def is5Pentagonal(num:int): return (0.5 + sqrt(0.25 + 6 * num)) / 3 def is6Hexagonal(num:int): return (1 + sqrt(1 + 8 * num)) / 4 def is7Heptagonal(num:int): return (1.5 + sqrt(2.25 + 10 * num)) / 5 def is8Octagonal(num:int): return (2 + sqrt(4 + 12 * num)) / 6 def getNumAttribute(num:int, funcList:list): res = tuple() funcListLen = len(funcList) for i in range(funcListLen): func = funcList[i] resNum = func(num) if resNum == int(resNum): res += (i + 3, ) return res def severNum(num:int): numStr = str(num) headNum = int(numStr[:2]) rearNum = int(numStr[2:]) return (headNum, rearNum) def getNext(numList:list, step:int, repreList:list, resList:list): if step == TARGET_STEP: resList.append(numList.copy()) return lastNum = numList[step - 1] rear = severNum(lastNum)[1] if rear < 10: return rear = headDict[rear] for i in rear: numList[step] = i repre = DICT[i] for j in repre: if repreList[j] == 1: continue repreList[j] = 1 getNext(numList, step + 1, repreList, resList) repreList[j] = 0 return triangle3Test = [1, 3, 6, 10, 15] square4Test = [1, 4, 9, 16, 25] pentagonla5Test = [1, 5, 12, 22, 35] hexagonal6Test = [1, 6, 15, 28, 45] heptagonal7Test = [1, 7, 18, 34, 55] octaonal8Test = [1, 8, 21, 40, 65] ''' test = octaonal8Test for i in test: print(is8Octagonal(i)) ''' NUM_RANGE = 4 minNum = 10 ** (NUM_RANGE - 1) maxNum = 10 ** NUM_RANGE DICT = dict() headDict = dict() funcList = [is3Triangle, is4Square, is5Pentagonal, is6Hexagonal, is7Heptagonal, is8Octagonal] TARGET_STEP = 6 # 计算出所有的数字具有的属性 for i in range(minNum, maxNum): res = getNumAttribute(i, funcList) if len(res) <= 0: continue DICT[i] = res # 计算头部数字对应关系 for i in range(10, 100): headDict[i] = tuple() for i in DICT.keys(): res = severNum(i) headDict[res[0]] += (i, ) numList = [0] * 6 repreList = [0] * 9 resList = list() for key, value in DICT.items(): numList[0] = key for i in value: repreList[i] = 1 keyHead = severNum(key)[0] getNext(numList, 1, repreList, resList) repreList[i] = 0 for numList in resList: if not severNum(numList[0])[0] == severNum(numList[TARGET_STEP-1])[1]: continue print(numList) print(sum(numList)) for j in range(TARGET_STEP): print(numList[j], end = '') print(getNumAttribute(numList[j], funcList)) print()
class Solution: def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ _size = len(nums) #print(_size) lastReachable = _size - 1; for i in range(_size-1, -1, -1): if(i + nums[i] >= lastReachable): lastReachable = i # print(lastReachable) return lastReachable == 0
def a(): print('a() starts') b() d() print('a() returns') def b(): print('b() starts') c() print('b() returns') def c(): print('c() starts') print('c() returns') def d(): print('d() starts') print('d() returns') a() # Python will remember which line of code called the function so that the execution can return there when it encounters a return statement # If that original function called other functions, # the execution would return to those function calls first, before returning from the original function call.
# isX() Methods return True or False depending on the contents of the string ''' isapha() returns True if the string consists of letters ONLY and isn't blank ; is alphabet isalnum() returns True if the string consists only of letters and #s and is not blank ; is alphabet and numbers isdecimal() returns True fi the string consists of only numeric characters and not blank ; is decimal == numeric isspace() returns True if not blank and consists of only spaces, tabs, and newlines ; is spaces and other things with space istitle() returns True if string has only of words that start with an uppercase letter followed by only lowercase ; like titles''' # print('hello'.isalpha()) # print('hello123'.isalpha()) # print('hello123'.isalnum()) # print('hello'.isalnum()) # letters or numbers too, doesn't have to be both # print('123'.isdecimal()) # print(' '.isspace()) # print('This Is Title Case'.istitle()) # print('This Is Title Case 123'.istitle()) # can include numbers # print('This Is not Title Case'.istitle()) # print('This Is NOT Title Case Either'.istitle()) # startswith() ; endswith() Methods: # returns True or False depending on if the string value they called on starts of ends with the string passed to the method print('Hello, world!'.startswith('Hello')) print('Hello, world!'.endswith('world!')) print('abc123'.startswith('abcdef')) print('abc123'.endswith('12')) # False; close to the end but is not the actual end print('Hello, world!'.startswith('Hello, world!')) # True print('Hello, world!'.endswith('Hello, world!')) # True # this methods are alternatives to the == operator if you need to see if the first or last part instead of the whole thing # is equal to another string
#1. Which of the following are operators, and which are values? # * is an operator # 'hello' is a string value # -88.8 is a floating point number value # - is an operator # / is an operator # + is an operator # 5 is an integer value #2. Which of the following is a variable, and which is a string? # spam is a variable and 'spam' is a string #3. Name three data types: floating point numbers, integers, and strings #4 What is an expression made up of? What do all expressions do? # Expressions are made up of an operator and some values. Expressions all reduce down to a single value. #5. What is the difference between an expression and an assignment statement? # An assignment statement uses an assignment operator or = and assigns a value to a variable while an expression uses # no assignment operator and simplifies or solves down to a single value. #6 What does bacon contain after the code bacon = 20, bacon +1, runs? bacon is still 20 but the expression is 21. #7 What do 2 expressions evaluate to? 'spam' + 'spamspam' and 'spam' * 3 # 'spamspamspam' and 'spamspamspam' #8. Why is eggs a valid variable name but not 100? 100 starts with a number #9 What three functions can be used to get the integer, floating-point number, or string version of a value? # int() or str() or float() #10 Why does this expression cause an error? How can you fix it? 'I have eaten ' + 99 + ' burritos.' # 99 is not converted to a string and left as an integer so Python does not understand. You fix it by doing the # command str(99) which turns 99 to a string
# Multiline string is used for hash comments that are really long! """This is a test Python program. Written by Anna Ween @me.com This program was designed for Python 3, not Python 2. """ def spam(): """This is a multiline comment to help explain what the spam() function does.""" print('Hello!') # Indexing and Slicing STrings spam = 'Hello, world!' print(spam[0]) print(spam[4]) print(spam[-1]) print(spam[0:5]) # reminder: goes up to 5 but not included print(spam[:5]) print(spam[7:]) spam = 'Hello, world!' fizz = spam[0:5] # slicing doesn't change the og string print(fizz) # store the slice somewhere else in another var # in and not in Operators (strings): works the same as normal print('Hello' in 'Hello, World') print('Hello' in 'Hello') print('HELLO' in 'Hello, World') print('' in 'spam') print('cats' not in 'cats and dogs') # this is case sensitive, must be exact
def addToInventory(inventory, addedItems): total = 0 for i in range(len(dragonLoot)): # check dragonLoot to see if there is a match for k in inv.keys(): # add 1 to the value if it is found in inv if inv.keys() in dragonLoot: return (inv.values() + 1) else: return str(addedItems) return(total + 1) def displayInventory(inventory): print('Inventory: ') itemTotal = 0 for k, v in inventory.items(): print(str(v, k)) itemTotal += str(v) print('Total number of items: ' + str(itemTotal)) inv = {'gold coin': 42, 'rope': 1} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = addToInventory(inv, dragonLoot) displayInventory(inv)
# import random # numberOfStreaks = 0 # H = 'heads' # T = 'tails' # # for experimentNumber in range(10000): # Code that creates a list of 100 'heads' or 'tails' values # if random.randint(0, 1) == 0: # print(list('H')) # elif random.randint(0, 1) == 1: # print(list('T')) # # if H or T == 6: # numberOfStreaks += 1 # currentStreaks = numberOfStreaks # print('Chance of streak: %s%%' % (currentStreaks / 100))Code that checks if there is a streak of 6 heads or tails in a row # Make a variable for the flips # in one experiment with a double for loop # append the coin flip value to the coin flip list for experiment 1 # coin flip - 1 to check the index of previous coin flip to see if it is matching to form it in a row times # if it doesn't match then the streak ends # if it reaches 6 then add to the number of streaks # then repeat for experiment 2 and reset import random numberOfStreaks = 0 inARow = 0 heads = 'H' tails = 'T' coinFlip = [] for experimentNumber in range(10000): # Code that creates a list of 100 'heads' or 'tails' values for flips in range(100): # Double for loops (make 100 flips) if random.randint(0,1) == 0: output = heads elif random.randint(0,1) == 1: output = tails result = output print(list(result)) coinFlip.append(result) # Adds H or T after whatever is in the list coinFlip if (flips-1) < 0: pass elif coinFlip[flips-1] == result: inARow += 1 if inARow == 6: numberOfStreaks += 1 else: numberOfStreaks += 0 coinFlip = [] print('Chance of streak: %s%%' % (numberOfStreaks / 100)) # Code that checks if there is a streak of 6 heads or tails in a row
#!/usr/bin/env python3 # Mark Pasquantonio # Senior Design and Dev COMP490 # Project 1 JobsAssignment Sprint 2 # Filename: get_git_database.py import sqlite3 from sqlite3 import Error global connection def create_connection(): global connection db_file = "git_jobs.sqlite" """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ try: connection = sqlite3.connect(db_file) return connection except Error as e: print(e) return connection def create_table(con, create_table_sql): """ create a table from the create_table_sql statement :param con: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ try: c = con.cursor() c.execute(create_table_sql) except Error as e: print(e) def main(): sql_create_jobs_table = """CREATE TABLE IF NOT EXISTS git_jobs_tbl ( id integer NOT NULL, type text NOT NULL, url text NOT NULL, created_at integer NOT NULL, company integer NOT NULL, company_url text NOT NULL, title text NOT NULL, location text NOT NULL, description text NOT NULL );""" # create a database connection connect = create_connection() # create tables if connect is not None: # create projects table create_table(connect, sql_create_jobs_table) else: print("Error! cannot create the database connection.") if __name__ == '__main__': main()
# Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters - each taken only once - coming from s1 or s2. def longest(a1, a2): new="" # make a string lst=[] # make a list lst2=[] # make a list final="" # make a string new+=a1 # add both a1 and a2 to first string new+=a2 for a in new: lst.append(a) # put a1 and a2 into a list lst.sort() # put list in alpha order for a in lst: if a not in lst2: # if letter not in lst2, add lst2.append(a) for a in lst2: final+=a # convert list to string return final print(longest("aretheyhere", "yestheyarehere"))
def validate_pin(pin): pin="".join(num for num in pin if num.isnumeric()) print(pin) for num in pin: if num if len(pin)<4: return False elif len(pin)>6: return False elif len(pin)==4: return True elif len(pin)==6: return True elif len(pin)==5: return False print(validate_pin("-1634"))
# def gimme(input_array): # print(input_array.sort(key=len)) # if input_array==[]: # return[] # dup_arr=input_array # l=sorted(dup_arr) # mid=l[1] # for num in input_array: # if num==mid: # print(num) # num_i=input_array.index(num) # return num_i # print(gimme(["howsy", "rar", "ajdaiaie"])) list=["howsy", "rar", "ajdaiaie"] print(sorted(list, key=len))
# Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms. # If you want to know more http://en.wikipedia.org/wiki/DNA # In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell). def DNA_strand(dna): dna=dna.upper() compStrand=[] #string="" for r in (dna): if r =="A": result="T" compStrand.append(result) if r=="G": result="C" compStrand.append(result) if r=="T": result="A" compStrand.append(result) if r== "C": result="G" compStrand.append(result) string = ''.join([str(elem) for elem in compStrand]) print(f"The complementary strand for {dna} is {string}.") DNA_strand("AGCTagtc") def DNA_strand(dna): dna=dna.upper() comp_strand="" for r in dna: print(r) if r == "A": comp_strand+="T" if r == "T": comp_strand+="A" if r == "G": comp_strand+="C" if r == "C": comp_strand+="G" return comp_strand print(DNA_strand("AAAA"))
def mxdiflg(a1, a2): short_a1, short_a2="","" i=0 while i<len(a1): if len(a1[i])>len(short_a1): short_a1+=(a1[i]) i+=1 print(short_a1) i=0 while i<len(a2): if len(a2[i])>len(short_a2): short_a2+=(a2[i]) i+=1 answer= max(len(short_a1), len(short_a2))-min(len(short_a1),len(short_a2)) return answer print(mxdiflg(["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"],["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"])) def mxdiflg(a1, a2): short_a1, short_a2=[],[] i=0 while i<len(a1): if len(a1[i])>len(short_a1): short_a1+=[] short_a1+=(a1[i]) print(short_a1) i+=1 short_a1=''.join(short_a1) # print(short_a1) i=0 while i<len(a2): if len(a2[i])>len(short_a2): short_a2+=[] short_a2+=(a2[i]) i+=1 short_a2=''.join(short_a2) # print(short_a2) # answer= max(len(short_a1), len(short_a2))-min(len(short_a1),len(short_a2)) shortest=max(short_a1,short_a2) print(shortest) print(mxdiflg(["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"],["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]))
def solution(number): if number<0: return 0 list=[] i=1 while 0<=i<number: list.append(i) i+=1 sum=0 for num in list: if (num%5==0) or (num%3==0): sum+=num return sum print(solution(20))
def alphabet_position(text): alpha=['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'] strng="" for let in text: let=let.lower() if let in alpha: x= alpha.index(let)+1 x=str(x) strng+=x strng+=" " return strng[:-1] print(alphabet_position("The narwhal bacons at midnight."))
def is_valid_walk(walk): vertical=0 horizontal=0 starting_point=0 num_n=walk.count('n') num_e=walk.count('e') num_s=walk.count('s') num_w=walk.count('w') for movement in walk: if movement== "n": vertical+=1 starting_point+=1 if movement== "e": horizontal+=1 starting_point+=1 if movement== "s": vertical-=1 starting_point-=1 if movement== "w": vertical-=1 starting_point-=1 vert_disp=(max(num_n, num_s)-min(num_n,num_s)) horz_disp=(max(num_w, num_e)-min(num_w,num_e)) print(f"len walk: {len(walk)}") print(starting_point) print(f"vertical: {vertical}") print(horizontal) print(vert_disp) print(horz_disp) if (len(walk)==10) and (starting_point==0) and (vertical==0) and (horizontal==0) and (vert_disp==0) and (horz_disp==0): return True if (len(walk)==10) and (starting_point==0) and (vertical + horizontal ==0)and (vert_disp==0) and (horz_disp==0): return True elif (len(walk)!=10)or (starting_point!=0) or (vertical!=0) or (horizontal!=0)or (vert_disp!=0) or (horz_disp!=0): return False
# This program is showing content based recommender system based on movie description import pandas as pd from ast import literal_eval from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import linear_kernel class ContentBaseRecomender: """ this is content base recommender class recommendation based on movie similarity, check movie description and vectorized it and find similarity. file link https://www.kaggle.com/rounakbanik/the-movies-dataset/downloads/movies_metadata.csv/7 """ def __init__(self, data, dataframe=None): """ initiate data frame :param data: :param dataframe: """ if dataframe: self.df_movie = dataframe else: self.df_movie = pd.read_csv(data) def modify_dataframe(self): """ keep only required data """ # Only keep those features that we require self.df_movie = self.df_movie[ ['title', 'genres', 'release_date', 'runtime', 'vote_average', 'vote_count', 'id', 'overview']] # genre operations self.df_movie['genres'] = self.df_movie['genres'].fillna('[]') self.df_movie['genres'] = self.df_movie['genres'].apply(literal_eval) # convert genre dictionary to list self.df_movie['genres'] = self.df_movie['genres'].apply( lambda x: [i['name'] for i in x] if isinstance(x, list) else []) # also remove NaN from "overview" field self.df_movie['overview'] = self.df_movie['overview'].fillna('') def create_tf_idf_matrix(self): """ creating tf-idf matrix based on movie "overview", note here we are removing stop words stop words are common english words like "the","a","in","on" etc. """ # clean dataframe self.modify_dataframe() tfidf = TfidfVectorizer(stop_words='english') # Construct the required TF-IDF matrix by applying the fit_transform method on the overview feature # This matrix is contains all word vectors.one dimension of this matrix should be the same as df_movie data frame tfidf_matrix = tfidf.fit_transform(self.df_movie['overview']) # Compute the cosine similarity matrix THIS STEP IS HEAVILY COMPUTE BASED. it required atleast 32 GB RAM. self.cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix) return self.cosine_sim def create_index_mapping(self): """ this function is creating mapping between title and index for east title search """ print(self.df_movie) self.indices = pd.Series(self.df_movie.index, index=self.df_movie['title']).drop_duplicates() return self.indices def get_recommendation(self, movie_title, top=10): """ get recommendation based on movie title, enter movie title and get top similar movie based on description """ # Obtain the index of the movie that matches the title cosine_sim = self.create_tf_idf_matrix() # create index and cosine matrix indices = self.create_index_mapping() try: movie_index = indices[movie_title] # Get the pairwsie similarity scores of all movies with that movie from cosine index sim_scores = list(enumerate(cosine_sim[movie_index])) # Sort the movies based on the cosine similarity scores sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) # Get the scores of the top most similar movies. Ignore the first movie. sim_scores = sim_scores[1:top] # Get the movie indices movie_indices = [i[0] for i in sim_scores] # return top similar movies return self.df_movie['title'].iloc[movie_indices] except IndexError: print("Movie that entered for recommendation is not found or may be mispelled?")
import re file_name = input() reg = input() input_file = open(file_name, mode="r") fileLines = input_file.readlines() for line in fileLines: if re.search(reg, line): print(line)
import math r = 2 area = math.pi * pow(r,2) print("{:.10f}".format(area))
def _odd_iter(): n=1 while True: n = n+2 yield n def _not_divisible(n): return lambda x: x%n>0 def primes(): yield 2 it = _odd_iter() while True: n = next(it) yield n it = filter(_not_divisible(n),it) for i in primes(): if i < 1000: print(i) else: break
#!/usr/bin/python3 import math class Unit(object): def __init__(self, value, gradient): self.value = value self.gradient = gradient class MultiplyGate(object): def forward(self, u0, u1): self.u0 = u0 self.u1 = u1 self.utop = Unit(self.u0.value * self.u1.value, 0.0) return self.utop def backward(self): self.u0.gradient += self.u1.value * self.utop.gradient self.u1.gradient += self.u0.value * self.utop.gradient class AddGate(object): def forward(self, u0, u1): self.u0 = u0 self.u1 = u1 self.utop = Unit(self.u0.value + self.u1.value, 0.0) return self.utop def backward(self): self.u0.gradient += 1 * self.utop.gradient self.u1.gradient += 1 * self.utop.gradient class SigmoidGate(object): def sigmoid(self, x): """ Computes the sigmoid function wrt x. Reference: http://en.wikipedia.org/wiki/Sigmoid_function """ return (1 / (1 + math.exp(-x))) def forward(self, u0): self.u0 = u0 self.utop = Unit(self.sigmoid(self.u0.value), 0.0) return self.utop def backward(self): """ Computes the local derivative with respect to its input, then multiplies on the gradient from the unit above. """ sig = self.sigmoid(self.u0.value) self.u0.gradient += (sig * (1 - sig)) * self.utop.gradient class ForwardNeuron(object): def __init__(self, mulg0, mulg1, addg0, addg1, sigg0): self.mulg0 = mulg0 self.mulg1 = mulg1 self.addg0 = addg0 self.addg1 = addg1 self.sigg0 = sigg0 def forward(self, a, b, c, x, y): self.a = a self.b = b self.c = c self.x = x self.y = y ax = self.mulg0.forward(a, x) by = self.mulg1.forward(b, y) axpby = self.addg0.forward(ax, by) axpbypc = self.addg1.forward(axpby, c) self.sig = self.sigg0.forward(axpbypc) def backward(self, gradient=1.0, step_size=0.01): """ Gradient """ self.sig.gradient = gradient self.sigg0.backward() self.addg1.backward() self.addg0.backward() self.mulg1.backward() self.mulg0.backward() self.a.value += step_size * self.a.gradient self.b.value += step_size * self.b.gradient self.c.value += step_size * self.c.gradient self.x.value += step_size * self.x.gradient self.y.value += step_size * self.y.gradient self.forward(self.a, self.b, self.c, self.x, self.y) if __name__ == '__main__': a = Unit(1.0, 0.0) b = Unit(2.0, 0.0) c = Unit(-3.0, 0.0) x = Unit(-1.0, 0.0) y = Unit(3.0, 0.0) mulg0 = MultiplyGate() mulg1 = MultiplyGate() addg0 = AddGate() addg1 = AddGate() sigg0 = SigmoidGate() neuron = ForwardNeuron(mulg0, mulg1, addg0, addg1, sigg0) neuron.forward(a, b, c, x, y) forward = 'Circuit output: {0}\n'.format(neuron.sig.value) print(forward) gradient = 1.0 step_size = 0.01 neuron.backward(gradient, step_size) backward = 'Circuit output after backprop: {0}\n'.format(neuron.sig.value) print(backward)
# Corey Caskey # Section C3 # GT ID: 903120273 # [email protected] # I worked on the homework assignment alone, using only this semester's course materials. # cocaCola # parksAndRec # iLoveFrozen # oscars # springBreakCalc # breakfastPlatters def cocaCola(): bottles = int(input("How many cans of Coke have you bought this week?")) totalAmount = bottles * 0.99 return totalAmount def parksAndRec(): weeks = int(input("How many weeks can you watch Parks and Recreation?")) dailyHours = float(input("How many hours of TV do you watch per day?")) hoursOfTV = weeks * 7 * dailyHours numOfEpisodes = (hoursOfTV * 60) / 21 return int(numOfEpisodes) def iLoveFrozen(dollars): theater = input("Are you going to Regal, AMC, or SMG to watch the movie?") if theater == "Regal": times = int(dollars / 12) print("You can see Frozen " + str(times) + " time(s).") elif theater == "AMC": times = int(dollars / 15) print("You can see Frozen " + str(times) + " time(s).") else: times = int(dollars / 9) print("You can see Frozen " + str(times) + " time(s).") def oscars(winners): speeches = int(input("How long, in minutes, do you think each speech will be?")) length = winners * speeches hours = int(length / 60) timeHours = hours + 8 minutes = length % 60 if timeHours >= 12: print("The Oscars cannot go past 11:59 pm.") else: if minutes >= 0 and minutes <= 9: minutes = "0" + str(minutes) print("The oscars will end at " + str(timeHours) + ":" + minutes + " pm.") else: minutes = minutes print("The oscars will end at " + str(timeHours) + ":" + str(minutes) + " pm.") def springBreakCalc(people, miles, costOfHotel): mpg = int(input("What's your car's MPG?")) gas = float(input("What's the cost of gas?")) tip = int(input("What percentage tip do you want to leave?")) gasMoney = float((miles / mpg) * gas) tipMoney = float(costOfHotel * (tip / 100)) totalCost = gasMoney + costOfHotel + tipMoney costPerPerson = totalCost / 3 costPerPerson = round(costPerPerson, 2) print("Each person needs to pay $" + str(costPerPerson) + " this Spring Break.") def breakfastPlatters(eggs,bacon,grits): eggPlatters = int(eggs / 2) baconPlatters = int(bacon / 3) gritsPlatters = int(grits / 1) if eggPlatters <= baconPlatters and eggPlatters <= gritsPlatters: numOfPlatters = eggPlatters elif baconPlatters <= eggPlatters and baconPlatters = gritsPlatters: numOfPlatters = baconPlatters else: numOfPlatters = gritsPlatters return numOfPlatters
#https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/magical-word/ prime_numbers = [] def is_prime(number): if number == 1: return True if number > 1: for _ in range(2, number): if (number % _) == 0: return False return True else: return False def get_nearest_prime_number(number): for i in range(0, len(prime_numbers)): if number == prime_numbers[i]: return number elif number < prime_numbers[i] and i ==0: return prime_numbers[i] elif i == len(prime_numbers)-1 and number > prime_numbers[i]: return prime_numbers[i] elif number > prime_numbers[i] and number < prime_numbers[i+1]: left_diff = number - prime_numbers[i] right_diff = prime_numbers[i+1] - number if right_diff < left_diff: return prime_numbers[i+1] else: return prime_numbers[i] def get_prime_numbers(): for n in range(65, 91): if is_prime(n): prime_numbers.append(n) for n in range(97, 123): if is_prime(n): prime_numbers.append(n) def main(): t = int(input()) get_prime_numbers() for _ in range(t): lst = [] n = int(input()) s = input() for i in range(0, n): ascii_ = ord(s[i]) lst.append(chr(get_nearest_prime_number(ascii_))) print("".join(lst)) if __name__ == '__main__': main()
data = open("dataAnalysis1.txt","r"); dataString = data.read() dataList = dataString.split("\n") for i in range(0, len(dataList), 1): dataList[i] = dataList[i].replace(",","") dataList[i] = float(dataList[i]) minimum = min(dataList) print(minimum) maximum = max(dataList) print(maximum) diff = maximum - minimum print(diff) smallest = dataList[0] for i in range (0, len(dataList), 1): if smallest > dataList[i]: smallest = dataList[i] print("MIN IS: " + str(smallest)) largest = dataList[0] for i in range (0, len(dataList), 1): if largest < dataList[i]: largest = dataList[i] print("MAX IS: " + str(largest)) maxvalue = input("What number do you want to set as upper limit: ") maxvalue = float(maxvalue) biggest = dataList[0] minvalue = input("What number do you want to set as lower limit: ") minvalue = float(minvalue) smallest1 = dataList[0] for i in range (0, len(dataList), 1): if maxvalue > dataList[i] and dataList[i] > biggest: biggest = dataList[i] print("MAX IS: " + str(biggest)) for i in range (0, len(dataList), 1): if minvalue < dataList[i] < smallest1: smallest1 = dataList[i] print("MIN IS: " + str(smallest1))
import tkinter as tk print("Start Program") root = tk.Tk() #Builds main window #Step 1: Construct the widget btn1=tk.Button(root, width = 10, height = 5) #Step 2: Configure the widget btn1.config(text = "I am a button") #Step 3: Place the widget - pack(), grid() btn1.pack() output = tk.Text(root, width=100, height=30) output.config() output.pack(); root.mainloop() print("END PROGRAM")
#### K nearest neighbor #### from math import sqrt # calculate the Euclidean distance between two vectors def euclidean_distance(row1, row2): distance = 0.0 for i in range(len(row1)-1): distance += (row1[i] - row2[i])**2 return sqrt(distance) # Locate the most similar neighbors def get_neighbors(train, test_row, num_neighbors): distances = list() for train_row in train: dist = euclidean_distance(test_row, train_row) distances.append((train_row, dist)) distances.sort(key=lambda tup: tup[1]) neighbors = list() for i in range(num_neighbors): neighbors.append(distances[i][0]) return neighbors # Make a classification prediction with neighbors def predict_classification(train, test_row, num_neighbors): neighbors = get_neighbors(train, test_row, num_neighbors) output_values = [row[-1] for row in neighbors] prediction = max(set(output_values), key=output_values.count) return prediction # Test distance function dataset = [[161, 61, 0], #### Herself [158, 58, 0], [158, 59, 0], [158, 63, 0], [160, 59, 0], [160, 60, 0], [163, 60, 0], [163, 61, 0], [160, 64, 1], [163, 64, 1], [165, 61, 1], [165, 62, 1], [165, 65, 1], [168, 62, 1], [168, 63, 1], [168, 66, 1], [170, 63, 1], [170, 64, 1], [170, 68,1]] neighbors = get_neighbors(dataset, dataset[0], 6) #### K=5 for neighbor in neighbors: print(neighbor)
# # Scooter sharing in Austin, Texas # In many cities around the world, micromobility in the form of # electric scooters has recently become very popular. The city of # Austin, Texas has made available trip-level data from all scooter # companies operating within the city limits. # This is the first notebook that we see in Stats 206. We are mainly # focused here on introducing the software tools and doing some very # basic summarization and description of the data. There are a lot of # new programming concepts below, and some of them are deliberately # only explained at a high level. We will revisit many of these # concepts later in the course and discuss them in greater detail at # that time. # # Importing modules # Python is a general-purpose programming language. On its own, it # can be used for some basic tasks. Most of the time, when working # with Python, you will be importing _modules_ containing code that is # not part of the core Python language, that will help you perform # more specialized tasks. For scientific computing and data science, # we almost always import the numpy and pandas modules. import numpy as np import pandas as pd # In addition, we will often need the "os" (operating system) module: import os # # Loading data from a file # The scooter data are in a format called "csv", which stands for # "comma separated values". This is the most common portable # text-based format for rectangular data (data arranged in a table # with rows and columns). The "pandas" package, imported above, # provides data management and basic data analysis capabilities in # Python. The central element of Pandas is a "dataframe", which is a # rectangular structure for holding data. # # Our first step here is to read the data from a csv format file # containing the scooter trips, and represent it in the computer's # memory as a dataframe. # First, modify this string according to your section number (001 or # 002): f = "stats206s002f21" # Now Pandas can read the data using the line of code below: base = "/scratch/%s_class_root/%s_class/shared_data/datasets" % (f, f) df = pd.read_csv(os.path.join(base, "scooters_short.csv.gz")) # The above commands create a dataframe holding the scooter trip data, # and creates a variable named `df` that is bound to this value. # # In the above commands, the values enclosed in quotation marks are # "strings". A string is a value that contains a sequence of text or # characters. In this case, the string bound to the "base" variable # is the "file path" pointing to the CSV file on greatlakes that we # wish to load. # Note also that the filename above ends with ".gz". This indicates # that the data are compressed so that the file takes up less space on # the disk. Pandas will automatically decompress the file when # reading it. # The dataframe that we just loaded contains all trips for a random # selection of 20,000 scooters drawn from the complete Austin mobility # dataset. # # Getting some basic information about the data # Now that we have the dataset loaded, we can do some basic things # with it. First, we will get the shape, or dimensions of the # dataframe: df.shape # The shape attribute contains the number of rows and the number of # columns in the dataframe. This dataset is a subset containing about # one quarter of the complete Austin e-mobility dataset. # Like most rectangular datasets, the rows of this dataset represent # cases and the columns represent variables. A case here is a single # trip on a rented scooter. The columns (variables) provide # information about the trip. Next we will see what the names of the # variables are. df.columns # Some of these variable names are self-explanatory, for others, we # will explain their meaning below as needed. The next line of code # displays the first few rows of the dataframe. Depending on the # width of your screen, it is possible that only a subset of the # columns will be shown, in which case the omitted columns are # displayed as "...". df.head() # Note that in the preceeding two code cells, "head" is followed by # parentheses and "columns" is not. This is because "head" is a method # while "columns" is an attribute. Methods are essentially functions, # and functions take arguments inside a pair of parentheses. # Attributes are not functions, and therefore do not have parentheses. # It is an error to use parentheses on an attribute, or to omit the # parentheses on a method. To avoid such errors, you will need to # learn when you have an attribute and when you have a method. # The `head` method takes an optional argument, which is the number of # rows to display. The default value of this argument is 5, so if we # call the method without any arguments, like above, we see five rows # of data. If we want to see a different number of rows, we can pass # an argument like this: df.head(3) # The "device ID" is a unique identifier for each scooter. The number # of times that a device ID appears in the dataframe is the number of # times that the scooter was rented during the period of time covered # by the dataset. Most of the device IDs appear multiple times in the # data set, since most of the scooters were rented multiple times. # # To learn more about the device IDs, we can select the column of the # dataframe containing these values using the syntax `df["Device # ID"]`. This creates a "series" since it contains data for only one # variable. The `unique` method then constructs another series # containing only the unique device IDs, and the `size` attribute of # this series tells us how many elements it contains. Thus, the # following line of code tells us how many unique scooters are # represented in this dataset. df["Device ID"].unique().size # The above code uses "chaining" to do three things in one line of # code. It may be instructive to see how this can be done in three # lines, without chaining. x = df["Device ID"] y = x.unique() y.size # We can now look at some summary statistics of how many times each # scooter was rented. The `value_counts` method determines all of the # distinct values in a series and counts how many times each occurs. # The `describe` method then produces a set of summary statistics for # these counts. df["Device ID"].value_counts().describe() # When Pandas reads a CSV file, the date and time variables are # usually not automatically converted to proper Pandas format. The # `dtypes` attribute tells us the storage format of each variable in # the dataframe. We can see below that the "Start Time" and "End # Time" variables have `object` storage format. To work with these # variables as time values we will want to convert them to "datetime64" # values. df.dtypes # The following lines of code perform this conversion for the "Start # Time" variable. Don't worry about the details of this conversion at # the moment. f = "%m/%d/%Y %I:%M:%S %p" df["Start Time"] = pd.to_datetime(df["Start Time"], format=f) # Now we check the types again and see that `Start Time` has type # "datetime64". df.dtypes # Now that we have this variable in a proper format, we can determine # the period of time covered by this dataset. print(df["Start Time"].min()) print(df["Start Time"].max()) # Regarding the use of `print` above -- the `print` function is used # to print a value to the notebook output cell. By default, the value # of the last expression in any code cell is always printed. If you # want to print more than one value from within a single code cell, # you should use the `print` function. # ## Scooter lifespan # One question that is often asked about scooter rentals is how long # the scooters stay in the fleet. In some cities, scooters have # generally not lasted very long before breaking or being stolen or # lost. To address this question, we can look at the earliest and # last rental of each scooter in the dataset. We do this by creating # a "grouped dataframe" with the `groupby` method. Grouped dataframes # are very powerful and we will use them frequently in this course. # We will explain how grouped dataframes work in more detail later. # This example is an introduction to show how grouped dataframes can # be used to achieve our current goals. dx = df.groupby("Device ID")["Start Time"].agg([np.min, np.max]) print(dx.columns) dx["duration"] = dx["amax"] - dx["amin"] print(df.shape, dx.shape) dx["duration"].describe() # `groupby` carries out a stratification of the data. In this case, # we are stratifying the data by the `Device ID` variable. Every # distinct value of `Device ID` forms a group. A group contains all # trips recorded for one scooter. We then select only the `Start # Time` variable. Finally, the `agg` method is used to carry out an # aggregation or summarization of the data for each group. # The functions passed as arguments to `agg()` are the functions used # to do the aggregation. Here we are aggregating using the `min` and # `max` functions. These will give us the minimum (earliest) and # maximum (latest) trip for each scooter. The `np.` is placed in # front of the `min` and `max` functions because they are part of the # numpy package, which we imported above. # Sometimes it can be hard to know what names the variables created by # the aggregation will have. Therefore, we print the names and see # here that they are "amax" and "amin". # We also printed the shapes of the two dataframes `df` and `dx`. # Here, `df` is the original dataframe that we loaded from a csv file, # and `dx` is the summarized dataframe containing one row for each # distinct device ID. Since there are 20,000 scooters in the dataset, # this summarized dataframe contains exactly 20,000 rows. # Once we have the minimum and maximum rental date per scooter, we can # subtract them to get the duration of time between the first and last # rental. Then, we use the `describe` method to get some basic # summary information about these durations. # We see that the median scooter was used for a period of 82 days. # Note that this is a biased estimate of the actual median lifespan # due to "truncation" and "censoring". We won't define these terms # precisely here, but they refer to the fact that some scooters were # in use before and/or after the period of time covered by this # dataset, so their actual lifespan is longer than the value # calculated here. There are more advanced statistical methods that # can be used to correct for this bias, but we will not pursue that # here. # ## Scooter usage over time # The usage of scooters varies throughout the year, and over the span # of several years. Scooter usage also varies by time of day and day # of week, but this is a separate topic that we will revisit later. # To focus on the longer term variation in scooter usage, we create a # variable below that counts the total number of trips taken during # each week within the dataset. We have around two year's of data, so # there are slightly more than 100 weeks. # To accomplish this goal, we will add two new columns to the # dataframe, one containing the year in which the trip occured, and # one containing the week within the year that the trip occured (which # is an integer between 1 and 52). Since we already have the start # time of each trip, we only need to exract the year and week from the # start time, as shown below. The `dt` symbol is a special attribute # of datetime variables that allows us to do things that only make # sense with date and/or time values. df["year"] = df["Start Time"].dt.year df["weekofyear"] = df["Start Time"].dt.isocalendar().week # Now that we have a variables indicating the year and week of each # trip, we can use `groupby` to count how many trips occur for each # combination of a year and a week. Note that here, unlike above, we # are grouping by two variables, which must be placed in a list using # square brackets (`[]`). dx = df.groupby(["year", "weekofyear"]).size() # Here we are taking advantage of the built in `size` aggregation # method. This gives us the number of rows per group, which is # equivalent to the number of trips per week. The same result can be # obtained using dxx = df.groupby(["year", "weekofyear"])["Device ID"].agg(np.size) # To confirm that these two series are equal, we can use the # following: assert(all(dx == dxx)) # It would make most sense to graph these counts, but we are not # introducing graphing yet in this notebook, so we will simply display # the counts in a table. Since our grouped dataframe here groups by # two variables, we have what is called a "hierarchical index". We # could view the result (`dx`) directly, but to make it easier to read # the table, we can "unstack" it to produce a table in which the rows # are years and the columns are weeks. This will be a 4 x 52 table # since we have at least some data in each of four years. For viewing # on the screen, it is better to have a table that is longer rather # than wider, so we use the transpose (`T`) attribute to put the weeks # in the rows and the years in the columns. dx.unstack().T # In the result of the above cell, a `NaN` ("not a number") will # appear in any cell that has no data. This includes some cells that # fall in the future relative to when the data were obtained, and some # earlier cells for which no data are available. # The results show that scooter usage increased rapidly in late summer # of 2018 and remained very popular until late fall of 2019. Note the # spike in week 11 of 2019, corresponding to the "South by Southwest" # event. By late fall of 2019 and into the early winter of 2020, # scooter usage had dropped by around half relative to the same period # in the previous year. Then around week 12 of 2020, the COVID # pandemic reached the US, and scooter usage plumetted (although not # to zero). By the end of the data series in the summer of 2020, # usage had recovered slightly, but only to around 15% of usage in the # previous year. In 2021, scooter usage remained somewhat lower than # pre-pandemic levels. # ## Trip duration # Another characteristic of interest is the length of time of each # scooter trip. The `Trip Duration` variable contains this information # in units of seconds. Suppose we wish to calculate some basic # summary statistics for the trip durations for trips taken each # month. The `describe` method calculates many common summary # statistics. df.groupby("Month")["Trip Duration"].describe() # If we want to calculate a particular summary statistic, for example # several quantiles, we can proceed as below. Note that by dividing # the results by 60, the units become minutes rather than seconds. df.groupby("Month")["Trip Duration"].quantile([0.5, 0.9]).unstack() / 60
""" Board class used in the m, n, k game. """ class Board: def __init__(self, m, n, k): self.m = m self.n = n self.k = k # used to keep track of who has won or if the game is finished self.scores = [0 for i in range(m + n + 2*(m+n-1))] self.positions_occcupied = 0 def initi_board(self): # empty board array_board = [[" " for i in range(self.n)] for j in range(self.m)] self.array_board = array_board return array_board def drawboard(self): list_lines = [] for index_line, array_line in enumerate(self.array_board): number_spaces_before_line = 2 - len(str(index_line)) space_before_line = number_spaces_before_line * ' ' list_lines.append(f'{space_before_line}{index_line}| ' + ' | '.join(array_line) + ' |\n') line_dashes = ' ' + '-' * 6 * self.n + '-\n' board_str = line_dashes + line_dashes.join(list_lines) + line_dashes print(board_str) # THIS IS NOT USED AND AT THE FIRST ROUND IT DOESNT CHECK FOR VALIDITY def is_valid(self, row, col): return ((0 <= row <= self.m and 0 <= col <= self.n) and (self.array_board[row][col] == " ")) def _add_move(self, row, col, player_name): # change the posiiton of the array_board self.array_board[row][col] = player_name # update the posiitons of the scores to keep track of who has won # get the mark to add depending on the player if player_name == "X": mark = 1 else: mark = -1 self.scores[row] += mark # add +/-1 to the row index self.scores[self.m + col] += mark # add +/-1 to the col index self.scores[self.m + self.n + row + col] += mark # add +/-1 to the diag index self.scores[self.m + self.n + (self.m+self.n-2) + (self.m - row) + col] += mark # add +/-1 to the other diag index # add 1 to the palces occupied self.positions_occcupied += 1 def _undo_move(self, row, col, player_name): # change the posiiton of the array_board self.array_board[row][col] = " " # update the posiitons of the scores to keep track of who has won # get the mark to add depending on the player if player_name == "X": mark = 1 else: mark = -1 self.scores[row] -= mark # add +/-1 to the row index self.scores[self.m + col] -= mark # add +/-1 to the col index self.scores[self.m + self.n + row + col] -= mark # add +/-1 to the diag index self.scores[self.m + self.n + (self.m+self.n-2) + (self.m - row) + col] -= mark # add +/-1 to the other diag index # add 1 to the palces occupied self.positions_occcupied -= 1 def board_status(self): """ Check if the board is in a finished state. e.g. either full or someone has won """ # check if any values of the score are +/- k if self.k in self.scores: return 1 if -self.k in self.scores: return -1 # check if board is full if self.positions_occcupied == self.m * self.n: return 0 # otherwise keep playing return None
# -*- coding: utf-8 -*- import re seq1 = input("escreva a sequência 1:") seq2 = input("escreva a sequência 2:") check = re.match(seq1, seq2) if (check == None): print("sequências distintas!") else: print("sequências identicas!")
## -*- coding: utf-8 -*- idade = int(input("qual a sua idade?")) while(idade < 0): print("número invalido!!") idade = int(input("qual a sua idade?")) if (idade > 18 or idade == 18): print("você é maior de idade.") elif (idade > 0 and idade < 18): print("você é menor de idade")
## -*- coding: utf-8 -*- import re string = "me namora pois quando eu saio eu sei que vc chora e fica em casa so contando as horas" ## método search print somente o primeiro resultado busca = re.search("[^ ]*[r|R][^ |\.]*", string) if busca: print(busca.group()) ## método findall printa todos os resultados busca2 = re.findall("[^ ]*[r|R][^ |\.]*", string) if busca2: print(busca2) ## separa a string de acordo com um padrão busca3 = re.split("[^ ]*[r|R][^ |\.]*", string) if busca3: print(busca3) 99999-233131 [email protected] #coletando email email = input("qual o seu email?") check = re.match("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", email) while (check == False): print("email invalido!") email = input("qual o seu email?") check = re.match("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", email) print("email registrado!") ##coletando número numero = input("qual o seu número?") check2 = re.match("[0-9]+-[0-9]+", numero) while (check == False): print("número invalido!") email = input("qual o seu número?") check = re.match("[0-9]+-[0-9]+", email) print("número registrado!")
tu = 43.85, 5, False, "plijy" print(tu) print(tu[1]) f3 = tu[:3] print(f3) l3 = tu[2:] print(l3) m2 = tu[1:3] print(m2) wis = ("Bohr", "Leibniz", "Einstein") wis1 = [] wis2 = [9, 8 , 7, 6, 5, 4, 3, 2, 1, 0] for vis in wis : print(vis) for dig in wis2 : wis1.append(dig) print(wis1)
class Animal: # we can also inherte the attributes of the base class def __init__(self): self.age = 1 def eat(self): print("Eat") # Animal is Parent, Base Class # Mammal is a Child, Sub Class class Mammal(Animal): #Method overloading : means replacing or extendig the method defined in the base class def __init__(self): self.weight = 5 #To prevent Method Overloading super().__init__() def walk(self): print("Walk") class Fish(Animal): def swim(self): print("Swim") m = Mammal() m.eat() m.walk() print(m.age) f = Fish() f.eat() f.swim()
#!/usr/local/bin/python3 # Josh Klaus # CS131A # Python # A CGI program which serves up all the words from the dictionary which start with a given stem. # The stem was passed as an HTTP parameter called “stem”. import cgi, cgitb, codecs cgitb.enable() # Create instance of FieldStorage form = cgi.FieldStorage() # Get value from the URL field wordstem = form.getvalue('stem') wordlen = len(wordstem) # find length of argument tempwordlist = [] # create temporary list to hold words with codecs.open('/users/abrick/resources/american-english-insane-ascii', 'r', 'utf-8') as inFile: for line in inFile: if wordstem in line[:wordlen]: tempwordlist.append(line.strip()) cwd = ', '.join(tempwordlist) # print list as a string # Used for response to HTTP queries print("Content-type: text/plain") print() print( 'these are the words in the dictionary with that stem: ' + cwd )
from functools import reduce items = [1, 2, 3, 4, 5] squared = [] for i in items: squared.append(i**2) print('squared: {}'.format(squared)) new_squared = list(map(lambda x: x**2, items)) print('new_squared: {}'.format(new_squared)) def multiply(x): return x*x def add(x): return x+x funcs = [multiply, add] for i in range(5): value = list(map(lambda x: x(i), funcs)) print(value) number_list = range(-5, 5) less_than_zero = list(filter(lambda x: x < 0, number_list)) print(less_than_zero) product = 1 list_data = [1, 2, 3, 4] for num in list_data: product = product * num print('product: {}'.format(product)) new_product = reduce((lambda x, y: x * y), list_data) print('new_product: {}'.format(new_product))
m1=int(input("mark of s1:")) m2=int(input("mark of s2:")) m3=int(input("mark of s3:")) total=m1+m2+m3 print("total is",total) if(total>145): print("A+") elif((total>=140)&(total<=145)): print("A") elif((total>=135) & (total<=140)): print("B+") elif((total>=130) & (total<=135)): print("B") else: print("fail")
''' Este juego es una implementacion del juego clasico de memorias en Python 3.3.2, donde se tiene que encontrar todos los pares de cartas con el mismo numero para ganar el juego. MEMORY GAME Created by: Jassael Ruiz Version: 1.0 ''' import sys sys.path.append("..") import simplegui import random as rand WIDTH = 800 HEIGHT = 100 #numbers in range [0,8) deck_part1 = ['0', '1', '2', '3', '4', '5', '6', '7'] deck_part2 = ['0', '1', '2', '3', '4', '5', '6', '7'] deck_cards = deck_part1 + deck_part2 card_color = ["white" for card in deck_cards] card_size = [50, 100] exposed = [False for card in deck_cards] state = 0 turn = 0 index_card1 = 0 index_card2 = 0 # helper function to initialize globals def shuffle_deck(): rand.shuffle(deck_cards) def new_game(): global exposed, state, turn, card_color shuffle_deck() exposed = [False for card in deck_cards] state = 0 turn = 0 l_turn.set_text("Turns = " + str(turn)) card_color = ["white" for card in deck_cards] def is_exposed(index): return exposed[index] def expose_card(index): exposed[index] = True def hide_card(index): exposed[index] = False def get_card(index): return deck_cards[index] def change_color(index): card_color[index] = "green" # define event handlers def mouseclick(pos): global state, turn, index_card1, index_card2 # add game state logic here index = 0 minx = 0 maxx = card_size[0] posx = pos[0] while(maxx < WIDTH): if(minx < posx < maxx): break index += 1 minx, maxx = maxx, maxx + card_size[0] if(not is_exposed(index)): expose_card(index) if state == 0: #firt flipped card index_card1 = index state = 1 elif state == 1: #second flipped card index_card2 = index state = 2 turn += 1 l_turn.set_text("Turns = " + str(turn)) else: #state 2, we have two fliped cards card1 = get_card(index_card1) card2 = get_card(index_card2) if(card1 != card2): hide_card(index_card1) hide_card(index_card2) else: #the cards are equals change_color(index_card1) change_color(index_card2) index_card1 = index state = 1 # cards are logically 50x100 pixels in size def draw(c): cordx = 10 cardx = 0 if(False in exposed): for ind in range(len(deck_cards)): card = deck_cards[ind] if(is_exposed(ind)): c.draw_text(card, [cordx, card_size[1]], 60, card_color[ind]) cordx += card_size[0] cardx += card_size[0] c.draw_line([cardx, 0], [cardx, card_size[1]], 1, "white") else: c.draw_text("Congratulations you win !!, click reset to play again", [0, 50], 20, "white") # create frame and add a button and labels frame = simplegui.create_frame("Memory", WIDTH, HEIGHT) frame.add_button("Reset", new_game) l_turn = frame.add_label("Turns = " + str(turn)) # register event handlers frame.set_mouseclick_handler(mouseclick) frame.set_draw_handler(draw) # get things rolling new_game() frame.start() # Always remember to review the grading rubric
t = (3, 30, 2019, 9, 25) dic = { 'hour': t[0], 'minute': t[1], 'year': t[2], 'month': t[3], 'day': t[4] } print('%02d'%dic["month"], end = '/') print('%02d'%dic["day"], end = '/') print('%04d'%dic["year"], end = ' ') print('%02d'%dic["hour"], end = ':') print('%02d'%dic["minute"])
#!/usr/bin/env python def convert_from_strarray(str_array): """ string 配列を文字列に変換 :param str_array: 文字列が格納された配列 :return: html用配列文字列 """ return u"[\'" + u"\',\'".join(str_array) + u"\']" def convert_from_intarray(int_array): """ integer配列を文字列に変換 :param int_array: integerが格納された配列 :return: html用配列文字列 """ str_array = map(str, int_array) return u"[" + u",".join(str_array) + u"]"
def DisplayFile(): try: fd = open('Demo.txt','r', encoding ='utf-8') except IOError as io: print('File dose not exists:') #data = fd.read() else: print('File exists:') print(fd) data = fd.read() print('File Data is:',data) fd.close() DisplayFile()
def chknum(no): if(no > 0): print("number is positive"); elif(no < 0): print("number is nigative"); else: print("number is Zero"); chknum(10); chknum(-8); chknum(0);
arr = list() def listdemo(): sum = 0; no = int(input("how many number u print: ")); for i in range(0,no): n =int(input("number:")); sum = sum + n; arr.append(int(n)); return sum; ret = listdemo(); print("your Elements is ", arr); print("Addition of list", ret);
def fact(no): factorial = 1; if no < 0: print("number is negative"); elif no == 0: print("number is zero"); else: for i in range(1,no+1): factorial = factorial * i; print("factorial is",factorial); fact(5);
# Enoncé : Créez une fonction qui va dire bonjour à quelqu'un. Elle a un paramètre, le nom de la personne # que le programme salue. # Essayez d'appeler la fonction de 4 manières différentes # et une fois avec un input # stocké dans une variable. def bonjour (_name): print (f"Bonjour à toi {_name}") #1er bonjour("Mattéo") #2 prenom = "lucas" bonjour(prenom) #3 bonjour(input("Quel est votre prénom? \n ")) #4 prenom = input("Quel est votre prénom? \n") bonjour(prenom) #region indice # 1) avec une string directement. #endregion #region indice # 2) Avec une variable qui stocke une string #endregion #region indice # 3) Avec un input direct à l'appel de la fonction #endregion #region indicec # 4) Avec le resultat d'un input stocké dans une variable #endregion
# On peut voir le "while" comme un "if". Sauf qu'à la différence du if, le code se trouvant dans un while # est executé en boucle le temps que l'expression booléenne passe à false. On a donc un code comme ceci # while (condition): # CodeSExecutantEnBoucle() # Le problème de ce code, c'est qu'il n'y a rien qui permet de modifier la condition pour avoir la possibilité # une fois qu'elle passe à false, ce qui fait donc une boucle infinie. Et notre programme va donc planter ! # Il faut donc agir au sein du while sur la condition pour qu'elle se modifie et passe après un certain nombre # de cycle à false. Un while ressemble donc souvent à ceci # while(condition): # CodeSExecutantEnBoucle() # ModificationDeLaCondition() # Voilà pour la théorie, en sachant ça, essayez d'écrire un bout de code qui va écrire 5 fois Hello World. # Ensuite, posez vous la question de comment vous devriez modifier ce code si vous vouliez écrire 5000 fois Hello World # Si vous avez réussi, une seule ligne devrait être à modifier ! import sys print("Bonjour, votre va programme va effectuer les tâches, suivantes ;\n") print("Afficher 5 fois la phrase : Hello world ! ") print("Afficher 5000 fois la phrase : Hello world ! ") i = 0 while (i<5): print("Hello World!") i+=1 print(" ") i = 0 while (i<5000): print("Hello World!") i+=1 print("Vous êtes à la fin du programme") sys.exit("Fin")
#Ici vous trouverez la fonction que j'ai faite (jessie) en classe pour calculer l'année de naissance en fonction de l'âge entré par l'utilisateur def CalculateBitdate(_age): _currentYear = 2021 print("Vous avez" + str(age) + "ans et vous êtes né en "+ str(_currentYear -int(_age))) age = input("Quel est votre âge") CalculateBitdate(age)
""" A game is a dictionary with the following structure: { board: [['X', '', ''], ['', 'O', ''], ['X', '', '']] players: [player_foo, player_bar] turn: player_foo } """ GAMES = [] def get_game(player_id): """Find the game in which player_id is playing.""" for game in GAMES: if player_id in game["players"]: return game return None def join_game(player_id): """ If there is a game without a second player, have player_id join it. Otherwise, create a new game for player_id. """ # If player_id is already in a game, return that game game = get_game(player_id) if game != None: return game # Find a game with only one player, and join it for game in GAMES: if len(game["players"]) < 2: game["players"].append(player_id) return game # Otherwise start a new game game = {} # Create an empty board game["board"] = [["", "", ""] for i in range(3)] # Add current player as player1 game["players"] = [player_id] # Player1 gets to start game["turn"] = player_id # Add the new game to GAMES GAMES.append(game) return game def remove_game(player_id): """Remove the game player_id is playing in.""" for i in range(len(GAMES)): if player_id in GAMES[i]["players"]: del GAMES[i] return
from array import * arr = array('i', ()) n = int(input("enter the length of array")) for i in range(n): x = int(input("enter the length of array")) arr.append(x) print(arr) val = int(input("enter the value")) for k in range(n): if (val == arr[k]): print(" value is at :" ,k ) # else: # print("no value") # if val == arr[k]: # print("the value is at :", k) # else: # print("value is not in array") # )
from array import * vals = array( 'i' ,[1,2,3,4,5,6,7,8]) print(vals) # for i in range(3): # while(i<7): # f = i+1 # print(vals[f] , end = " ") # i = i+1; # print("\n") # m = number of shift # n = size of array # e = incremental integer g=0 while(g<4): for e in range (8): f = 0; #number of shift if (e<=(7-g)): f= e+g print(vals[f] , end = " ") else: f= 0+g print(vals[f] , end = " ") e=e+1 g= g+1 print("\n");
from datetime import datetime, date date_of_birth = datetime.strptime(input("Enter date of birth in the format dd mm yyyy: "), "%d %m %Y") future_day = datetime.strptime( input("Enter the date when you want to find the age, in the format dd mm yyyy: "), "%d %m %Y") def calculate_age(sDate, eDate): #TODO: try except to compare dates return eDate.year - sDate.year - ((eDate.month, eDate.day) < (sDate.month, sDate.day)) #TODO: calculate months as well age = calculate_age(date_of_birth, future_day) print(age)
# move Zero # 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 # 双指针 class Solution: def moveZeroes(self, nums: List[int]) -> None: # length = len(nums) # i = j = 0 # while j < length: # if nums[j] != 0: # nums[i], nums[j] = nums[j], nums[i] # i += 1 # j += 1 j = 0 for i in range(len(nums)): if nums[i] != 0: nums[j] = nums[i] if (i != j): nums[i] = 0 j += 1
# 64. 最小路径和 # 给定一个包含非负整数的 m x n 网格 grid ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。 # dp class Solution: def minPathSum(self, grid: List[List[int]]) -> int: dp = grid m = len(dp) n = len(dp[0]) for i in range(m): for j in range(n): if i == 0 and j == 0: continue elif i == 0: dp[i][j] = dp[i][j - 1] + dp[i][j] elif j == 0: dp[i][j] = dp[i - 1][j] + dp[i][j] else: dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + dp[i][j] return dp[m- 1][n -1]
## # displayinfo.py # DisplayInfo class. Pop up window with radio buttons to select an option # name: Gregory Marvin ## import tkinter as tk import tkinter.messagebox as tkmb from PIL import ImageTk, Image import requests import textwrap from movieData import MovieData from playtrivia import PlayTrivia class DisplayInfo(tk.Toplevel) : def __init__(self, master, movieName, title="Displaying Info") : tk.Toplevel.__init__(self, master) # override the Toplevel window constructor # DisplayInfo takes the focus from its master self.grab_set() self.resizable(True, True) # allow the window to be resizable # if window is closed call the cancel method to clean up self.protocol("WM_DELETE_WINDOW", self.cancel) # set master so it can be accessed by methods of DisplayInfo self._master = master # set the title with the provided value self.title(title) # create label to indicate that the user should select an option self.optionLabel = tk.Label(self, text="Select an option:").grid(row=0, column=0, columnspan=2, sticky='nsw') # create control variable for the radiobuttons self.controlVar = tk.StringVar() # create a radiobutton for showing movie info in listbox self.rbMovieInfo = tk.Radiobutton(self, text="Movie Info", variable=self.controlVar, value='info', command=self.updateListBox).grid(row=1, column=0, sticky='nsew') # create a radiobutton for showing movie facts in listbox self.rbRandomFacts = tk.Radiobutton(self, text="Interesting Facts", variable=self.controlVar, value='facts', command=self.updateListBox).grid(row=1, column=1, sticky='nsew') # create a radiobutton for showing movie quotes in listbox self.rbReviews = tk.Radiobutton(self, text="Quotes", variable=self.controlVar, value='quotes', command=self.updateListBox).grid(row=1, column=2, sticky='nsew') # create label to show name of movie entered by the user self.movie = tk.StringVar() self.movie.set(movieName) self.movieLabel = tk.Label(self, textvariable=self.movie).grid(row=5, columnspan=2, sticky='nsw') # create a vertical and horizontal scrollbar to scroll through if beyond the boundary of the ListBox widget self.yscroll = tk.Scrollbar(self, orient=tk.VERTICAL) # create ListBox to store the results of the search self.contentContainer = tk.Listbox(self, height=10, width=60, yscrollcommand=self.yscroll.set) self.contentContainer.grid(row=6, columnspan=3, sticky='nsew') # position across the whole window on row 6 # connect the scrollbar to the ListBox self.yscroll.config(command=self.contentContainer.yview) self.yscroll.grid(row=6, column=4, sticky='nsew') # create labels and buttons to start a game of trivia self.trivia = tk.StringVar() self.trivia.set("Would you like to play some trivia?") self.triviaLabel = tk.Label(self, textvariable=self.trivia).grid(row=7, column=0, columnspan=2, sticky='nsew') self.playTrivia = tk.Button(self, text="play", command=self.playTrivia).grid(row=7, column=2, sticky='nsew') # create labels and buttons to view the selected movies poster self.poster = tk.StringVar() self.poster.set("Click to see the movie's poster") self.poterLabel = tk.Label(self, textvariable=self.poster).grid(row=8, column=0, columnspan=2, sticky='nsew') self.seePoster = tk.Button(self, text="click!", command=self.viewPoster) self.seePoster.grid(row=8, column=2, sticky='nsew') # set up so window and widgets are resizable(listbox stays the same height) self.grid_columnconfigure(0 , weight=1) self.grid_columnconfigure(1 , weight=1) self.grid_columnconfigure(2 , weight=1) self.grid_rowconfigure(0 , weight=1) self.grid_rowconfigure(1 , weight=1) self.grid_rowconfigure(2 , weight=1) self.grid_rowconfigure(3 , weight=1) self.grid_rowconfigure(4 , weight=1) self.grid_rowconfigure(5 , weight=1) self.grid_rowconfigure(6 , weight=1) self.grid_rowconfigure(7 , weight=1) self.grid_rowconfigure(8 , weight=1) # set up so window appears down and right from the movie search window self.geometry("+%d+%d" % (master.winfo_rootx()+50, master.winfo_rooty()+50)) # fetch the data in a thread so the DisplayInfo window pops up immediately self.id = self.after(100, self.fetchData, movieName) def fetchData(self, movieName) : '''fetchData method, creates new MovieData object for web scraping and accessing API''' try : self.chosenMovie = MovieData(movieName, load_all_data=True) # gets data for provided movie self.getInfo() # get movie info self.getFacts() # get movie facts self.getQuotes() # get quotes from the movie except KeyError : print("Error, no movie with that name") tkmb.showerror("Uh-oh!", "Could not find anything by that name...\nClick ok and then press click to begin.") self.cancel() def viewPoster(self) : '''viewPoster method, creates pop up window with the movie poster''' def close() : '''local close method, eliminates the possibility an empty window is left after the 'x' is clicked''' self.popUpPoster.destroy() # create a Toplevel window so existance is independent of DisplayInfo window self.popUpPoster = tk.Toplevel() self.popUpPoster.resizable(False, False) self.popUpPoster.title("Movie Poster") # set title # cause window to pop up beyond DisplayInfo window so it is not obstructing self.popUpPoster.geometry("+%d+%d" % (self._master.winfo_rootx()+700, self._master.winfo_rooty())) self.popUpPoster.protocol("WM_DELETE_WINDOW", close) # if the window is closed, clean up and close try : # try to fetch the byte stream of the .jpg image at the url provided self.getImage = requests.get(self.chosenMovie.movie_technical_info['poster'], stream=True) # raise any exceptions self.getImage.raise_for_status() # create tk PhotoImage object that tkinter can use self.poster = ImageTk.PhotoImage(data = self.getImage.content) # create a label to store the picture self.imageWindow = tk.Label(self.popUpPoster, image=self.poster) self.imageWindow.grid() # puts the picture to the window # handle common exceptions that may arise except requests.exceptions.HTTPError as e : print('HTTP Error:', e) except requests.exceptions.ConnectionError as e : print('Connection Error:', e) except requests.exceptions.Timeout as e : print('Timeout Error:', e) except requests.exceptions.RequestException as e : print('Request Exception:', e) tkmb.showerror("Hmm...", "It doesn't look like an image could be found.") self.popUpPoster.destroy() def playTrivia(self) : '''playTrivia method, creates a new instance of the PlayTrivia class to manage a round of trivia''' if len(self.infoList) > 40 and \ (self.chosenMovie.movie_technical_info['director'] != "N/A" or \ self.chosenMovie.movie_technical_info['runtime'] != "N/A" or \ self.chosenMovie.movie_technical_info['rated'] != "N/A" or \ self.chosenMovie.movie_technical_info['imdb_rating'] != "N/A") : # start new game of trivia self.newGame = PlayTrivia(self, self.chosenMovie) else : tkmb.showerror("Sorry...", "Not enough information to play trivia.") def getInfo(self) : '''getInfo method, gets the info generated by the MovieData class''' # header and value with prefixed tab on the following line to aid in readability # for each value in getInfo. Hard coded headers to make them more meaningful than # the dictionary keys, otherwise possible loop to cut down lines of code. try : self.infoList = ['Title:'] self.infoList.append('\t' + self.chosenMovie.movie_technical_info['title']) self.infoList.append('Type:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['type']) self.infoList.append('Plot:') # textwrap object used to wrap plot within default listbox boundary for improved readability wrap = textwrap.TextWrapper(width=75) plot = wrap.wrap(text=self.chosenMovie.movie_technical_info['plot']) for row in plot : self.infoList.append('\t' + row) self.infoList.append('Main Actors:') # split comma separated list and put each value on new line to improve readability self.actorsList = self.chosenMovie.movie_technical_info['actors'].split(', ') for actor in self.actorsList : self.infoList.append('\t' + actor) self.infoList.append('Directed by:') # split comma separated list and put each value on new line to improve readability self.directorsList = self.chosenMovie.movie_technical_info['director'].split(', ') for director in self.directorsList : self.infoList.append('\t' + director) #self.infoList.append('\t' + self.chosenMovie.movie_technical_info['director']) self.infoList.append('Written by:') # split comma separated list and put each value on new line to improve readability self.writersList = self.chosenMovie.movie_technical_info['writer'].split(', ') for writer in self.writersList : self.infoList.append('\t' + writer) self.infoList.append('Production company:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['production']) self.infoList.append('Runtime:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['title'] + ' is ' + self.chosenMovie.movie_technical_info['runtime'] + ' long') self.infoList.append('Film release date:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['released']) self.infoList.append('DVD release date:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['dvd']) self.infoList.append('Country of origin:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['country']) self.infoList.append('Languages available:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['language']) self.infoList.append('Genre:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['genre']) self.infoList.append('MPAA Rating:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['rated']) self.infoList.append('Box Office earnings:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['box_office']) self.infoList.append('Awards:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['awards']) self.infoList.append('metacritic.com Metascore:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['metascore']) self.infoList.append('IMDB Rating:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['imdb_rating']) self.infoList.append('Number of IMDB votes:') self.infoList.append('\t' + self.chosenMovie.movie_technical_info['imdb_votes']) except AttributeError : print("Error, one or more values could not be found") except KeyError : print("Error, one or more values could not be found") def getFacts(self) : '''getFacts method, gets the facts generated by the MovieData class''' self.factList = [] # create empty list to concatenate fetched lists # create textwrap object to fit facts in the listbox for improved readability wrapper = textwrap.TextWrapper(width=75) try : # get trivia entries wrapped to fit in the listbox triviaList = [trivia for entry in self.chosenMovie.trivia for trivia in wrapper.wrap(text=entry)] self.factList += triviaList # concatenate to factlist # get goofs wrapped to fit in the listbox goofList = [goof for entry in self.chosenMovie.goofs for goof in wrapper.wrap(text=entry)] self.factList += goofList # concatenate to factlist # get credits wrapped to fit in the listbox creditList = [credit for entry in self.chosenMovie.crazycredits for credit in wrapper.wrap(text=entry)] self.factList += creditList # concatenate to factlist except AttributeError : self.factList.append("Error, no facts could be found...") def getQuotes(self) : '''getQuotes method, gets the quotes generated by the MovieData class''' #self.quoteList = [] # create textwrap object to fit quotes in the listbox for improved readability wrapper = textwrap.TextWrapper(width=75) try : # fill the quoteList with quotes from the movie that are wrapped to fit in the listbox self.quoteList = [quote for entry in self.chosenMovie.quotes for quote in wrapper.wrap(text=entry)] except AttributeError : self.quoteList = ["Error, no quotes found..."] def updateListBox(self) : '''updateListBox method, fills the listbox based off the radio button selected at the top of window''' if self.controlVar.get() == 'info' : # if the ListBox is not empty, clear it out to display the results of the new search if self.contentContainer.size() != 0 : self.contentContainer.delete(0, self.contentContainer.size()) # starts at first item, and goes to the last one(inclusive) # fill the listbox with movie information for item in self.infoList : self.contentContainer.insert(tk.END, item) elif self.controlVar.get() == 'facts' : # if the ListBox is not empty, clear it out to display the results of the new search if self.contentContainer.size() != 0 : self.contentContainer.delete(0, self.contentContainer.size()) # starts at first item, and goes to the last one(inclusive) # fill the listbox with movie facts for fact in self.factList : self.contentContainer.insert(tk.END, fact) elif self.controlVar.get() == 'quotes' : # if the ListBox is not empty, clear it out to display the results of the new search if self.contentContainer.size() != 0 : self.contentContainer.delete(0, self.contentContainer.size()) # starts at first item, and goes to the last one(inclusive) # fill the listbox with the movie's quotes for quote in self.quoteList : self.contentContainer.insert(tk.END, quote) def cancel(self, *args): '''[Cancel] button to close window''' # check if any of the threads are still running if self.id is not None : self.after_cancel(self.id) # if there is an after thread, cancel it self._master.focus_set() # set focus back to the master window self.destroy() # close window
#!/usr/bin/env python # ocw05_funtions.py var1 = 10 var2 = 5 def function(): var1 = 20 print 'Inside of this function, var1 is:', var1 return 'Hello world!' print function() def funct(var1, var2): print 'inside this ideration of the function, var1 is:', var1 print 'and var2 is:', var2 return var1**var2 print funct(5, 0) print funct(5, 3) print funct(8, 2) print 'Outside of the function, var1 is:', var1 print 'Outside of the function, var2 is:', var2
#!/usr/bin/env python x = raw_input("Input number: ") x = int(x) #print(type(x)) if x < 100: print("Too Bad") elif x == 100: print("Not Bad") else: print("meh.")
#!/usr/bin/env python # Spencer Harper's Split Calculator def addI(person, item): People[person] = People[person] + item return def choose(selection): if selection == 'end': person = 'end' return person else: person = raw_input('Input person: ') if person == 'Mel' or person == 'Dyl'\ or person == 'Dav' or person == 'Spe'\ or person == 'Tip': newItem = raw_input('Input price of item: $') newItem = float(newItem) People[person] += newItem return person else: person = '' return person def display(People): people = People.keys() people.sort() for person in People: if person != 'Tip': print '%-15s | %10.2f' %(person, People[person]) def tipOut(People, tip): people = People.keys() for person in People: People[person] += tip x = 0.0 People = {'Tip':x, 'Dyl':x, 'Dav':x, 'Mel':x, 'Spe':x} selection = '' while selection != 'end': option = raw_input('Enter an action ( \'+\' OR \'end\' ): ') if option == 'end': selection = 'end' elif option == '+': if choose(option) == '': print 'Choose a valid option.' selection = '' else: selection = '' else: print 'Choose a valid option.' selection = '' total = 0.0 people = People.keys() for person in people: total += People[person] tip = People['Tip'] print 'Total: $' + str(total) print 'Tip: $' + str(tip) tip = People['Tip'] / 4.0 tipOut(People, tip) print '-Each: $' + str(tip) print '-----------------------------------' display(People) print '-----------------------------------' print 'Thanks for using Spencer\'s split calculator.' print '-----------------------------------'
#!/usr/bin/env python3 import re result = re.search("Spencer", "My name is Spencer, dude.") print(result)
#!/usr/bin/env python # ocw15-palindromes.py from string import * def flip(string): string3 = [] x = 1 y = len(string) while len(string3) < y: string3.append(string[-x]) x += 1 return join(string3, '') def palindrome(string): x = len(string) / 2 string1 = string[:x] string2 = string[-x:] string3 = flip(string2) if string1 == string3: return 'This is a palindrome!' else: return 'This is not a palindrome!' input = raw_input('Enter a string: ') input = lower(input) print palindrome(input)
from tkinter import Frame, Label, Entry, Button, W,E, FLAT from frames.Home import Home from classes.User import User #Ventana de inicio de sesion class Login(Frame): def __init__(self, parent): self.parent = parent super(Login,self).__init__(parent, pady=100) self.label_title = Label(self, text="Login", font= ("Arial Bold", 30), pady=20) self.label_title.grid(row=1, column=3, columnspan=2) self.label1 = Label(self, text="Username:", font= ("Arial Bold", 15), anchor=W) self.label1.grid(row=2, column=3) self.entry_username = Entry(self) self.entry_username.grid(row=2, column=4) self.label2 = Label(self, text="Contraseña:", font= ("Arial Bold", 15), anchor=W) self.label2.grid(row=4, column=3) self.entry_password = Entry(self) self.entry_password.grid(row=4, column=4) self.bienvenida = Label(self, text="COVID-19", font=("Arial Bold", 20), anchor="center") self.bienvenida.grid(row=4, column=7, columnspan=3, pady=20, padx=50) self.sep_label = Label(self,text="") self.sep_label.grid(row=5, rowspan=3) self.login_button = Button( self, text="Iniciar Sesion", height=2, width=13, font=("Arial bold", 15), bg="deep sky blue", fg="white", relief = FLAT, cursor = "hand2", command=lambda:self.login() ) self.login_button.grid(row=9, column=3, columnspan=2) self.message_label = Label(self,text="", fg="red") self.message_label.grid(row=10,column=3, columnspan=2) def login(self): existe = False passw = "" user = None with open('usuarios.txt', 'r') as archivo: lineas = archivo.readlines() for linea in lineas: columnas = linea.split('-') if(self.entry_username.get() == columnas[2]): existe = True passw = columnas[3] user = User(columnas[0],columnas[1],columnas[2],columnas[3],columnas[4].split('\n')[0]) if(existe): if passw == self.entry_password.get(): home = Home(self.parent, user, Login(self.parent)) self.parent.create_window((0, 0), window=home, anchor="nw") self.parent.configure(yscrollcommand=self.parent.scroll.set) home.bind( "<Configure>", lambda e: self.parent.configure( scrollregion=self.parent.bbox("all") ) ) self.destroy() else: self.message_label.configure(text= "Contraseña incorrecta") else: self.message_label.configure(text= "Usuario no existente")
#coding=utf-8 class Gragh(): def __init__(self,nodes,sides): ''' nodes 表示点 sides 表示边 ''' self.sequense = {} self.side=[] for node in nodes: for side in sides: u,v=side if node ==u: self.side.append(v) elif node == v: self.side.append(u) self.sequense[node] = self.side self.side=[] print(self.sequense) ''' # Depth-First-Search ''' def DFS(self,node0): queue,order=[],[] queue.append(node0) while queue: v = queue.pop() order.append(v) for w in self.sequense[v]: if w not in order and w not in queue: queue.append(w) return order ''' beadth-First-Search ''' def BFS(self,node0): queue,order = [],[] queue.append(node0) order.append(node0) while queue: v = queue.pop(0) for w in self.sequense[v]: if w not in order: order.append(w) queue.append(w) return order def main(): nodes = [i+1 for i in range(8)] sides=[(1, 2), (1, 3), (2, 4), (2, 5), (4, 8), (5, 8), (3, 6), (3, 7), (6, 7)] G = Gragh(nodes,sides) print("广度优先搜索检索:%s"%G.DFS(1)) print("深度优先搜索检索:%s"%G.BFS(1)) if __name__ == "__main__": main()
"""Module to work with geocoding-related stuff.""" from typing import Tuple import httpx from settings import settings YANDEX_GEOCODER_API_URL = 'https://geocode-maps.yandex.ru/1.x' class UnknownAddressError(Exception): """Raised when address is not recognized.""" def fetch_coordinates(address: str) -> Tuple[float, float]: """Get latitude and longitude of a place by address.""" response = httpx.get( YANDEX_GEOCODER_API_URL, params={'geocode': address, 'apikey': settings.yandex_geocoder_api_key, 'format': 'json'}, ) response.raise_for_status() found_places = response.json()['response']['GeoObjectCollection']['featureMember'] if not found_places: raise UnknownAddressError most_relevant = found_places[0] return most_relevant['GeoObject']['Point']['pos'].split(' ')
import numpy as np import random class Network: def __init__(self,sizes,weights= None, biases= None) -> None: if biases!=None or weights!=None: print("Network loaded") self.layers= len(sizes) self.sizes= sizes self.weights= weights self.biases= biases else: print("Network created") self.layers= len(sizes) self.sizes= sizes weight_shapes= np.array([(a,b) for a,b in zip(sizes[1:],sizes[:-1])]) self.weights= np.array([np.random.standard_normal(s) for s in weight_shapes],dtype=object) self.biases= np.array([np.zeros((s,1)) for s in sizes[1:]],dtype=object) def feedForward(self,input): #takes an input vector and outputs a vector based on the current weights and biases a= input for w,b in zip(self.weights, self.biases): #applies matrix vector multiplication to every layer and adds the bias vector to it # where w is a matrix of weights and a,b is a vector(can be viewed as a n,1 matrix) #output of one is the input of the preceding layer a= Network.sigmoid(np.matmul(w,a)+b) return a def printWeights(self): for w in self.weights: print(w,"\n") def printBiases(self): for b in self.biases: print(b,"\n") @staticmethod def sigmoid(x): return 1/(1+np.exp(-x)) @staticmethod def sigmoid_prime(z): """Derivative of the sigmoid function.""" return Network.sigmoid(z)*(1-Network.sigmoid(z)) def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None): """Train the neural network using mini-batch stochastic gradient descent. The ``training_data`` is a list of tuples ``(x, y)`` representing the training inputs and the desired outputs. The other non-optional parameters are self-explanatory. If ``test_data`` is provided then the network will be evaluated against the test data after each epoch, and partial progress printed out. This is useful for tracking progress, but slows things down substantially.""" #for every epoch the whole trainibg set is split into mini batches after being randomized if test_data: n_test = len(test_data) n = len(training_data) for j in range(epochs): random.shuffle(training_data) mini_batches = [ training_data[k:k+mini_batch_size] for k in range(0, n, mini_batch_size)] #Every mini batch is fed as an input for gradient descent algorithm # Then for each mini_batch we apply a single step of gradient descent for mini_batch in mini_batches: self.update_mini_batch(mini_batch, eta) if test_data: print("Epoch {0}: {1} / {2}".format( j+1, self.evaluate(test_data), n_test)) else: print("Epoch "+str(j+1)+" complete...") print("Training complete!") def update_mini_batch(self, mini_batch, eta): """Update the network's weights and biases by applying gradient descent using backpropagation to a single mini batch. The ``mini_batch`` is a list of tuples ``(x, y)``, and ``eta`` is the learning rate.""" #Initializing arrrays of 0's in the shape of weights and biases nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] # x= training input , y= expected output for x, y in mini_batch: #for every training input it computes a gradient vector(delta_nabla) # for weights and biases and addes them to a vector so that it can be averaged after #summing it up for all the mini batch delta_nabla_b, delta_nabla_w = self.backprop(x, y) nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)] nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)] #Substracting the nabla vector from the weight vector since we are aiming for the steepest # # descent which is the negative of the gradient self.weights = [w-(eta/len(mini_batch))*nw for w, nw in zip(self.weights, nabla_w)] self.biases = [b-(eta/len(mini_batch))*nb for b, nb in zip(self.biases, nabla_b)] def backprop(self, x, y): """Return a tuple ``(nabla_b, nabla_w)`` representing the gradient for the cost function C_x. ``nabla_b`` and ``nabla_w`` are layer-by-layer lists of numpy arrays, similar to ``self.biases`` and ``self.weights``.""" nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] # feedForward activation = x activations = [x] # list to store all the activations, layer by layer zs = [] # list to store all the z vectors, layer by layer for b, w in zip(self.biases, self.weights): z = np.dot(w, activation)+b zs.append(z) activation = Network.sigmoid(z) activations.append(activation) # backward pass delta = self.cost_derivative(activations[-1], y) * \ Network.sigmoid_prime(zs[-1]) nabla_b[-1] = delta nabla_w[-1] = np.dot(delta, activations[-2].transpose()) # Note that the variable l in the loop below is used a little # differently to the notation in Chapter 2 of the book. Here, # l = 1 means the last layer of neurons, l = 2 is the # second-last layer, and so on. It's a renumbering of the # scheme in the book, used here to take advantage of the fact # that Python can use negative indices in lists. for l in range(2, self. layers): z = zs[-l] sp = Network.sigmoid_prime(z) delta = np.dot(self.weights[-l+1].transpose(), delta) * sp nabla_b[-l] = delta nabla_w[-l] = np.dot(delta, activations[-l-1].transpose()) return (nabla_b, nabla_w) def cost_derivative(self, output_activations, y): """Return the vector of partial derivatives \partial C_x / \partial a for the output activations.""" return (output_activations-y) def evaluate(self, test_data): """Return the number of test inputs for which the neural network outputs the correct result. Note that the neural network's output is assumed to be the index of whichever neuron in the final layer has the highest activation.""" #Aimed at testing the progress, returns how many of the inputs in the whole test data #that the network guessed correctly test_results = np.array([(np.argmax(self.feedForward(x)), np.argmax(y)) for (x, y) in test_data]) return sum(int(x==y) for (x,y) in test_results)
import matplotlib.pyplot as plt plt.plot([1,2,3,4]) #给ploy()一个列表数据[1,2,3,4],matplotlib假设它是y轴的数值序列, # 然后会自动产生x轴的值,因为python是从0作为起始的,所以这里x轴的序列对应为[0,1,2,3]。 plt.ylabel('some numbers') #为y轴加注释 plt.show() import matplotlib.pyplot as plt plt.plot([1,2,3,4],[1,4,9,16],'ro') plt.axis([0,6,0,20]) #axis()函数给出了形如[xmin,xmax,ymin,ymax]的列表,指定了坐标轴的范围。 plt.show() import numpy as np import matplotlib.pyplot as plt t = np.arange(0.,5.,0.2) plt.plot(t,t,'r--',t,t**2,'bs',t,t**3,'g^') #红色短划线,蓝色方块和绿色三角形 plt.show()
# -*- coding:utf-8 -*- # @Author :kobe # @time :13/4/2019 上午 9:41 # @File :get_time.py # @Software : PyCharm import time class GetTime(object): def getCurrentDate(self): date = time.strftime('%Y-%m-%d') # 当前日期格式为:2019-4-13 return date def getCurrentTime(self): now = time.strftime('%H_%M_%S') # 当前时间格式为:09_45_23 return now def getCurrentDateTime(self): dateTime = time.strftime('%Y-%m-%d %H_%M_%S') # 当前完整时间格式为:2019-4-13 09_45_23 return dateTime def getTimeStamp(self): timeStamp = int(time.time() * 1000) # 获取时间戳 return timeStamp if __name__ == '__main__': times = GetTime() print(times.getTimeStamp())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 11 17:31:58 2018 @author: virajdeshwal """ import matplotlib.pyplot as plt import pandas as pd import random file = pd.read_csv('Ads_CTR_Optimisation.csv') '''We are dealing with the different version of the same advertisement for the user''' '''We have to find the CTR(Click through Rate )for the user. We have the clicks from 10000 users and based on the clicks from 100k users we will choose which ads to show to the user. ''' '''There is no library to implement Thomson Sampling Algo. We have to write it from scratch. Let's do it ;) ''' #implementing the Thomson Sampling ALgo #Number of the users N=10000 d=10 ads_selected = [] #defind the two variables numbers_of_rewards_1=[0]*d numbers_of_rewards_0=[0]*d sum_of_rewards = [0]*d total_reward = 0 #we will loop all the selctions of the users for n in range(0,N): ad = 0 max_upper_bound =0 max_random=0 #We need to compute of each version of the ads (the average reward and the confidence interval) for i in range(0,d): random_beta =random.betavariate(numbers_of_rewards_1[i]+1, numbers_of_rewards_0[i]+1) if random_beta > max_random: max_random = random_beta ad =i ads_selected.append(ad) reward=file.values[n,ad] if reward==1: numbers_of_rewards_1[ad]= numbers_of_rewards_1[ad]+1 else: numbers_of_rewards_0[ad] = numbers_of_rewards_0[ad] +1 total_reward = total_reward +reward #Now time for visualize the results plt.hist(ads_selected) plt.title('Histogram of Ads Selected') plt.xlabel('Ads') plt.ylabel('Number of time Ad was selected') plt.show() print('\n\n Done ;)')
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: XF @site: https://www.cnblogs.com/c-x-a @software: PyCharm @file: Queues.py @time: 2020/2/14 21:40 """ class ArrayQueue: Default_Capacity = 10 def __init__(self): """ Create a empty queue. """ self.data = [[]]*ArrayQueue.Default_Capacity self.__size = 0 self.__front = -1 def __len__(self): return self.__size def Is_Empty(self): return self.__size == 0 def First(self): # if self.Is_Empty(): # raise Empty('Queue is empty') return self.__front def DeQueue(self): if self.Is_Empty(): raise Empty('Queue is empty') self.__front = (self.__front + 1) % len(self.data) self.__size -= 1 p = self.data[self.__front] # self.data[self.__front] = [] # if self.Is_Empty(): # self.__front = 0 # else: return p def EnQueue(self, e): avail = (self.__front + self.__size + 1) # % len(self.data) if self.__size == len(self.data) or avail>= len(self.data) : self.__ReSize(2*len(self.data)) # avail = (self.__front + self.__size + 1) % len(self.data) self.data[avail] = e self.__size += 1 return True def __ReSize(self, length): old = self.data self.data = [[]]*length # walk = self.__front # for k in range(len(old)): # self.data[k] = old[walk] # walk = (walk + 1) % len(old) # self.__front = -1 self.data[:len(old)] = old return True
import os import csv import numpy as np # Path to collect data csvpath = os.path.join('budget_data.csv') with open(csvpath, newline='') as budget_csv: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(budget_csv, delimiter=',') # Read the header row first (skip this step if there is now header) budget_header = next(csvreader) #print(f"CSV Header: {budget_header}") # define and initialize variables total_month = 0 total_sum = 0 budget_list = [] avg_change = 0 greatest_max = 0 greatest_min = 0 great_max_index = 0 great_min_index = 0 change = 0 # find total month and total sum for row in csvreader: total_month = total_month + 1 total_sum = float(row[1]) + total_sum # Create array budget_list.append(float(row[1])) # calculate change value in array change = np.diff(budget_list) # Calculate average change avg_change = (np.sum(change) / (len(budget_list)-1)) # Calculate max value and assign array index to variable great_max_index = np.argmax(change) # find max value from array and assign to variable greatest_max = change[great_max_index] # Calculate min value and assign array index to variable great_min_index = np.argmin(change) # find min value from array and assign to variable greatest_min = change[great_min_index] print("Financial Analysis") print("----------------------------------") print(f"Total Months: {total_month}") print(f"Total: ${total_sum}") print(f"Total: ${round(avg_change,2)}") print(f"Greatest Increase in Profits: Feb-2012 ({greatest_max})") print(f"Greatest Decrease in Profits: Sep-2013 ({greatest_min})")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 9 22:46:35 2020 @author: AktorEvan """ import pandas as pd doc = input("Please input the file name: ") colName = input ("Please input the column name: ") print("Loading the file, please wait..", "\n") file = pd.ExcelFile(doc+".xlsx") sheet_list = file.sheet_names print(len(file.sheet_names), "sheet(s) found in the file named", doc, "\n") i = 0 k = 1 listSheet = [] listDupl = [] while i < len(sheet_list): #List for dataframe listSheet.append(i) listSheet[i] = pd.read_excel(doc+".xlsx", sheet_name=sheet_list[i]) #To display the number of unique and duplicated values x = listSheet[i].duplicated(colName).value_counts() x = x.rename(index = {False : "Unique values", True : " Duplicates"}) #To show the name of each sheet print("Sheet name : ", sheet_list[i], "(", colName, ")", "\n", x, "\n") #list for duplicates listDupl.append(i) listDupl[i] = listSheet[i][listSheet[i].duplicated(colName)] #Export duplicates to .xlsx listDupl[i].to_excel(sheet_list[i]+" (duplicate lists).xlsx", sheet_name = sheet_list[i], index = False) i += 1 k += 1 print("Succefully scanned!")
if __name__ == '__main__': y, x = int(input()), int(input()) count = 0 print("All step: ") while(y != x): if x * 2 - y <= x - y // 2: x *= 2 print("x * 2") else: x -= 1 print("x - 1") count += 1 print(x) print("Total step:", count)
''' You're given the three angles a, b, and c respectively. Now check if these three angles can form a valid triangle with an area greater than 0 or not. Print "YES"(without quotes) if it can form a valid triangle with an area greater than 0, otherwise print "NO". ''' a,b,c=map(int,input().split(" ")) if (a+b+c)==180 and a!=0 and b!=0 and c!=0: if (a+b)>=c or (b+c)>=a or (c+a)>=b: print("YES") else: print("NO") else: print("NO")
#1.anaconda环境配置和解释器 将anaconda安装目录下的scripts文件的全路径添加到系统变量path中,python的默认解释器就是anaconda了 #2. print和input #1)print(*objects, sep=' ', end='\n', file=sys.stdout),无论什么类型,数值,布尔,列表,元组、字典...都可以直接输出,格式化输出中%字符是标记转换说明符的开始 1.输出字符串和数字 print("felix") # 输出字符串 print(100) # 输出数字 str = 'felix' print(str) # 输出变量 L = [1,2,'a'] # 列表 print(L) t = (1,2,'a') # 元组 print(t) d = {'a':1, 'b':2} # 字典 print(d) 2.格式化输出整数 str = "the length of (%s) is %d" %('felix',len('felix')) print(str) the length of (felix) is 6 3.格式化输出16进制,十进制,八进制整数 #%x — hex 十六进制 #%d — dec 十进制 #%o — oct 八进制 nHex = 0xFF print("nHex = %x,nDec = %d,nOct = %o" %(nHex,nHex,nHex)) nHex = ff,nDec = 255,nOct = 377 #2)Python3.x中input()函数接受一个标准输入数据,返回为string类型。当写完a = input()按回车时,光标闪烁即为在等待用户输入内容。此时,你可以输入任何字符串,输入的内容会存放到a变量中 #语法格式如下: input:输入函数 name=input("please enter your name:") print(name) #3.python基础讲解 #1)python变量特性+命名规则 变量命名规则:  #1.变量名的长度不受限制,但其中的字符必须是字母、数字、或者下划线(_),而不能使用空格、连字符、标点符号、引号或其他字符。 #2.变量名的第一个字符不能是数字,而必须是字母或下划线。 #3.Python区分大小写。 #4.不能将Python关键字用作变量名。 # 2)注释方法 单行注释和多行注释: Python中单行注释以#开头,多行注释用三个单引号 ''' 或者三个双引号 """ 将注释括起来。 # 3)python中“:”作用 冒号用于定义分片、步长,a[ : n]表示从第0个元素到第n个元素(不包括n),a[1: ] 表示该列表中的第1个元素到最后一个元素。 # 4)学会使用dir( )及和help( ) dir()用来查询一个类或者对象所有属性,help()函数帮助我们了解模块、类型、对象、方法、属性的详细信息,如dir(list),help(list) # 5)import使用 通常模块为一个文件,直接使用import来导入,用逗号分割模块名称就可以同时导入多个模块,可以使用 as 关键字来改变模块的引用对象名字;通常包总是一个目录,可以使用import导入包,或者from + import来导入包中的部分模块,使用from语句可以将模块中的对象直接导入到当前的名字空间,import 语句可以在程序的任何位置使用 # 6)pep8介绍 PEP8-style for python code #PEP8是针对python代码格式而编订的风格指南,采用一致的编码风格可以令代码更加易懂易读! #1 缩进与换行 每级缩进使用四个空格 #2 限制每行的最大长度为79个字符 #3 空行 顶层函数和类之间使用两个空行 类的方法之间用一个空行 在函数中使用空行表示不同逻辑段落 #4 导入位于文件的顶部 #5 避免多余空格 #6 注释 注释要保持与时俱进 一句后面两个空格 跟注释 #7 命名规范 除了正常的命名规范外 不要使用 大小写的L 大写的O 作为变量名 类名首字母大写 内部类 加上前导下划线 函数名应该小写 增强可读性可以使用下划线分割 #8 其他 #别用 ‘==‘ 进行布尔值 和 True 或者 False 的比较 应该用 is #4.python数值基本知识 # 1)python中数值类型,int,float,bool,e记法等 创建 int 值有两种方式:直接赋予变量整数值和使用构造器 int()创建 int类型实例,针对第二种方式,如果没有任何输入参数,那么创建 int实例值为0,int()可选参数 base 表示第一个参数值所属进制,默认为 10,表示输入值为十进制数。在所有的进制中,2-进制,8-进制 和 16-进制 可以通过添加前缀 0b/0B, 0o/0O, or 0x/0X 的方式进行转换。 创建 float 值有两种方式:直接赋予变量整数值和使用构造器 float() 创建 float 类型实例,使用第一种方式,如果该数值没有小数,需要添加后缀 .0,否则,解释器会认为这是 int 类型数值,使用 float() 构造器还可以定义无穷大(Infinity 或者 inf)和无穷小 布尔型仅有两个实例对象 False 和 True,布尔型是 int 类型的子类,False 等同于 0,True 等同于 1,对于构造器 bool() 方法来说,如果输入为空或者为 0,得到 False;否则得到 True # 2)算数运算符 + - *两个数相乘或是返回一个被重复若干次的字符串 / %返回除法的余数 **幂,返回x的y次幂 //取整除,返回商的整数部分(向下取整) # 3)逻辑运算符 and:布尔"与" - 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。 or:布尔"或" - 如果 x 是非 0,它返回 x 的值,否则它返回 y 的计算值。 not:布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 # 4)成员运算符 in:如果在指定的序列中找到值返回 True,否则返回 False。 not in:如果在指定的序列中没有找到值返回 True,否则返回 False。 # 5)身份运算符 用于比较两个对象的存储单元:is和is not,is 是判断两个标识符是不是引用自一个对象,is not 是判断两个标识符是不是引用自不同对象。 is 用于判断两个变量引用对象是否为同一个(同一块内存空间), == 用于判断引用变量的值是否相等 #6)运算符优先级 ** #指数 (最高优先级) ~ + - #按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@) * / % // #乘,除,取模和取整除 + - #加法减法 >> << #右移,左移运算符 & #位 'AND' ^ | #位运算符 <= < > >= #比较运算符 <> == != #等于运算符 = %= /= //= -= += *= **= #赋值运算符 is is not #身份运算符 in not in #成员运算符 not and or #逻辑运算符
import random def random_value(): value = random.randint(0,9); return value; def get_odd_start_position(): string_position = ''; names1 = [1,1,2,2,2,1,1,2,2,2]; names2 = ['k','q','r','n','b','K','Q','R','N','B']; for i in range(8): value = random_value(); while (names1[value] == 0) or (value >4): value = random_value(); names1[value] -=1; string_position += names2[value]; string_position += "/pppppppp/8/8/8/8/PPPPPPPP/"; for i in range(8): value = random_value(); while (names1[value] == 0) or (value <5): value = random_value(); names1[value] -=1; string_position += names2[value]; string_position += " w KQkq - 0 1"; return (string_position)
pi=3.141 r=int(input("Enter Radius of cirle")) area=pi*r**2 print("the area of circle os ",area)
import turtle import time heart = turtle.Pen() i=20 heart.color("red") heart.left(45) heart.forward(100) heart.right(90) heart.forward(100) heart.right(90) heart.forward(200) heart.right(90) heart.forward(200) heart.right(90) heart.forward(100) heart.right(90) heart.forward(100) heart.left(135) heart.forward(i) heart.right(90) heart.left(45) heart.forward(100+i) heart.right(90) heart.forward(100+i) heart.right(90) heart.forward(200+i) heart.right(90) heart.forward(200+i) heart.right(90) heart.forward(100+i) heart.right(90) heart.forward(100+i) # heart.speed(0) # heart.left(-140) # for i in range(1,4): # heart.up() # heart.left(140) # heart.forward(5) # heart.left(-140) # heart.down() # heart.color("red") # heart.left(45) # heart.forward(i*10) # heart.right(90) # heart.forward(i*10) # heart.right(90) # heart.forward(i*10*2) # heart.right(90) # heart.forward(i*10*2) # heart.right(90) # heart.forward(i*10) # heart.right(90) # heart.forward(i*10) # time.sleep(10) input()
import turtle import random toad = turtle.Pen() color = ["red", "green", "black", "blue", "yellow"] toad.shape("turtle") toad.hideturtle() toad.speed(0) for i in range(200): toad.fillcolor(random.choice(color)) toad.begin_fill() toad.circle(2*i) toad.left(10) toad.end_fill() # for j in range(50): # # toad.up() # toad.goto(random.randint(-50, 200), random.randint(-50, 200)) # toad.down() # # toad.color(random.choice(color)) # toad.fillcolor(random.choice(color)) # toad.begin_fill() # shape_sq = random.randint(10,200) # for i in range(4): # toad.forward(shape_sq) # toad.left(90) # toad.end_fill() input()
# data attributes: account_num, interest_rate, and balance class SavingsAccount: def __init__(self, account_num, interest_rate, balance): self.account_num = account_num self.interest_rate = interest_rate self.balance = balance # methods: get_account_num, check_balance, apply_interest, deposit, and withdraw def get_account_num(self): return self.account_num def get_balance(self): return self.balance def get_interest_rate(self, int_rate): self.balance = self.balance * (1 + int_rate) # self.apply_interest = self.balance * self.interest_rate return self.balance def get_deposit(self, deposit_amount): self.balance = self.balance + deposit_amount return self.balance def get_withdraw(self, withdraw_amount): if withdraw_amount > self.balance: return 'Insufficient funds' self.balance = self.balance - withdraw_amount return self.balance # Design a CDAccount as a subclass of the SavingAccount class class CDAccount(SavingsAccount): # new attributes: mini_balance def __init__(self, account_num, interest_rate, balance, mini_balance): SavingsAccount.__init__(self, account_num, interest_rate, balance) self.mini_balance = mini_balance # new methods: withdraw (this method should ensure the mini_balance in the account, # otherwise displays "insufficient balance") def get_mini_balance(self, mini_balance): if mini_balance > self.balance: return 'Insufficient Funds' self.balance = self.balance + mini_balance return self.balance # main() function, create an object of SavingAccount and perform deposit, apply interest, and withdraw operations; # then create an object of CDAccount and perform the same series of operations. def main(): print('Enter information for a saving account:') acct_num = input('Account number: ') int_rate = float(input('Interest rate: ')) balance = float(input('Initial Balance: ')) deposit_amount = float(input('Deposit Amount: ')) savings = SavingsAccount(acct_num, int_rate, balance) print('Account', savings.get_account_num(), 'Balance: $', format(savings.get_deposit(deposit_amount), ',.2f'), sep='') print('Applying Interest') print('Account', savings.get_account_num(), 'Balance: $', format(savings.get_interest_rate(int_rate), ',.2f'), sep='') withdraw_amount = float(input('Withdraw Amount: ')) print('Account', savings.get_account_num(), 'Balance: $', savings.get_withdraw(withdraw_amount)) print() print('Enter information for CD account:') acct_num = input('Account number:') int_rate = float(input('Interest rate:')) balance = float(input('Initial Balance:')) mini_balance = input('Minimum Balance:') deposit_amount = float(input('Deposit Amount: ')) cd = CDAccount(acct_num, int_rate, balance, mini_balance) print('Account', cd.get_account_num(), 'Balance: $', format(cd.get_deposit(deposit_amount), ',.2f'), sep='') print('Applying Interest') print('Account', cd.get_account_num(), 'Balance: $', format(cd.get_interest_rate(int_rate), ',.2f'), sep='') withdraw_amount = float(input('Withdraw Amount: ')) print('Account', cd.get_account_num(), 'Balance: $', cd.get_withdraw(withdraw_amount)) main()
# # class Person: # # def __init__(self, name, age): # # self.name, self.age = name, age # # def getName(self): # # print("Name: %s" %(self.name)) # # def getAge(self): # # print("Age: %d" %(self.age)) # # def getSex(self): # # print("Sex: %s" %(self.sex)) # # class Male(Person): # # sex = "Male" # # male = Male("Ngo Manh", 29) # # male.getName() # # male.getAge() # # male.getSex() # class Foo: # name = "Foo" # def getName(self): # print("Class: Foo") # class Bar(Foo): # name = "Bar" # def getName(self): # # print("Class: Bar") # print("Atribute name = " + super(Bar, self).name) # super(Bar, self).getName() # # print(Foo().name) # # Foo().getName() # # print(Bar().name) # # Bar().getName() # Bar().getName() class First: def getClass(self): print("Class First") class Second(First): def getClass(self): super() .getClass() print("Class Second") class Third(Second): def getClass(self): super().getClass() third = Third() third.getClass()
def hello(name): print("Hello " + name + " !") hello("Kim") def sum(list, start =0): sum = 0 i = start while i < len(list): sum += list[i] i += 1 return sum # for i in list: # sum += i # return sum result = sum([1,2,3], 2) print("result: %s" %result)
#!/usr/bin/env python import pandas as pd def avgcity(city, my_csv): citypop = {} for line in my_csv: mycity = line["loc"] #identificamos la localidad pop = float(line["pop"])# identificamos la poblacion y transformamos a un numero float if line["cases"] != "NA": # en este caso NA es el punto clave ya que decimos que se cree una funcion #donde si es que en las lineas no tiene el NA, REALIZE LA FUNCIONDE ABAJO. cases =float(line["cases"]) citypop[mycity] = citypop.get(mycity, [0,0,0]) #GENERAMOS RESPUES QUE TENGAN 3 NIVELES: EN EL PRIMERO GUARDAMOS LA POBLACION, EN EL 2 IDENTIFICADOR GUARDAMOS LOS CASOSY EN EL ULTIMO IDENTIFICADOR GUARDAMOS EL CONTEO. citypop[mycity][0] = citypop[mycity][0] + pop citypop[mycity][1] = citypop[mycity][1] + cases citypop[mycity][2] = citypop[mycity][2] + 1 for key in citypop: if key == city: avg_cases = 100000*citypop[key][2]/citypop[key][1] #CALCULAMOS EL PORCENTAJE DE CASO: en este caso multiplicamos por 1000 para tener un numero legible, lo que quieres decir que sera por 100000 habitantes return print (key, avg_cases) def avgyear(year, my_csv): """Esto es una función""" yearpop = {} for line in my_csv: myyear = str(line["year"]) pop = float(line["pop"]) if line["cases"] != "NA": cases =float(line["cases"]) yearpop[myyear] = yearpop.get(myyear, [0,0,0]) yearpop[myyear][0] = yearpop[myyear][0] + pop yearpop[myyear][1] = yearpop[myyear][1] + cases yearpop[myyear][2] = yearpop[myyear][2] + 1 for key in yearpop: if key == year: avg_cases = 100000*yearpop[key][2]/yearpop[key][1] return print (key, avg_cases) def avgweeks(weeks, my_csv): weekspop = {} for line in my_csv: myweeks = line["biweek"] pop = float(line["pop"]) if line["cases"] != "NA": cases =float(line["cases"]) weekspop[myweeks] = weekspop.get(myweeks, [0,0,0]) weekspop[myweeks][0] = weekspop[myweeks][0] + pop weekspop[myweeks][1] = weekspop[myweeks][1] + cases weekspop[myweeks][2] = weekspop[myweeks][2] + 1 for key in weekspop.keys(): if key == weeks: avg_cases = 100000*weekspop[key][2]/weekspop[key][1] return print (key, avg_cases)
'''class shifu(object): def __init__(self): self.hui = '煎饼果子配方' def zuo(self): print(f'我会用{self.hui}做煎饼果子') class tudi(shifu): pass aa = tudi() aa.zuo() ''' '''class shifu(object): def __init__(self): self.gongfu = '麻辣' self.__qian = 200 def make(self): print(f'我会用{self.gongfu}做,我有{self.qian}') def get_money(self): return self.__qian def set_money(self): self.__qian = 500 class tudi(shifu): pass a = tudi() print(a.get_money()) a.set_money() print(a.get_money())''' '''class Master(object): def __init__(self): self.kongfu = '[五香]' def make_cake(self): print(f'用{self.kongfu}做煎饼果子') class School(object): def __init__(self): self.kongfu = '[香辣]' def make_cake(self): print(f'用{self.kongfu}做煎饼果子') class Prentice(Master, School, ): def __init__(self): self.kongfu = '自己创造的麻辣' def make_cake(self): self.__init__() print(f'我会用{self.kongfu}做煎饼果子') def make_old_cake(self): super().__init__() super().make_cake() aa = Prentice() aa.make_cake() aa.make_old_cake()''' # class dog(): # def word(self): # print('指哪打哪') # class jdog(): # def word(self): # print('追击绑匪') # class ddog(): # def word(self): # print('追击毒贩') # class persen(): # def witha(self,dog): # dog.word() # a = jdog() # b = ddog() # c = dog() # d = persen() # d.witha(a) # d.witha(b) # d.witha(c) '''class dog(): gao = 10 b = dog() c = dog() print(b.gao) print(c.gao) dog.gao = 20 print(b.gao) print(c.gao)''' #2-http协议的组成,状态码含义; '''常见的200 请求成功,但是不一定功能成功, 300 重定向 404 页面不存在 端的问题 500 服务挂了 后端问题 ''' #3-完成手机app抓包 # 已完成,通过同一wifi下,手机设置代理ip信息,下载fiddler或者Charles连接进行抓包 #4-get和post区别 '''get: 不安全,会把用户输入的信息带到url,比如账号密码等私密信息。一般获取列表之类的接口使用get请求 post:安全,不会带用户输入的信息 一般提交用户输入信息的接口使用post请求 ''' #-cookie和session区别 ''' COOKIE: cookie的数据会保存在客户端,而且可以通过f12在cookie存在的容器去篡改cookie的数据 SESSION:session的数据不会保存在客户端而是服务器,如果考虑安全用session,但是性能不如cookie '''
euro = int(input("Diguem una quantitat d'euros\n")) print("el valor en pesetes es:",euro*166.3860)
from math import sqrt A = int(input("Nombre elevat a 2\n")) B = int(input("Nombre elevat a 1\n")) C = int(input("Terme independent\n")) if ((B**2)-4*A*C) < 0: print("La rael dona negativa") else: print("les solucions són") print((-B+sqrt(B**2-(4*A*C)))/(2*A)) print((-B-sqrt(B**2-(4*A*C)))/(2*A))
preu = int(input("Quin es el preu del producte?\n")) IVA = int(input("quin es el porcentatge de IVA?\n")) print("l'IVA són:", IVA/100*preu,"€") print("El preu total es:",IVA/100*preu+preu,"€")