text
stringlengths
37
1.41M
# Write a function that takes in two non-empty arrays of integers, finds the pair of # numbers (one from each array) whose absolute difference is closest to zero, and # returns an array containing these two numbers, with the number from the first array in # the first position. # Note that the absolute difference of two integers is the distance between them on the # real number line. For example, the absolute difference of -5 and 5 is 10, and the # absolute difference of -5 and -4 is 1. # You can assume that there will only be one pair of numbers with the smallest # difference. # Sample Input: # arrayOne :[-1, 5, 10, 20, 28, 3] # arrayTwo : [26, 134, 135, 15, 17] # Sample Output: # [28, 26] def smallestDifference(arrayOne, arrayTwo): # Write your code here. arrayOne.sort() arrayTwo.sort() idxOne = 0 idxTwo = 0 smallest = float("inf") current = float("inf") smallestPair = [] while idxOne < len(arrayOne) and idxTwo < len(arrayTwo): firstNum = arrayOne[idxOne] secondNum = arrayTwo[idxTwo] if firstNum < secondNum: current = secondNum - firstNum idxOne+=1 elif secondNum < firstNum: current = firstNum - secondNum idxTwo+=1 else: return([firstNum,secondNum]) if current < smallest: smallest = current smallestPair = [firstNum,secondNum] return(smallestPair)
# Given an array of positive integers representing coin denominations and a single non- # negative integer n representing a target amount of money, write a function that # returns the smallest number of coins needed to make change for (to sum up to) that # target amount using the given coin denominations. # Note that you have access to an unlimited amount of coins. In other words, if the # denominations are [1, 5, 10] , you have access to an unlimited amount of 1 s, # s, and 10 s. # If it's impossible to make change for the target amount, return -1 . # Sample Input: # n=7 # denoms = [1,5,10] # Sample Output: # 3(2*1 + 1*5) def minNumberOfCoinsForChange(n, denoms): # Write your code here. numOfCoins = [float("inf") for amount in range(n+1)] numOfCoins[0] = 0 for denom in denoms: for amount in range(len(numOfCoins)): if denom <=amount: numOfCoins[amount] = min(numOfCoins[amount],numOfCoins[amount-denom]+1) return numOfCoins[n] if numOfCoins[n] !=float("inf") else -1
# Sample Input : # array = [0, 1, 21, 33, 45, 45, 61, 71, 72, 73] # target = 33 # Sample Output: # 3 def binarySearch(array, target): # Write your code here. return binarySearchHelper(array,target,0,len(array)-1) def binarySearchHelper(array,target,left,right): if left >right: return -1 middle = (left + right)//2 tnumber = array[middle] if target < tnumber: return binarySearchHelper(array,target,left,middle-1) elif target > tnumber: return binarySearchHelper(array,target,middle+1,right) else: return middle
####note################################################### #return [i for i in data if data.count(i) > 1] ########################################################### #Your optional code here #You can import some modules or create additional functions def checkio(data): #Your code here #It's main function. Don't remove this function #It's used for auto-testing and must return a result for check. count = [data.count(data[i]) for i in range(len(data))] index = [i for i in range(len(count)) if count[i]==1] nai = 0 for i in index: data.pop(i -nai) nai += 1 #replace this for solution return data if __name__ == '__main__': d = checkio([1,2,3,4,5]) print(d)
def find_two(): with open('one.input', 'r') as f: data = f.readlines() data = [int(x) for x in data] for x in data: for y in data: if x + y == 2020: print(x*y) return print('Sum not found') def find_three(): with open('one.input', 'r') as f: data = f.readlines() data = [int(x) for x in data] for x in data: for y in data: for z in data: if x + y + z == 2020: print(x*y*z) if __name__ == "__main__": find_two() find_three()
# Quick sort 10000 random numbers between 0 and 10000 # Print the Initial list and final result only. import random from itertools import chain def quick_sort(dl): if len(dl) == 1: # One Number return dl all_same = True # All same numbers for i in range(len(dl)): if dl[0] != dl[i]: all_same = False break if all_same == True: return dl else: head_index_number = 0 tail_index_number = len(dl)-1 check_number = dl[0] temporary_number = 0 change = False while head_index_number < tail_index_number: while head_index_number < tail_index_number: if dl[head_index_number] >= check_number: temporary_number = dl[head_index_number] break else: head_index_number += 1 while head_index_number < tail_index_number: if dl[tail_index_number] < check_number: dl[head_index_number] = dl[tail_index_number] dl[tail_index_number] = temporary_number change = True break else: tail_index_number -= 1 c = 0 if change == False: c = 1 dl1 = dl[:head_index_number+c] dl2 = dl[head_index_number+c:] result = [quick_sort(dl1),quick_sort(dl2)] return flatten_by_extend(result) # https://www.lifewithpython.com/2014/01/python-flatten-nested-lists.html def flatten_by_extend(nested_list): flat_list = [] for e in nested_list: flat_list.extend(e) return flat_list if __name__ == "__main__": random_list = [0]*10000 i = 0 while i < len(random_list): random_list[i] = random.randint(0,10000) i += 1 print(random_list) print("Sorting...") print(quick_sort(random_list))
import abc class Feature(object): __metaclass__ = abc.ABCMeta """ class to wrap all the scripts/method to aggregate features from the database """ @abc.abstractmethod def createFeature(self,collectionName,param): """ Method to define how a feature/set of features is computed. param contains eventual parameters for querying database competion, subset of teams, whatever Best practice: features have to be stored into a collection of documents in the form: {_id: {match: (numeric) unique identifier of the match, name: (string) name of the feature, entity: (string) name of the entity target of the aggregation. It could be teamId, playerID, teamID + role or whatever significant for an aggregation}, value: (numeric) the count for the feature} return the name of the collection where the features have been stored """ return class Aggregation(object): __metaclass__ = abc.ABCMeta """ defines the methods to aggregate one/more collection of features for each match it have to provide results as a dataframe, e.g. it is used to compute relative feature for each match match -> team (or entity) -> featureTeam - featureOppositor """ @abc.abstractproperty def get_features(self): return 'Should never get here' @abc.abstractproperty def set_features(self, collection_list): """ set the list of collection to use for relative features computing e.g. we could have a collection of quality features, one for quantity features, one for goals scored etc """ return @abc.abstractmethod def aggregate(self): """ merge the collections of feature and aggregate by match and team, computing the relative value for each team e.g. match -> team (or entity) -> featureTeam - featureOppositor returns a dataframe """ return
def readfiles(fnames): for i in fnames: f = open(i, 'r') for line in f: yield line def grep(pattern, lines): a = [] for line in lines: if pattern in line: a.append(line) return a def printlines(lines): for line in lines: print line def main(pattern, fnames): lines = readfiles(fnames) answr = grep(pattern, lines) printlines(answr) main('ok', ['data.txt', 'data2.txt', 'data3.txt','data4.txt','data5.txt'])
""" Program to list all the files in the given directory along with their length and last modification time.""" import os path = input("Enter the path of the file to be listed, enclosed in double quotes.\n") dirs = os.listdir(path) for i in dirs: path_n = path + "/%s" %(i) s = os.stat(path) print i + "\t" + str(s.st_size) + "\t" + str(s.st_mtime)
#!/usr/bin/env python3 import json import math import operator import argparse import numpy as np import pandas as pd import vocab import preprocessing import plot class TFIDF(): def __init__(self, documents, vocab): """ Term Frequency - Inverse Document Frequency Class It takes a set of documents and a vocabulary to compute TF and IDF. When initialize, it generates the TFIDF score per each word per each document stored in tfidf_documents variable. It is also able to process a document query and evaluate document comparisons: - matching score - cosine similarity """ self.documents = documents self.vocab = vocab self.N = len(documents) self.tf_documents = {doc: self.compute_tf(documents[doc]) for doc in self.documents} # tf_documents is a dictionary to store each word's tf value per document. # tf_documents['doc']['word'] = tf_score self.idf = self.compute_idf() # idf is a dictionary to store each word's idf value. # as opposed to tf, idf is a unique value per word across the corpus. # idf['word'] = idf_score self.tfidf_documents = {doc: self.compute_tfidf(self.tf_documents[doc], self.idf) for doc in self.documents} # tfidf is the tf_score multiplied by idf_score per each word per each document # tfidf['doc']['word'] = tfidf_score #self.print() self.documents_vectors = {doc: self.vectorize_tfidf(self.tfidf_documents[doc]) for doc in self.tfidf_documents} # in order to achieve cosine similarity, tfidf must be vectors # documents_vectors['doc']['vector'] def frequency(self, term, document): """ returns the normalized frequency of term t in document d """ freq = document.count(term) freq_normalized = freq / len(document) return freq_normalized def frequency_N(self, term): """ returns the number of documents that term t occurs in """ freq = 0 for doc in self.documents: if term in self.documents[doc]: freq += 1 return freq def compute_tf(self, document): """ function that computes the term frequency for all vocabulary: the amount of times that term t occurs in document d normalized by the total amount of occurrences in document d """ tf = {voc: self.frequency(voc, document) for voc in self.vocab} return tf def compute_idf(self): """ function that computes the inverse document frequency: total amount of documents d divided by the number of documents d in which the term t occurs """ idf = {} for voc in self.vocab: # added 1 to numerator to avoid negative values # added 1 to denominator to avoid division by 0 if term t is not in any document df = self.frequency_N(voc) idf_score = math.log((self.N + 1) / (df + 1)) # if term t appears in all documents: log(N/N) --> log(1) --> idf = 0.0 # smoothing idf score to avoid multiplication by 0 if idf_score == 0.0: idf_score = 0.0000001 idf[voc] = idf_score return idf def compute_tfidf(self, tf, idf): """ function that computes tf-idf score: tf is passed as a dictionary with tf values per word in vocabulary for a specific document. idf is a dictionary with idf values per word in vocabulary. """ tfidf_score = {voc: tf[voc] * idf[voc] for voc in self.vocab} return tfidf_score def query2tfidf(self, query): """ function that computes tf-idf for query input: query preprocessed output: tfidf for query """ tf = self.compute_tf(query) idf = self.compute_idf() tfidf_query = self.compute_tfidf(tf, idf) return tfidf_query def matching_score(self, query): """ function that matches query to all documents and assigns a score for each. the score is calculated regarding the tfidf value per word in the document input: tfidf for each document and query preprocessed output: a dictionary with ordered results by their matching score """ matching_score = {doc: 0 for doc in self.tfidf_documents} for term in query: for doc in self.tfidf_documents: if term in self.tfidf_documents[doc]: matching_score[doc] += self.tfidf_documents[doc][term] best_k = self.rank_scores(matching_score) return best_k def rank_scores(self, scores, n=-1): """ function that ranks (descending order) score results input: scores is a dictionary, n is the amount of results to retrieve output: ranked scores dictionary with a max lenght of n if n == -1, then all results are retrieved """ if n == -1: n = len(scores) ranked_scores = {k: v for k, v in sorted(scores.items(), key=operator.itemgetter(1), reverse=True)[:n]} return ranked_scores def vectorize_tfidf(self, tfidf): """ function that converts the tfidf dictionary to vector space (numpy array) each word's value is stored in its index position """ vector = np.zeros(len(self.vocab)) for voc in self.vocab: index = self.vocab.index(voc) vector[index] = tfidf[voc] return vector def compute_cosine_similarity_matrix(self): """ function that computes cosine similarity between all documents. returns a dataframe with cosine values. """ matrix = {doc: self.compute_cosine_similarity(self.documents_vectors[doc]) for doc in self.documents_vectors} matrix = pd.DataFrame.from_dict(matrix, orient='index') indexes = matrix.index.tolist() matrix = matrix.reindex(columns=indexes) return matrix def compute_cosine_similarity(self, query_vector): """ function that computes cosine similarity between documents and given query vector. returns ranked cosine similarity values stored in a dictionary. """ cosine_similarities = {doc: self.cosine_similarity(self.documents_vectors[doc], query_vector) for doc in self.documents_vectors} ranked_cosine_similarities = self.rank_scores(cosine_similarities) return ranked_cosine_similarities def cosine_similarity(self, v1, v2): """ function that computes the cosine similarity between two vectors """ cos_sim = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)) return cos_sim def print_tfidf(self): """ function that nicely prints tfidf scores """ for doc in self.tfidf_documents: print(doc) for voc in self.tfidf_documents[doc]: print('\t',voc, self.tfidf_documents[doc][voc]) def print_scores(self, scores, n=-1): """ function that nicely prints scores """ if n == -1: n = len(scores) for i, (k, v) in enumerate(scores.items()): print(k, '\t', v) if i == n-1: break def higher_terms(self, n=10): ranked_scores = {doc: self.rank_scores(self.tfidf_documents[doc], n) for doc in self.tfidf_documents} return ranked_scores if __name__ == '__main__': parser = argparse.ArgumentParser(description='...') parser.add_argument('-t', '--test', action='store_true', default=False) parser.add_argument('-c', '--cosine', action='store_true', default=False) parser.add_argument('-m', '--matching', action='store_true', default=False) parser.add_argument('-s', '--scores', action='store_true', default=False) parser.add_argument('-q', '--query', action='store', default=False) args = parser.parse_args() if args.test: documents = {'1':['hola','cómo','estás'], '2':['hola', 'y','tu', 'yo'], '3':['bien', 'cómo', 'estás']} query = 'hola cómo estás? yo' print(documents) print(query) else: with open('text_processed.json', 'r') as openfile: # loading created json file book = json.load(openfile) documents = book['book_lemmas'] query = ' '.join(['pedir', 'su', 'desayuno', 'temprano', 'pagar', 'su', 'cuenta', 'y', 'él', 'marchar', 'este', 'ser', 'todo', 'el', 'historia', 'uno', 'momento', 'de', 'silencio', 'y', 'no', 'él', 'ver', 'más', 'preguntar', 'dos', 'o', 'tres', 'voz', 'a', 'uno', 'tiempo', 'nunca', 'más', 'él', 'sentir', 'varios', 'puñetazo', 'sobre', 'el', 'mesa']) vocab_info = vocab.generate_vocab(documents) # vocab_info = tuple with types, total number of types, and total number of tokens vocab = list(vocab_info[0]) tfidf = TFIDF(documents, vocab) if args.query: # input: query as a string (i.e. 'this is a query') query_preprocessed = preprocessing.preprocess_query(args.query) # comparison metrics: if args.matching: # 1) matching score matching_score = tfidf.matching_score(query_preprocessed) tfidf.print_scores(matching_score, n=3) if args.cosine: # 2) cosine similarity # it requires query in vector space query_tfidf = tfidf.query2tfidf(query_preprocessed) query_vector = tfidf.vectorize_tfidf(query_tfidf) cosine_similarities = tfidf.compute_cosine_similarity(query_vector) tfidf.print_scores(cosine_similarities) # plotting cosine similarity between documents cosine_similarity_matrix = tfidf.compute_cosine_similarity_matrix() plot.plot_heatmap(cosine_similarity_matrix) if args.scores: terms = tfidf.higher_terms() for doc in terms: print(doc) tfidf.print_scores(terms[doc])
# -*- coding: utf-8 -*- import itertools import os import matplotlib as mpl mpl.use('Agg') from matplotlib import pyplot as plt import numpy as np import pandas as pd from sklearn.feature_selection import VarianceThreshold from sklearn.preprocessing import normalize from sklearn.decomposition import PCA from utils.config_utils import Config def principal_component_analysis(x_train): """ Principal Component Analysis (PCA) identifies the combination of attributes (principal components, or directions in the feature space) that account for the most variance in the data. Let's calculate the 2 first principal components of the training data, and then create a scatter plot visualizing the training data examples projected on the calculated components. """ # Extract the variable to be predicted y_train = x_train["TARGET"] x_train = x_train.drop(labels="TARGET", axis=1) classes = np.sort(np.unique(y_train)) labels = ["Satisfied customer", "Unsatisfied customer"] # Normalize each feature to unit norm (vector length) x_train_normalized = normalize(x_train, axis=0) # Run PCA pca = PCA(n_components=2) x_train_projected = pca.fit_transform(x_train_normalized) # Visualize fig = plt.figure(figsize=(10, 7)) ax = fig.add_subplot(1, 1, 1) colors = [(0.0, 0.63, 0.69), 'black'] markers = ["o", "D"] for class_ix, marker, color, label in zip( classes, markers, colors, labels): ax.scatter(x_train_projected[np.where(y_train == class_ix), 0], x_train_projected[np.where(y_train == class_ix), 1], marker=marker, color=color, edgecolor='whitesmoke', linewidth='1', alpha=0.9, label=label) ax.legend(loc='best') plt.title( "Scatter plot of the training data examples projected on the " "2 first principal components") plt.xlabel("Principal axis 1 - Explains %.1f %% of the variance" % ( pca.explained_variance_ratio_[0] * 100.0)) plt.ylabel("Principal axis 2 - Explains %.1f %% of the variance" % ( pca.explained_variance_ratio_[1] * 100.0)) #plt.show() #plt.savefig("../data/pca.pdf", format='pdf') #plt.savefig("../data/pca.png", format='png') plt.savefig(os.path.join(Config.get_string('data.path'), 'graph', 'pca.png'), format='png') plt.close() def remove_feat_constants(data_frame): # Remove feature vectors containing one unique value, # because such features do not have predictive value. print("") print("Deleting zero variance features...") # Let's get the zero variance features by fitting VarianceThreshold # selector to the data, but let's not transform the data with # the selector because it will also transform our Pandas data frame into # NumPy array and we would like to keep the Pandas data frame. Therefore, # let's delete the zero variance features manually. n_features_originally = data_frame.shape[1] selector = VarianceThreshold() selector.fit(data_frame) # Get the indices of zero variance feats feat_ix_keep = selector.get_support(indices=True) orig_feat_ix = np.arange(data_frame.columns.size) feat_ix_delete = np.delete(orig_feat_ix, feat_ix_keep) # Delete zero variance feats from the original pandas data frame data_frame = data_frame.drop(labels=data_frame.columns[feat_ix_delete], axis=1) # Print info n_features_deleted = feat_ix_delete.size print(" - Deleted %s / %s features (~= %.1f %%)" % ( n_features_deleted, n_features_originally, 100.0 * (np.float(n_features_deleted) / n_features_originally))) return data_frame def remove_feat_identicals(data_frame): # Find feature vectors having the same values in the same order and # remove all but one of those redundant features. print("") print("Deleting identical features...") n_features_originally = data_frame.shape[1] # Find the names of identical features by going through all the # combinations of features (each pair is compared only once). feat_names_delete = [] for feat_1, feat_2 in itertools.combinations( iterable=data_frame.columns, r=2): if np.array_equal(data_frame[feat_1], data_frame[feat_2]): feat_names_delete.append(feat_2) feat_names_delete = np.unique(feat_names_delete) # Delete the identical features data_frame = data_frame.drop(labels=feat_names_delete, axis=1) n_features_deleted = len(feat_names_delete) print(" - Deleted %s / %s features (~= %.1f %%)" % ( n_features_deleted, n_features_originally, 100.0 * (np.float(n_features_deleted) / n_features_originally))) return data_frame if __name__ == "__main__": train_data_path = os.path.join(Config.get_string('data.path'), 'input', 'train.csv') x_train = pd.read_csv(filepath_or_buffer=train_data_path, index_col=0, sep=',') x_train = remove_feat_constants(x_train) x_train = remove_feat_identicals(x_train) principal_component_analysis(x_train)
import math def list(a, x): smallest = math.inf largest = 0 five = [] other = [] for i in range(len(a)): if a[i] < smallest: smallest = a[i] elif a[i] > largest: largest = a[i] print('Smallest: ', smallest) print('Largest: ', largest) for i in range(len(a)): if a[i]%5 ==0: five.append(a[i]) if a[i]%x ==0: other.append(a[i]) print('Divide by 5: ', five) print('Divide by', x, ': ', other)
''''lista_telefonica = [('Rafael', '11-9-7072.3887'), ('Fernanda', '11-9999.000'), ("Gustavo", '11-8888.0000'), ('Vicente', '11-7777.8888'), ('Luzia', '1111.2222')] print (lista_telefonica) print (lista_telefonica[0]) print (lista_telefonica[0][0]) contatos = dict (lista_telefonica) nome = input("Digite um nome: ") print (contatos.get(nome, "O nome não foi encontrado!"))''' vingadores = {'Chris Evans':'Capitão America', 'Mark Ruffalo':'Hulk', 'Tom Hiddleston': 'Loki', 'Chris Hemworth': 'Thor', 'Robert Downey Jr': 'Homem de Ferro', 'Scarlett Johansson':' Viúva Negra'} personagens = input ("Digite o nome de um personagem: ") print (vingadores.get (personagens, "O nome não foi encontrado!")) vingadores ["Jason"] = "Terror das águas" vingadores ["Freddie"] = "Mestre dos Pesadelos!" vingadores ["O mascara"] = "Arrasando corações" vingadores ["Viuva Negra"] = "invencivel" vingadores ["Rafael"] = "Eu" #Deletando Valores del vingadores ["Rafael"] print (vingadores) excluido_pop = vingadores.pop('Mark Ruffalo', 'nome não encontrado') print (excluido_pop) excluidospop = vingadores.popitem() print (excluidospop)
##5. Faça um programa que calcule através de uma função o IMC de uma pessoa que tenha 1,68 e pese 75kg. '''def IMC(altura,peso): imc_calculado = peso /(altura ** 2) if imc_calculado < 18.5: print("Magreza") elif imc_calculado >= 18.5 and imc_calculado < 24.9: print("Normal") elif imc_calculado >= 24.9 and imc_calculado <= 30: print("Sobrepeso") else: print("Obesidade") str_altura = float((((input("Digite sua altura em metros: ").replace(',','.')).lower()).replace('m',' ')).strip()) str_peso = float((((input("Digite seu peso: ").replace(',','.')).lower()).replace('kg',' ')).strip()) IMC(str_altura,str_peso) print("Resultado: ") IMC(1.68,75)'''
'''Exercício 1 1. Dada a lista L = [5, 7, 2, 9, 4, 1, 3], escreva um programa que imprima as seguintes informações: a. tamanho da lista. b. maior valor da lista. c. menor valor da lista. d. soma de todos os elementos da lista. e. lista em ordem crescente. f. lista em ordem decrescente.''' '''listaL = [5, 7, 2, 9, 4, 1, 3] tamanho = len(listaL) maior = max(listaL) menor = min(listaL) soma = sum(listaL) listaL.sort() print("Tamanho da lista: ", tamanho, "O maior número da lista é: ", maior, "O menor número da lista é: ", menor, "A soma dos elementos da lista é: ", soma, "Lista na ordem crescente: "), print("lista em ordem crescente: ", listaL) listaL.reverse() print ("lista em ordem decrescente: ", listaL)'''
## 6.Escreva uma função que, dado um número nota representando a nota de um estudante, converte o valor de nota para um conceito (A, B, C, D, E e F). ''' def nota_aluno(): notaluno = float(input("Digite a nota do aluno: ")) if notaluno <= 5.9: print ("nota F") elif notaluno >=6.0 and notaluno <=6.9: rint ("nota D") elif notaluno >=7.0 and notaluno <8.0: print ("nota C") elif notaluno >=8.0 and notaluno <9.0: print ("nota B") elif notaluno >= 9.0 and notaluno <=10: print ("Parabéns!!! nota A") else: print ("valor inválido") nota_aluno()'''
#https://wiki.python.org.br/EstruturaSequencial from number import Number num = Number() metros = input("Informe um valor em metros ") if num.isnumber(metros): print(metros + " metro(s) são " + str(int(metros) * 60) + " centímetros") else: print("Você não informou um número válido!")
# Task 1.1 replace " ' def replace (stroka): print (stroka) i = 0 strokanew = "" while i < len(stroka): if stroka[i] == "'": strokanew = strokanew + '"' elif stroka[i] == '"': strokanew = strokanew + "'" else: strokanew = strokanew + stroka[i] i=i+1 return (strokanew) print ("\n Task 1.1 replace") print (replace("df'dsf''fds")) print (replace('df"sf""fds')) # Task 1.2 palindrome def palindrome (word): palindrome = "Yes its palindrome!" wordl = len(word) print (word) i=0 while i < len(word)//2+1: if word[i] != word[-(i+1)]: palindrome = "Not palindrome" # print (i," ",word[i]," ",word[-(i+1)]) i = i+1 return (palindrome) print ("\n Task 1.2 palindrome") print (palindrome('asdfgfdsa')) print (palindrome('asdfggfdsa')) print (palindrome('asdfgfsa')) # Task 1.3 split def split(stroka, razdelitel): print (stroka,'"',razdelitel,'"') spisok = [] j=1 slovo="" for i in stroka: # print (i,j,slovo,spisok) if i != razdelitel: slovo=slovo+i elif slovo != "": spisok.insert(j,slovo) j=j+1 slovo="" if slovo != "": spisok.insert(j+1,slovo) return spisok print ("\n Task 1.3 split") print (split("python is cool,isnt'it?"," ")) print (split("python, is cool,isnt'it?,",",")) # Task 1.4 split by index index=[] def splitindex (stroka, index): spisok=[] slovo="" print(stroka, index) j=0 i=0 while i < len(stroka): # print (i,stroka[i],slovo) slovo=slovo+stroka[i] if i+1 == index[j]: spisok.insert(j,slovo) # print("index",index[j],spisok) slovo="" if j+1 < len(index): j=j+1 i=i+1 if slovo !="": spisok.insert(j+1,slovo) return spisok print ("\n Task 1.4 split by index") print (splitindex("12345678901234567",[4,6,10,15])) print (splitindex("pythoniscool",[6,8])) # Task 1.5 number to tuple int def number2tuple (num): print (num) spisok = list(str(num)) i=0 while i < len(spisok): spisok[i]=int(spisok[i]) # print(i, spisok[i]) i=i+1 tup=tuple(spisok) return tup print ("\n Task 1.5 number to tuple") print (number2tuple(2643376)) # Task 1.6 longest word def getlongest (stroka): print (stroka) longest="" slovo="" for i in stroka+" ": slovo = slovo + i # print (slovo, "==",longest) if i == " ": # print (slovo) if len(slovo)>len(longest): longest = slovo slovo = "" return (longest) print ("\n Task 1.6 get longest word") print (getlongest("why Python vis simple and effectiv")) print (getlongest("why Python is s!imple and effective!!!")) # Task 1.7 product of array exept i def foo (spisok): product=1 print (spisok) for i in spisok: product=product*i i=0 while i<len(spisok): spisok[i]=int(product/spisok[i]) i=i+1 return spisok print ("\n Task 1.7 product of array exept i") print (foo([1,2,3,4,5])) print (foo([3,2,1])) # Task 1.8 def get_pairs (onelist): i=0 pairs=[] while i < len(onelist)-1: pairs.insert(i,(onelist[i],onelist[i+1])) i=i+1 # print (pairs) return (pairs) print ("\n Task 1.8 pairs") stroka=(1,2,3,4,5,6,7,8) print (stroka) print (get_pairs(stroka))
def reverse(str): res = "" for c in str: res = c + res return res s = input() print(reverse(s))
#################################################### #################################################### ############# Welcome to lesson 1 ################## ############## Python 3.3 ################# #################################################### #################################################### # You may at this point have noticed loads of hash signs - # - and are wondering why? # Well, the hash sign # is used as a starter sign for a line where you'll place a comment to your code. # What ever comes after the # is not read as a code, but merely as what it is: # A note, message or explanation to the code. print ("Be carefull not to write too long lines. Try to keep the length of your lines below 80 carracters.") # This is a comment. Text in comments have a different color as do statements like print. print ("Comments can be added at the end of a line to explain the code.") print () print ('kelvin = celcius * 273.14 # Inserts the degrees in celcius.') print () print ("You can also print multiple lines with only one print statement.") print ('To do this you must enclose the text with 3 """double quotes at the beginning and 3 """double quotes at the end of the text.') print ("""This text is printed on several lines. Here we used 3 double quotes in the beginning and end of the text. Note that the line shift comes automaticly.""") print ('''Naturally you can also use the single quotes to print long text to the console window. And single quotes obey the same rules as double quotes. By using single quotes you can include the double quotes in the text. "He said hello to the world."''') print () print ("""Often you have to make longer comments to your code. To avoid filling your code with the hash sign you simply enclose the comment with 3 '''single quotes at the beginning and end of the comment.''' This allows you to write multiple lines of comments to you code""") print () ''' Here I've made my own comment to my code. I preferr to start the line comment with the 3 single quotes and then make a line shift like I've done here. I also place the last 3 single quotes on a separate line. This makes it much easier to spot longer comments. Remember, that you can't make enough comments to your code. In the long term it ease up the understanding of your code, especially when you after a while returns to review the code.''' """Naturally you can use # " at the beginning and 3 " at the end of longer comments. """ print () print ("I'll in a later file introduce you to more advances use of the 'print' statement.") print () print ("So off to the next lesson. Se lesson_2.py.")
import math # print (1) # ceil()向上取整 ''' help(math) print(math.ceil(5.1) ) # floor()向下取整 # print(math.floor(5.9)) # 查看系统关键字 不能用来当做变量名 import keyword print (keyword.kwlist) # 四舍五入 python 内置函数 print(round(5.3)) print(round(5.5)) # sqrt()开平方 返回浮点数 print(math.sqrt(9)) # sin 正弦 # pwd()与幂运算差不多,计算一个数的几次方,有两个参数,第一个是底数,第二个是指数 print(math.pow(4,3)) # 4 的 3 次方 返回浮点型 print(4**3) #返回整形 # fabs()对一个数取绝对值 返回浮点数 print(math.fabs(-1)) # abs()获取绝对值 不是数学模块的 是Python内置函数 print(abs(-1)) # fsum() 对整个序列求和 返回浮点数 # sum()Python内置求和 返回看给的类型 # math.modf()将一个浮点数拆分为小数部分跟整数部分 组成元祖 print(math.modf(4.5)) print(math.modf(0)) print(math.modf(3)) # copysign() 将第二个数的符号(正负号)传给第一个数 返回第一个数的浮点数 print(math.copysign(2,-3)) print(math.copysign(-2,3)) print(math.e) print(math.pi) ''' import random # # random() 获取0-1之间的随机小数 包含0 不包含1 # for i in range(10): ''' # range可迭代 用for # print (random.random()) # 随机指定开始和结束之间的整数值 # print(random.randint(1,6)) # random.randrange()获取指定开始和结束之间的值,可以指定间隔值 # print(random.randrange(1,9,2)) ''' # choice() 随机获取列表的值 # print(random.choice([10,24,4,15])) # shuffle() 随机打乱序列,返回值是none ''' list1 = ([10,24,4,15]) print(list1) print(random.shuffle(list1)) print(list1) ''' # uniform() 随机获取指定范围内的值(包括小数) for n in range(10): print(random.uniform(1,9))
# 피보나치 함수(Fibonacci Function)을 재귀함수로 구현 def fibo(x): if x == 1 or x == 2: return 1 return fibo(x-1) + fibo(x-2) print(fibo(4)) # 피보나치 수열 : 탑다운 # 한 번 계산된 결과를 메모이제이션하기 위한 리스트 초기화 d = [0] * 100 def fibo_topdown(x): if x == 1 or x == 2: return 1 if d[x] != 0: return d[x] d[x] = fibo_topdown(x-1) + fibo_topdown(x-2) return d[x] print(fibo(99)) # 피보나치 수열 : 보텀업 # 앞서 계산된 결과를 저장하기 위한 DP 테이블 초기화 d2 = [0] * 100 d2[1] = 1 d2[2] = 1 n = 99 for i in range(n+1): d2[i] = d2[i-1] + d2[i-2] print(d[n])
# 배열 문법 공부하자 # 1) 1차원 배열 arr1 = [0, 0, 0, 0, 0] print(arr1) arr2 = [0] * 5 print(arr2) arr2[0] = 1 print(arr2) # 2) 2차원 배열 arr3 = [[0]*5 for _ in range(5)] print(arr3) arr3[0][1] = 1 print(arr3)
def calculate_exponent(base,exponent): return base**exponent print("Please enter the base") base = int(input()) print("Please enter the exponent") exponent = int(input()) calculate_exponent(base,exponent)
op = int(input("""Enter an operation (1) for addition (2) for multiplication""")) a = int(input("Enter the first value")) b = int(input("Enter the second value")) if (op == 1): print("a + b = ",a+b) elif (op == 2): print("a*b = ", a*b) else: print("Wrong option!")
# 모델링할 경우 lstm을 2~3개 이상 사용하면 효율이 저하 될수 있음 # return sequence는 2개이상의 lstm을 사용할 경우 사용함. # lstm에서 output shape의 dimension을 하나 늘려주기 위해 return_sequences=True 옵션을 사용한다. from numpy import array from keras.models import Sequential from keras.layers import Dense, LSTM #1. 데이터 x = array([[1,2,3], [2,3,4], [3,4,5], [4,5,6], [5,6,7], [6,7,8], [7,8,9],[8,9,10], [9,10,11], [10,11,12], [20,30,40], [30,40,50], [40,50,60]]) y = array([4,5,6,7,8,9,10,11,12,13,50,60,70]) x = x.reshape((x.shape[0], x.shape[1], 1)) # (10,3) -> (10,3,1) #2. 모델구성 model = Sequential() model.add(LSTM(100, activation='relu', input_shape=(3,1), return_sequences=True)) # lstm 에서 output shape의 dimension을 하나 늘려주기 위해 return_sequences=True 옵션을 사용한다. model.add(LSTM(200, activation='relu', return_sequences=True)) model.add(LSTM(300, activation='relu', return_sequences=True)) model.add(LSTM(400, activation='relu', return_sequences=True)) model.add(LSTM(10)) model.add(Dense(1000)) model.add(Dense(500)) model.add(Dense(50)) model.add(Dense(1)) model.summary() #3. 실행 model.compile(optimizer='adam', loss='mse') from keras.callbacks import EarlyStopping early_stopping = EarlyStopping(monitor='loss', patience=100, mode='auto') # model.fit(x, y, epochs=100, verbose=0) model.fit(x, y, epochs=10000, callbacks=[early_stopping]) # https://tykimos.github.io/2017/07/09/Early_Stopping/ x_input = array([25,35,45]) x_input = x_input.reshape((1,3,1)) yhat = model.predict(x_input) print(yhat) # _________________________________________________________________ # Layer (type) Output Shape Param # # ================================================================= # lstm_1 (LSTM) (None, 3, 100) 40800 # lstm에서 output shape의 dimension을 하나 늘려주기 위해 return_sequences=True 옵션을 사용한다. # _________________________________________________________________ # lstm_2 (LSTM) (None, 3, 200) 240800 # _________________________________________________________________ # lstm_3 (LSTM) (None, 3, 300) 601200 # _________________________________________________________________ # lstm_4 (LSTM) (None, 3, 400) 1121600 # _________________________________________________________________ # lstm_5 (LSTM) (None, 10) 16440 # _________________________________________________________________ # dense_1 (Dense) (None, 1000) 11000 # _________________________________________________________________ # dense_2 (Dense) (None, 500) 500500 # _________________________________________________________________ # dense_3 (Dense) (None, 50) 25050 # _________________________________________________________________ # dense_4 (Dense) (None, 1) 51 # ================================================================= # hobby : data pre-processing # speciality : hyper parameter tunning # http://physics2.mju.ac.kr/juhapruwp/?p=1517 ANN, DNN, CNN, LSTM, RNN, GRUs
#searches through a text file with entries of the form name, phone number, address #each line represent one person, uses regex to extract data import re #regexp import sys #for command line arguments if len(sys.argv) < 2 : print("Error, no file given") else: filename = sys.argv[1] #the first argument is actually address_book.py names=[] phone_numbers=[] address=[] with open(filename, "r") as textfile: for line in textfile: match = re.search('^([^\d]+)\s(\d+)\s([\w\s,]+)$', line) #this regex captures all three properties names.append( match.group(1) ) phone_numbers.append( match.group(2) ) address.append( match.group(3)) print( names ) print( phone_numbers ) print( address )
"""Level 2""" def answer(codes): """Find number of distinct access codes in a list of possibilities. Two codes are equivalent if they are the same or reverses of one another. Two codes which are not equivalent are distinct. For example, 'abc' is equivalent to 'abc' and 'cba', but not to 'bca'. The empty string counts as a code. Args: codes (list(str)): List of possible access codes. Each code is a string containing only letters a-z, all lower case. Lenth of this list is never longer than 5000 codes. Each code has at most 10 characters. Returns (int): number of distinct codes. """ s = set() num_distinct_codes = 0 for code in codes: if code in s: continue elif is_palindrome(code): s.add(code) else: s.add(code) s.add(code[::-1]) num_distinct_codes += 1 return num_distinct_codes def is_palindrome(code): if code == code[::-1]: return True else: return False
bits=[1,1,0] class Solution: def isOneBitCharacter(self, bits): i = 0 while i < len(bits): if bits[i]==0: if i == len(bits)-1: return True i += 1 if bits[i]==1: if i == len(bits)-2: return False i += 2 x=Solution() print(x.isOneBitCharacter(bits))
#inputString = "abcabcbb" # the answer is "abc", which the length is 3. #inputString = "au" # the answer is "b", with the length of 1. inputString = "pwwkew" # the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. class Solution: def lengthOfLongestSubstring(self, s): bank = {} pointer = 0 maxValue = 0 for index,value in enumerate(s): if value in bank: pointer = max(pointer,bank[value]+1) maxValue = max(maxValue,index-pointer+1) bank[value]=index return maxValue so = Solution() x = so.lengthOfLongestSubstring(inputString) print(x)
class Solution: def setZeroes(self, matrix): zeroXIndex = {} zeroYIndex = {} for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 0: zeroXIndex[i] = 1 zeroYIndex[j] = 1 for i in range(len(matrix)): for y in zeroYIndex: matrix[i][y] = 0 for x in zeroXIndex: for j in range(len(matrix[0])): matrix[x][j] = 0 return matrix """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ so = Solution() print(so.setZeroes([ [0,1,2,0], [3,4,5,2], [1,3,1,5] ]))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ arry = [] self.travel(root,0,arry) return (arry) def travel(self,root,level,array): if root: print(root.val,level) #check level array exist or not try: array[level] except: array.append([]) array[level].append(root.val) self.travel(root.left,level+1,array) self.travel(root.right, level+1,array)
#retorna uma string sem espaços e com a primeira letra de cada palavra maiuscula def split_string(string): strArray = string.split() newString = '' for str in strArray: newString += str.title() return newString
my_variable=10 my-boolan=True #布尔值首字母大写,后面不用打分号 print my_boolean def spam(): #一个函数 eggs = 12 #需要空4格 return eggs # return print spam() #返回12 """ 三个双引号就苏多行注释 """ eight = 2 ** 3 # 2的3次方 'he'\s'#\代表 name='ly'[1] print name #y print len(name) #2 print name.lower() #ly print name.upper() #LY print str(name) #'ly' name='ly12' name.isalpha() #检查是否只含了字母 """ string_1 = "Camelot" string_2 = "place" print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2) #用%替换后面的变量 name = raw_input("What is your name?") quest = raw_input("What is your quest?") color = raw_input("What is your favorite color?") print "Ah, so your name is %s, your quest is %s, " \ "and your favorite color is %s." % (name, quest, color) """ """ from datetime import datetime now=datetime.now() print now #获取当前时间 print now.day #now.month now.year print '%s/%s/%s' % (now.year, now.month, now.day) #2016/9/10 """ """ def clinic(): print "You've just entered the clinic!" print "Do you take the door on the left or the right?" answer = raw_input("Type left or right and hit 'Enter'.").lower() #提问 if answer == "left" or answer == "l": #判断语句 print "This is the Verbal Abuse Room, you heap of parrot droppings!" elif answer == "right" or answer == "r": print "Of course this is the Argument Room, I've told you that already!" else: print "You didn't pick left or right! Try again." #打印 clinic() clinic() #调用函数 """ """ from module import function # 导入方法,moudle,function """ """ for item in prices: print item print "price: %s" % prices[item] print "stock: %s" % stock[item] #遍历数组,%s被%后面的数值替代 """
def tower_builder(n_floors): # build here myList = [] for i in range(1, n_floors + 1): if (i == 1): myList.append((' ' * (n_floors - 1)) + '*' + (' ' * (n_floors - 1))) elif (i < n_floors): myList.append( (' ' * (n_floors - i)) + ('*' * ((i * 2)-1)) + (' ' * (n_floors - i))) else: myList.append('*' * ((i * 2)-1)) return myList
import pygame import random import solver from eval_expression import * """ CREDITS: Pygame basics and image loading: https://youtu.be/UdsNBIzsmlI Pygame mouse interactions: https://youtu.be/vhNiwvUv4Jw Pygame image scaling: https://www.pygame.org/docs/ref/transform.html Pygame font usage: https://www.pygame.org/docs/ref/font.html#pygame.font.Font Application icon and math operations: https://en.wikipedia.org/wiki/Operation_(mathematics) These sources were used as an intro to how to interact with pygame and the different aspects of it. Actual implementation (like drag and drop to snap to a red rectangle) was done by us """ pygame.init() WINDOW_HEIGHT = 500 WINDOW_WIDTH = 500 GAME_SCREEN = 'main' VICTORY_SCREEN = 'victory' screen = 'main' font = pygame.font.Font('freesansbold.ttf', 32) font2 = pygame.font.Font('freesansbold.ttf', 50) check = font2.render("Check", True, (255, 255, 255), (0, 0, 0)) green = (0, 255, 0) blue = (0, 0, 128) pale = (255, 255, 153) win = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) icon = pygame.image.load("images/Basic_arithmetic_operators.png") pygame.display.set_caption("Operation Guesser") pygame.display.set_icon(icon) plus = pygame.image.load("images/plus_sign.png") times = pygame.image.load("images/multiplication_sign.png") divide = pygame.image.load("images/division_sign.png") plus = pygame.transform.scale(plus, (30, 30)) minus = 0 mult = pygame.transform.scale(times, (30, 30)) divide = pygame.transform.scale(divide, (30, 30)) test_string = "(2 + 3) + 86 + 17 / 5 = 1" omited_string = "" final_string = "" eq = "Impossible" while eq == "Impossible": numbers = [random.randint(0, 9) for i in range(4)] numbers = tuple(numbers) result = random.randint(0, 50) solve = solver.OperationGuess() eq = solve.solve(numbers, result) eq += ' = {}'.format(result) num_spaces = len(eq) equation_display = [] for i in range(num_spaces): if eq[i] == "+" or eq[i] == "-" or eq[ i] == "/" or eq[i] == "*": equation_display.append(((20 + i * (WINDOW_WIDTH - 50) / num_spaces), WINDOW_HEIGHT * 0.30, 30, 30)) omited_string += '#' elif eq[i].isnumeric() or eq[i] in "()=": num = font.render(eq[i], True, blue, pale) rect = num.get_rect() rect.topleft = ((20 + i * (WINDOW_WIDTH - 50) / num_spaces), WINDOW_HEIGHT * 0.30) equation_display.append((num, rect)) omited_string += eq[i] else: omited_string += eq[i] mult_l = mult_x, mult_y = [50, WINDOW_HEIGHT * 0.70] plus_l = plus_x, plus_y = [(50 + (WINDOW_WIDTH - 50) / 4), WINDOW_HEIGHT * 0.70] minus_l = minus_x, minus_y = [(50 + 2 * (WINDOW_WIDTH - 50) / 4), WINDOW_HEIGHT * 0.70 + 12] divide_l = divide_x, divide_y = [(50 + 3 * (WINDOW_WIDTH - 50) / 4), WINDOW_HEIGHT * 0.70] mult_orig = (mult_x, mult_y) plus_orig = (plus_x, plus_y) minus_orig = (minus_x, minus_y) divide_orig = (divide_x, divide_y) signs = [] signs_placed = [] x = 50 y = 50 width = 50 height = 70 run = True clicking_obj = {} while run: win.fill((255, 255, 153)) mx, my = pygame.mouse.get_pos() if screen == GAME_SCREEN: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: if mult_orig[0] <= mx <= mult_orig[0] + 50 and \ mult_orig[1] <= my <= mult_orig[1] + 50: new_mult = mult signs.append([new_mult, mx, my, "*", False]) clicking_obj[len(signs) - 1] = True if minus_orig[0] <= mx <= minus_orig[0] + 50 and minus_orig[ 1] <= my <= minus_orig[1] + 50: new_minus = minus signs.append([new_minus, mx, my, "-", False]) clicking_obj[len(signs) - 1] = True if plus_orig[0] <= mx <= plus_orig[0] + 50 and plus_orig[ 1] <= my <= plus_orig[1] + 50: new_plus = plus signs.append([new_plus, mx, my, "+", False]) clicking_obj[len(signs) - 1] = True if divide_orig[0] <= mx <= divide_orig[0] + 50 and divide_orig[ 1] <= my <= divide_orig[1] + 50: new_divide = divide signs.append([new_divide, mx, my, "/", False]) clicking_obj[len(signs) - 1] = True if mx >= 500 - check.get_rect().width and my >= 450: signs_placed.sort() final_string = omited_string for i in signs_placed: final_string = final_string.replace("#", i[1], 1) if "#" not in final_string and eval_expression(final_string): screen = VICTORY_SCREEN for i in range(len(signs)): if signs[i][3] == '-' and signs[i][1] - 5 <= mx <= signs[i][1] + 35 and \ signs[i][2] - 8 <= my <= signs[i][2] + 15: clicking_obj[i] = True break elif signs[i][3] != '-' and signs[i][1] <= mx <= signs[i][1] + 30 and signs[i][2] <= my <= \ signs[i][2] + 30: clicking_obj[i] = True break if event.type == pygame.MOUSEBUTTONUP: if event.button == 1: for i in clicking_obj: if clicking_obj[i]: clicking_obj[i] = False is_on_blank = False for y in range(len(equation_display)): if len(equation_display[y]) != 2: blank_loc = ( equation_display[y][0], equation_display[y][1]) if blank_loc[0] <= mx <= blank_loc[ 0] + 30 and blank_loc[1] <= my <= \ blank_loc[1] + 30: signs[i][1] = blank_loc[0] signs[i][2] = blank_loc[1] if signs[i][3] == '-': signs[i][2] += 12 if signs[i][4]: for z in range(len(signs_placed)): if signs_placed[z][2] == i: signs_placed.pop(z) break signs_placed.append((y, signs[i][3], i)) is_on_blank = True if signs[i][4] and not is_on_blank: signs[i][4] = False for y in range(len(signs_placed)): if signs_placed[y][2] == i: signs_placed.pop(y) break signs[i][4] = is_on_blank break for i in clicking_obj: if clicking_obj[i]: signs[i][1] = mx - 15 signs[i][2] = my - 15 if signs[i][3] == '-': signs[i][1] = mx - 15 signs[i][2] = my - 3 for item in equation_display: if len(item) == 2: win.blit(item[0], item[1]) else: pygame.draw.rect(win, (255, 0, 0), item) for i in range(len(signs)): if signs[i][3] == '*' or signs[i][3] == '/' or signs[i][3] == '+': win.blit(signs[i][0], (signs[i][1], signs[i][2])) elif signs[i][3] == '-': pygame.draw.rect(win, (0, 0, 0), (signs[i][1], signs[i][2], 30, 7)) pygame.draw.rect(win, (0, 0, 0), (minus_x, minus_y, 30, 7)) win.blit(plus, plus_l) win.blit(divide, divide_l) win.blit(mult, mult_l) rect = check.get_rect() rect.topleft = (500 - rect.width, 450) win.blit(check, rect) elif screen == VICTORY_SCREEN: vict_font = pygame.font.Font('freesansbold.ttf', 50) vict1 = vict_font.render("Congratulations,", True, (0, 0, 0), pale) vict2 = vict_font.render("you got it!", True, (0, 0, 0), pale) vict3 = vict_font.render(":D", True, (0, 0, 0), pale) vict1_rect = vict1.get_rect() vict1_rect.topleft = (50, 160) vict2_rect = vict2.get_rect() vict2_rect.topleft = (90, 220) vict3_rect = vict3.get_rect() vict3_rect.topleft = (240, 280) retry = vict_font.render("Next Challenge?", True, (255, 255, 255), (0, 0, 0)) retry_rect = retry.get_rect() retry_rect.topleft = (89, 450) win.blit(vict1, vict1_rect) win.blit(vict2, vict2_rect) win.blit(vict3, vict3_rect) win.blit(retry, retry_rect) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: if mx >= 89 and my >= 450: screen = GAME_SCREEN signs = [] signs_placed = [] clicking_obj = {} omited_string = "" eq = "Impossible" while eq == "Impossible": numbers = [random.randint(0, 9) for i in range(4)] numbers = tuple(numbers) result = random.randint(0, 50) solve = solver.OperationGuess() eq = solve.solve(numbers, result) eq += ' = {}'.format(result) num_spaces = len(eq) equation_display = [] for i in range(num_spaces): if eq[i] == "+" or eq[i] == "-" or eq[ i] == "/" or eq[i] == "*": equation_display.append(((20 + i * (WINDOW_WIDTH - 50) / num_spaces), WINDOW_HEIGHT * 0.30, 30, 30)) omited_string += '#' elif eq[i].isnumeric() or eq[i] in "()=": num = font.render(eq[i], True, blue, pale) rect = num.get_rect() rect.topleft = ((20 + i * (WINDOW_WIDTH - 50) / num_spaces), WINDOW_HEIGHT * 0.30) equation_display.append((num, rect)) omited_string += eq[i] else: omited_string += eq[i] pygame.display.update() pygame.quit()
''' Sauer's book page 43. Derive three different g(x) for finding roots to six correct decimal places of the following f(x) = 0 by Fixed-Point Iteration. Run FPI for each g(x) and report results, convergence or divergence. Each equation f (x) = 0 has three roots. Derive more g(x) if necessary until all roots are found by FPI. For each convergent run, determine the value of S from the errors e i+1 /e i , and compare with S determined from calculus as in (1.11). (a) f(x) = 2x**3 − 6x − 1 (b) f(x) = e**x−2 + x**3 − x (c) f(x) = 1 + 5x − 6x**3 − e**2x A return 1 / ((2 * (x ** 2)) - 6) -0.1682544 return pow((0.5 + 3 * x), 1/3) 1.81003792 B return pow(x - e ** (x - 2), 1/3) 0.78894139 return -e ** (x - 2) / ((x ** 2) - 1) 0.16382224 C Complex solutions. ''' from math import * def psi(x, op): if op == 'A': return pow(x - e ** (x - 2), 1/3) if op == 'B': return -e ** (x - 2) / ((x ** 2) - 1) return x ** 3 + e ** (x - 2) def equal(xk1, xk): m = abs(xk1 - xk) e = 10**(-8) / 2.0 if m < e: return True return False def fixed_point(x, x0, k, op): b = x a = psi(x, op) if k and equal(a, b): return a else: return fixed_point(a, b, k+1, op) def main(): print("Choose the function you want to test!") print("A. f(x) = 2x**3 − 6x − 1") print("B. f(x) = e**x−2 + x**3 − x") print("C. f(x) = 1 + 5x − 6x**3 − e**2x) print("function: ") op = input() print("Type x0 value: ") x0 = float(input()) root = str(fixed_point(x0, x0, 0, op)) print("The root is: {:.10}".format(root)) if __name__ == "__main__": main()
# Multiples of 3 and 5 # If we list all the natural numbers below 10 that are multiples # of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. # # real 0m0.045s # user 0m0.027s # sys 0m0.014s sum = 0 for i in range(1, 1000): if i % 3 == 0 or i % 5 == 0: sum += i print "Answer: %s" % sum
# Python3 implementation of the approach # Link list node class Node: def __init__(self): self.data = 0 self.next = None # Function to get the intersection point # of the given linked lists def getIntersectionNode(head1, head2): curr1 = head1 curr2 = head2 # While both the pointers are not equal while (curr1 != curr2): # If the first pointer is None then # set it to point to the head of # the second linked list if (curr1 == None): curr1 = head2 # Else point it to the next node else: curr1 = curr1.next # If the second pointer is None then # set it to point to the head of # the first linked list if (curr2 == None): curr2 = head1 # Else point it to the next node else: curr2 = curr2.next # Return the intersection node return curr1.data # Driver code # Create two linked lists # 1st Linked list is 3.6.9.15.30 # 2nd Linked list is 10.15.30 # 15 is the intersection point newNode = None head1 = Node() head1.data = 10 head2 = Node() head2.data = 3 newNode = Node() newNode.data = 6 head2.next = newNode newNode = Node() newNode.data = 9 head2.next.next = newNode newNode = Node() newNode.data = 15 head1.next = newNode head2.next.next.next = newNode newNode = Node() newNode.data = 30 head1.next.next = newNode head1.next.next.next = None # Print the intersection node print(getIntersectionNode(head1, head2))
class Solution(object): def majorityElement(nums): """ :type nums: List[int] :rtype: int """ count = 0 candidate = None for num in nums: if count == 0: candidate = num if num == candidate: count = count + 1 else: count = count - 1 return candidate arr=[2,3,4,3,3] a=majorityElement(arr) print(a)
def removeAdjDup(s, n): chars = list(s) # k maintains the index of next free location in the result k = 0 # i maintains the current index in the String # start from the second character i = 1 print(chars) while i < len(chars): # if current character is not same as the # previous character, add it to result if chars[i - 1] != chars[i]: print("in if loop") print(chars) chars[k] = chars[i - 1] k = k + 1 print(chars) else: print("in else loop") # remove adjacent duplicates print(chars[i - 1],chars[i]) while i < len(chars) and chars[i - 1] == chars[i]: i = i + 1 i = i + 1 print("chars at end of loop",chars) print(i,k) # Add last character to result chars[k] = chars[i - 1] k = k + 1 print("chars",chars) # construct the with first k chars s = ''.join(chars[:k]) print("combine s",s) # start again if any duplicate is removed if k != n: print("going again",s) return removeAdjDup(s, k) # Shlemiel Painter's Algorithm # if the algorithm didn't change the input String, that means # all the adjacent duplicates are removed return s if __name__ == '__main__': str = "DBCCA" print("The left after removal of all adjacent duplicates is", removeAdjDup(str, len(str)))
square = {2: 4, 3: 9, -1: 1, -2: 4} # the smallest key key1 = min(square) print("The smallest key:", key1) # -2 # the key whose value is the smallest key2 = min(square, key = lambda k: square[k]) print("The key with the smallest value:", key2) # -1 # getting the smallest value print("The smallest value:", square[key2]) # 1 from collections import OrderedDict dict = {'ravi': '10', 'rajnish': '9', 'sanjeev': '15', 'yash': '2', 'suraj': '32'} dict1 = OrderedDict(sorted(dict.items())) print(dict1) ############################################################################################ for i in sorted(dict.keys()): print(dict[i]) ########## sorted values ################################################################################## dict1 = {1: 'a', 2: 'd', 3: 'c'} sorted_dict = {} sorted_keys = sorted(dict1, key=dict1.get) # [1, 3, 2] print("asas",sorted_keys) for w in sorted_keys: sorted_dict[w] = dict1[w] print(sorted_dict) # {1: 1, 3: 4, 2: 9} ########################################################## dict1 = {'carl':40, 'alan':2, 'bob':1, 'danny':3} sorted_tuples = sorted(dict1.items(), key=lambda item: item[1]) print(sorted_tuples) # [(1, 1), (3, 4), (2, 9)] sorted_dict = {k: v for k, v in sorted_tuples} print(sorted_dict) # {1: 1, 3: 4, 2: 9} ########################################################## mydict = {'carl':40, 'alan':2, 'bob':1, 'danny':3} for key in sorted(mydict): print(key, mydict[key])
def twosum(arr,target): dm={} for i in range(0,len(arr)): val=target-arr[i] if val in dm: print("sum of",arr[i],str(val)) return True else: dm[arr[i]]=i a = twosum(arr=[2, 3, 7, 9], target=10) print(a)
''' In this chapter, you'll be introduced to fundamental concepts in network analytics while exploring a real-world Twitter network dataset. You'll also learn about NetworkX, a library that allows you to manipulate, analyze, and model graph data. You'll learn about the different types of graphs and how to rationally visualize them. ''' ''' Basic drawing of a network using NetworkX ''' # Import necessary modules import networkx as nx import matplotlib.pyplot as plt # Draw the graph to screen nx.draw(T_sub) plt.show() ''' Queries on a graph ''' # Use a list comprehension to get the nodes of interest: noi noi = [n for n, d in T.nodes(data=True) if d['occupation'] == 'scientist'] # Use a list comprehension to get the edges of interest: eoi eoi = [(u, v) for u, v, d in T.edges(data=True) if d['date'] < date(2010, 1, 1)] ''' Specifying a weight on edges ''' # Set the weight of the edge T.edges[1,10]['weight'] = 2 # Iterate over all the edges (with metadata) for u, v, d in T.edges(data=True): # Check if node 293 is involved if 293 in [u,v]: # Set the weight to 1.1 T.edges[u,v]['weight'] = 1.1 ''' Checking whether there are self-loops in the graph ''' # Define find_selfloop_nodes() def find_selfloop_nodes(G): """ Finds all nodes that have self-loops in the graph G. """ nodes_in_selfloops = [] # Iterate over all the edges of G for u, v in G.edges(): # Check if node u and node v are the same if u == v: # Append node u to nodes_in_selfloops nodes_in_selfloops.append(u) return nodes_in_selfloops # Check whether number of self loops equals the number of nodes in self loops assert T.number_of_selfloops() == len(find_selfloop_nodes(T)) ''' Visualizing using Matrix plots It is time to try your first "fancy" graph visualization method: a matrix plot. To do this, nxviz provides a MatrixPlot object. nxviz is a package for visualizing graphs in a rational fashion. Under the hood, the MatrixPlot utilizes nx.to_numpy_matrix(G), which returns the matrix form of the graph. Here, each node is one column and one row, and an edge between the two nodes is indicated by the value 1. In doing so, however, only the weight metadata is preserved; all other metadata is lost, as you'll verify using an assert statement. A corresponding nx.from_numpy_matrix(A) allows one to quickly create a graph from a NumPy matrix. The default graph type is Graph(); if you want to make it a DiGraph(), that has to be specified using the create_using keyword argument, e.g. (nx.from_numpy_matrix(A, create_using=nx.DiGraph)). ''' # Import nxviz import nxviz as nv # Create the MatrixPlot object: m m = nv.MatrixPlot(T) # Draw m to the screen m.draw() # Display the plot plt.show() # Convert T to a matrix format: A A = nx.to_numpy_matrix(T) # Convert A back to the NetworkX form as a directed graph: T_conv T_conv = nx.from_numpy_matrix(A, create_using=nx.DiGraph()) # Check that the `category` metadata field is lost from each node for n, d in T_conv.nodes(data=True): assert 'category' not in d.keys() ''' Visualizing using Circos plots Circos plots are a rational, non-cluttered way of visualizing graph data, in which nodes are ordered around the circumference in some fashion, and the edges are drawn within the circle that results, giving a beautiful as well as informative visualization about the structure of the network. ''' # Import necessary modules import matplotlib.pyplot as plt from nxviz import CircosPlot # Create the CircosPlot object: c c = CircosPlot(T) # Draw c to the screen c.draw() # Display the plot plt.show() ''' Visualizing using Arc plots Following on what you've learned about the nxviz API, now try making an ArcPlot of the network. Two keyword arguments that you will try here are node_order='keyX' and node_color='keyX', in which you specify a key in the node metadata dictionary to color and order the nodes by. ''' # Import necessary modules import matplotlib.pyplot as plt from nxviz import ArcPlot # Create the un-customized ArcPlot object: a a = ArcPlot(T) # Draw a to the screen a.draw() # Display the plot plt.show() # Create the customized ArcPlot object: a2 a2 = ArcPlot(T, node_order='category', node_color='category') # Draw a2 to the screen a2.draw() # Display the plot plt.show()
import math as m h = float(input("Digite a altura da parede: ")) w = float(input("Digite a largura da parede: ")) area = h * w areaTinta = 2 print("Para pintar uma parede de {:0.2f} m^2 é necessário {} litros de tinta".format(area, m.ceil(area/areaTinta)))
n = int(input("Digite um número inteiro: ")) divisores = 0 divisor = 1 while (divisores <= 2 and divisor <= n): if n % divisor == 0: divisores+= 1 divisor += 1 if (divisores == 2): print("primo") else: print("não primo")
print("\033[7;30m-=\033[m"*20) print("\033[7;30m{:^40s}\033[m".format("MÉDIA DE NOTAS")) print("\033[7;30m-=\033[m"*20) n1 = float(input("Digite a primeira nota do aluno: ")) n2 = float(input("Digite a segunda nota do aluno: ")) media = (n1+n2)/2 print("A média das notas do aluno foi \033[41;30m{:.2f}\033[m".format(media))
''' Course: Writing Efficient Python Code Chapter: 1 - Foundations for efficiencies In this chapter, you'll learn what it means to write efficient Python code. You'll explore Python's Standard Library, learn about NumPy arrays, and practice using some of Python's built-in tools. This chapter builds a foundation for the concepts covered ahead. Remember, Pythonic code == efficient code ''' import pandas as pd ''' Foundations for efficiencies ''' # Print the list created using the Non-Pythonic approach i = 0 new_list= [] while i < len(names): if len(names[i]) >= 6: new_list.append(names[i]) i += 1 print(new_list) # Print the list created by looping over the contents of names better_list = [] for name in names: if len(name) >= 6: better_list.append(name) print(better_list) # Print the list created by using list comprehension best_list = [name for name in names if len(name) >= 6] print(best_list) ''' Built-in practice: range() Notice that using Python's range() function allows you to create a range object of numbers without explicitly typing them out. You can convert the range object into a list by using the list() function or by unpacking it into a list using the star character (*). Cool! ''' # Create a range object that goes from 0 to 5 nums = range(6) print(type(nums)) # Convert nums to a list nums_list = list(nums) print(nums_list) # Create a new list of odd numbers from 1 to 11 by unpacking a range object nums_list2 = [*range(1,12,2)] print(nums_list2) ''' Built-in practice: enumerate() Using Python's built-in enumerate() function allows you to create an index for each item in the object you give it. You can use list comprehension, or even unpack the enumerate object directly into a list, to write a nice simple one-liner. ''' # Rewrite the for loop to use enumerate indexed_names = [] for i,name in enumerate(names): index_name = (i,name) indexed_names.append(index_name) print(indexed_names) # Rewrite the above for loop using list comprehension indexed_names_comp = [(i,name) for i,name in enumerate(names)] print(indexed_names_comp) # Unpack an enumerate object with a starting index of one indexed_names_unpack = [*enumerate(names, start=1)] print(indexed_names_unpack) ''' Built-in practice: map() You used Python's built-in map() function to apply the str.upper() method to each element in the names object. Later on in the course, you'll explore how using map() can provide some efficiency improvements to your code. ''' # Use map to apply str.upper to each element in names names_map = map(str.upper, names) # Print the type of the names_map print(type(names_map)) # Unpack names_map into a list names_uppercase = [*names_map] # Print the list created above print(names_uppercase) ''' Practice with NumPy arrays ''' # Print second row of nums print(nums[1,:]) # Print all elements of nums that are greater than six print(nums[nums > 6]) # Double every element of nums nums_dbl = nums * 2 print(nums_dbl) # Replace the third column of nums nums[:,2] = nums[:,2] + 1 print(nums) ''' Bringing it all together: Festivus! ''' # Create a list of arrival times arrival_times = [*range(10,60,10)] # Convert arrival_times to an array and update the times arrival_times_np = np.array(arrival_times) new_times = arrival_times_np - 3 # Use list comprehension and enumerate to pair guests to new times guest_arrivals = [(names[i],time) for i,time in enumerate(new_times)] # Map the welcome_guest function to each (guest,time) pair welcome_map = map(welcome_guest, guest_arrivals) guest_welcomes = [*welcome_map] print(*guest_welcomes, sep='\n')
n = int(input("Digite o valor de n: ")) i = 0 x = 0 while (x < n): if (not i % 2 == 0): print(i) x +=1 i +=1
''' Having been exposed to the toolbox of data engineers, it's now time to jump into the bread and butter of a data engineer's workflow! With ETL, you will learn how to extract raw data from various sources, transform this raw data into actionable insights, and load it into relevant databases ready for consumption! ''' ''' Data sources In the previous video you've learned about three ways of extracting data: Extract from text files, like .txt or .csv Extract from APIs of web services, like the Hackernews API Extract from a database, like a SQL application database for customer data We also briefly touched upon row-oriented databases and OLTP. ''' ''' Fetch from an API ''' import requests # Fetch the Hackernews post resp = requests.get("https://hacker-news.firebaseio.com/v0/item/16222426.json") # Print the response parsed as JSON print(resp.json()) # Assign the score of the test to post_score post_score = resp.json()['score'] print(post_score) ''' Read from a database ''' # Function to extract table to a pandas DataFrame def extract_table_to_pandas(tablename, db_engine): query = "SELECT * FROM {}".format(tablename) return pd.read_sql(query, db_engine) # Connect to the database using the connection URI connection_uri = "postgresql://repl:password@localhost:5432/pagila" db_engine = sqlalchemy.create_engine(connection_uri) # Extract the film table into a pandas DataFrame extract_table_to_pandas('film', db_engine) # Extract the customer table into a pandas DataFrame extract_table_to_pandas('customer', db_engine) '''
n = int(input("Digite um número: ")) cores = {"limpa": "\033[m", "inverte": "\033[7;30m"} print("{}dobro de {} = {}{}\n" "Triplo de {} = {}\n" "{}Raiz quadrada de {} = {:.2f}{}" .format(cores["inverte"], n, n*2, cores["limpa"], n, n*3,cores["inverte"], n, n**(1/2), cores["limpa"]))
def pay(hour, rate): if hours > 40: pay = 40 * rate pay = pay + (hours - 40) * (rate * 1.5) else: pay = hours * rate return pay print("Hello user") hoursSTR = input("Enter how many hours your work this month: ") try: hours = float(hoursSTR) except Exception as e: hours = -1 if hours == -1: print("Error, please enter numeric input") exit() rateSTR = input("Enter your rate/hour: ") try: rate = float(rateSTR) except Exception as e: rate = -1 if rate == -1: print("Error, please enter numeric input") exit() else: print(pay(hours, rate))
i = 1 lista = [] while i != 0: i = int(input("Digite um número: ")) lista.append(i) tam = len(lista) while tam > 1: print(lista[tam-2]) tam -= 1
''' Now that you know the primary differences between a data engineer and a data scientist, get ready to explore the data engineer's toolbox! Learn in detail about different types of databases data engineers use, how parallel computing is a cornerstone of the data engineer's toolkit, and how to schedule data processing jobs using scheduling frameworks. ''' ''' The database schema A PostgreSQL database is set up in your local environment, which contains this database schema. It's been filled with some example data. You can use pandas to query the database using the read_sql() function. You'll have to pass it a database engine, which has been defined for you and is called db_engine. The pandas package imported as pd will store the query result into a DataFrame object, so you can use any DataFrame functionality on it after fetching the results from the database. ''' # Complete the SELECT statement data = pd.read_sql(""" SELECT first_name, last_name FROM "Customer" ORDER BY last_name, first_name """, db_engine) # Show the first 3 rows of the DataFrame print(data.head(3)) # Show the info of the DataFrame print(data.info()) ''' Joining on relations ''' # Complete the SELECT statement data = pd.read_sql(""" SELECT * FROM "Customer" INNER JOIN "Order" ON "Order"."customer_id"="Customer"."id" """, db_engine) # Show the id column of data print(data.id) ''' From task to subtasks For this exercise, you will be using parallel computing to apply the function take_mean_age() that calculates the average athlete's age in a given year in the Olympics events dataset. The DataFrame athlete_events has been loaded for you and contains amongst others, two columns: Year: the year the Olympic event took place Age: the age of the Olympian You will be using the multiprocessor.Pool API which allows you to distribute your workload over several processes. The function parallel_apply() is defined in the sample code. It takes in as input the function being applied, the grouping used, and the number of cores needed for the analysis. Note that the @print_timing decorator is used to time each operation. ''' # Function to apply a function over multiple cores @print_timing def parallel_apply(apply_func, groups, nb_cores): with Pool(nb_cores) as p: results = p.map(apply_func, groups) return pd.concat(results) # Parallel apply using 1 core parallel_apply(take_mean_age, athlete_events.groupby('Year'), 1) # Parallel apply using 2 cores parallel_apply(take_mean_age, athlete_events.groupby('Year'), 2) # Parallel apply using 4 cores parallel_apply(take_mean_age, athlete_events.groupby('Year'), 4) ''' Using a DataFrame In the previous exercise, you saw how to split up a task and use the low-level python multiprocessing.Pool API to do calculations on several processing units. It's essential to understand this on a lower level, but in reality, you'll never use this kind of APIs. A more convenient way to parallelize an apply over several groups is using the dask framework and its abstraction of the pandas DataFrame, for example. The pandas DataFrame, athlete_events, is available in your workspace. ''' import dask.dataframe as dd # Set the number of pratitions athlete_events_dask = dd.from_pandas(athlete_events, npartitions = 4) # Calculate the mean Age per Year print(athlete_events_dask.groupby('Year').Age.mean().compute()) ''' A PySpark groupby You've seen how to use the dask framework and its DataFrame abstraction to do some calculations. However, as you've seen in the video, in the big data world Spark is probably a more popular choice for data processing. In this exercise, you'll use the PySpark package to handle a Spark DataFrame. The data is the same as in previous exercises: participants of Olympic events between 1896 and 2016. The Spark Dataframe, athlete_events_spark is available in your workspace. The methods you're going to use in this exercise are: .printSchema(): helps print the schema of a Spark DataFrame. .groupBy(): grouping statement for an aggregation. .mean(): take the mean over each group. .show(): show the results. ''' # Print the type of athlete_events_spark print(type(athlete_events_spark)) # Print the schema of athlete_events_spark print(athlete_events_spark.printSchema()) # Group by the Year, and find the mean Age print(athlete_events_spark.groupBy('Year').mean("Age")) # Group by the Year, and find the mean Age print(athlete_events_spark.groupBy('Year').mean("Age").show()) ''' Running PySpark files In this exercise, you're going to run a PySpark file using spark-submit. This tool can help you submit your application to a spark cluster. For the sake of this exercise, you're going to work with a local Spark instance running on 4 threads. The file you need to submit is in /home/repl/spark-script.py. Feel free to read the file: cat /home/repl/spark-script.py You can use spark-submit as follows: spark-submit \ --master local[4] \ /home/repl/spark-script.py ''' ''' Airflow DAGs Fill in the schedule_interval keyword argument using the crontab notation ''' # Create the DAG object dag = DAG(dag_id="car_factory_simulation", default_args={"owner": "airflow","start_date": airflow.utils.dates.days_ago(2)}, schedule_interval="0 * * * *") # Create the DAG object dag = DAG(dag_id="car_factory_simulation", default_args={"owner": "airflow","start_date": airflow.utils.dates.days_ago(2)}, schedule_interval="0 * * * *") # Task definitions assemble_frame = BashOperator(task_id="assemble_frame", bash_command='echo "Assembling frame"', dag=dag) place_tires = BashOperator(task_id="place_tires", bash_command='echo "Placing tires"', dag=dag) assemble_body = BashOperator(task_id="assemble_body", bash_command='echo "Assembling body"', dag=dag) apply_paint = BashOperator(task_id="apply_paint", bash_command='echo "Applying paint"', dag=dag) # Complete the downstream flow assemble_frame.set_downstream(place_tires) assemble_frame.set_downstream(assemble_body) assemble_body.set_downstream(apply_paint)
n = float(input("Digite um valor em m: ")) print("A medida de {:.2f} m é equivalente a {:.1f} cm e a {:.0f} mm".format(n, n *100, n*1000))
n = int(input("Digite um número inteiro: ")) print("-"*12) for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: print("{} x {:2} = {}".format(n, i, n*i)) print("-"*12)
import math as m x1 = int(input("Digite o primeiro número: ")) y1 = int(input("Digite o segundo número: ")) x2 = int(input("Digite o terceiro número: ")) y2 = int(input("Digite o quarto número: ")) D = m.sqrt(m.pow(x2-x1, 2) + m.pow(y2-y1, 2)) if D >= 10: print("longe") else: print("perto")
cidade = input("Informe o nome da sua cidade: ").strip() duvida = "santo" in cidade.split()[0].lower() if duvida: print("Sua cidade começa com a palavra Santo") else: print("A cidade não começa com a palavra Santo")
''' Course: Working with Dates and Times in Python Chapter 4: Easy and Powerful: Dates and Times in Pandas To conclude this course, you'll apply everything you've learned about working with dates and times in standard Python to working with dates and times in Pandas. With additional information about each bike ride, such as what station it started and stopped at and whether or not the rider had a yearly membership, you'll be able to dig much more deeply into the bike trip data. In this chapter, you'll cover powerful Pandas operations, such as grouping and plotting results by time. * method to work datetime object on pandas package ''' import pandas as pd import numpy as np ''' Loading a csv file in Pandas ''' # Import pandas import pandas as pd # Load CSV into the rides variable rides = pd.read_csv('capital-onebike.csv', parse_dates = ['Start date', 'End date']) # Print the initial (0th) row print(rides.iloc[0]) ''' Making timedelta columns ''' # Subtract the start date from the end date ride_durations = rides['End date'] - rides['Start date'] # Convert the results to seconds rides['Duration'] = ride_durations.dt.total_seconds() print(rides['Duration'].head()) ''' How many joyrides? Suppose you have a theory that some people take long bike rides before putting their bike back in the same dock. Let's call these rides "joyrides". You only have data on one bike, so while you can't draw any bigger conclusions, it's certainly worth a look. Are there many joyrides? How long were they in our data set? Use the median instead of the mean, because we know there are some very long trips in our data set that might skew the answer, and the median is less sensitive to outliers. ''' # Create joyrides joyrides = (rides['Start station'] == rides['End station']) # Total number of joyrides print("{} rides were joyrides".format(joyrides.sum())) # Median of all rides print("The median duration overall was {:.2f} seconds"\ .format(rides['Duration'].median())) # Median of joyrides print("The median duration for joyrides was {:.2f} seconds"\ .format(rides[joyrides]['Duration'].median())) ''' It's getting cold outside, W20529 ''' # Import matplotlib import matplotlib.pyplot as plt # Resample rides to daily, take the size, plot the results rides.resample('D', on = 'Start date')\ .size()\ .plot(ylim = [0, 15]) # Show the results plt.show() '''' Members vs casual riders over time ''' # Resample rides to be monthly on the basis of Start date monthly_rides = rides.resample('M', on='Start date')['Member type'] # Take the ratio of the .value_counts() over the total number of rides print(monthly_rides.value_counts() / monthly_rides.size()) ''' Combining groupby() and resample() ''' # Group rides by member type, and resample to the month grouped = rides.groupby('Member type')\ .resample('M', on='Start date') # Print the median duration for each group print(grouped['Duration'].median()) ''' Timezones in Pandas ''' # Localize the Start date column to America/New_York rides['Start date'] = rides['Start date'].dt.tz_localize('America/New_York', ambiguous='NaT') # Print first value print(rides['Start date'].iloc[0]) # Convert the Start date column to Europe/London rides['Start date'] = rides['Start date'].dt.tz_convert('Europe/London') # Print the new value print(rides['Start date'].iloc[0]) ''' How long per weekday? Pandas has a number of datetime-related attributes within the .dt accessor. Many of them are ones you've encountered before, like .dt.month. Others are convenient and save time compared to standard Python, like .dt.weekday_name. ''' # Add a column for the weekday of the start of the ride rides['Ride start weekday'] = rides['Start date'].dt.weekday_name # Print the median trip time per weekday print(rides.groupby('Ride start weekday')['Duration'].median()) ''' How long between rides? ''' # Shift the index of the end date up one; now subract it from the start date rides['Time since'] = rides['Start date'] - (rides['End date'].shift(1)) # Move from a timedelta to a number of seconds, which is easier to work with rides['Time since'] = rides['Time since'].dt.total_seconds() # Resample to the month monthly = rides.resample('M', on='Start date') # Print the average hours between rides each month print(monthly['Time since'].mean()/(60*60))
#/usr/bin/python3 def count(string, word): counter=0 word_length = len(word) for index, value in enumerate(string): print(string[index:word_length + index]) if string[index:word_length + index] == word: counter += 1 return counter def calculate_score(string): ''' Given a list, the minion game score is calculated for from the list ''' previous_sequence = '' score =0 for v in string: previous_sequence += v # remebers the previous substring score += string.count(previous_sequence) print(previous_sequence, string.count(previous_sequence)) return score def minion_game(s): # your code goes here s=s.up per() stuart_score = 0 # s ore holder for stuart kevin_score = 0 # s ore holder for kevin vowels="AEIOU" string_length = len(s) if 0 < len(s) <= 10e6 : previous = '' seen = set() # s t to remember letters already seen in the string for index,v in enumerate(s): if v not in seen: #seen.add(v) print(str(index),v) if v in vowels: kevin_score += calculate_score(s[index:string_length]) else: stuart_score += calculate_score(s[index:string_length]) print ("Stuart " + str(stuart_score)) print("Kevin "+ str(kevin_score)) if __name__ == '__main__': # s = input() minion_game("BAANANAS") #print(count("banana", "ana"))
# 0 1 2 3 4 5 6 7 lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] if __name__ == '__main__': print(lst[::2]) # Output: ['a', 'c', 'e', 'g'] print(lst[2:4]) # Output: ['c', 'd'] print(lst[2:]) # Output: ['c', 'd', 'e', 'f', 'g', 'h']
def fourthpower(x): """ Inputs x. Takes x to the fourth (4th) power. It does so using a function inside a function -- secondpower(x). This is an exercise in using functions and scopes/namespaces. """ def secondpower(x): x = x ** 2 secondpower(secondpower(x))
# -*- coding: utf-8 -*- """ Created on Tue Nov 28 18:59:34 2017 @author: Dimitar Nikolov """ # This is Iteration 3, or the second refactoring of my Zen of Python script. # This is by far my cleanest attempt at storing and printing the poem. How it works: # The poem is stored in a text file called Poem.txt. Then, a function called zenOfPython # reads the file -- and prints its contents. Simple! This separates the content (which might # need to be edited by a user at a certain point in time) from the backend, which tells the # script to read and print it. At this stage of my Python knowledge, I can say that this is # my most elegant software solution so far. def zenOfPython(): poem = open('Poem.txt', 'r') print(poem.read()) zenOfPython()
def is_palindrome(word): """Return True/False if this word is a palindrome. >>> is_palindrome("a") True >>> is_palindrome("noon") True >>> is_palindrome("racecar") True >>> is_palindrome("porcupine") False >>> is_palindrome("Racecar") False """ # # using list slicing # # Runtime for list slicing: a[:k] = b[:k] # # In this case, our runtime would be O(k) where k is the entire length of the lsit # if word == word[::-1]: # return True # return False # using iteration # make a right index and a left index # while the right index < left index # if the value of the right index doesnt equal the value of the left index, return False # Increment left and right index # return True if you get all the way through the loop and all letters are equal # left_index = 0 # right_index = len(word) - 1 # while left_index < right_index: # if word[left_index] != word[right_index]: # return False # left_index += 1 # right_index -= 1 # return True for i in range(len(word) / 2): if word[i] != word[-i - 1]: return False return True if __name__ == "__main__": import doctest if doctest.testmod().failed == 0: print "All test passed!!"
def is_pangram(sentence): """Given a string, return True if it is a pangram, False otherwise. >>> is_pangram("The quick brown fox jumps over the lazy dog!") True >>> is_pangram("I like cats, but not mice") False """ # a panagram is a sentence that contains all of the letters of the english # alphabet at least once # create a set out of the sentence # create a set out of the english dictionary (make sure to add a space) # check to see that the sets are equal # if so, return True # english_dict = {" ", "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"} # char_count = {} # for char in sentence: # char_count[char] = char_count.get(char, 0) + 1 # for item in english_dict: # if item not in char_count.keys(): # return False # return True # we can use a set comprehension... # loop through the charecters in the sentence # if the charecter is_alpha(not a space)... # add it to the set (lowercased) seen = set() for char in sentence: if char.isalpha(): seen.add(char.lower()) return len(seen) == 26 if __name__ == "__main__": import doctest if doctest.testmod().failed == 0: print "All tests passed!!"
"""Stack implemented using Python list""" class StackEmptyError(IndexError): """Attempt to pop an empty stack.""" class Stack(object): """LIFO stack. Implemented using a Python list; since stacks just need to pop and push, a list is a good implementation as popping and appending to the end of a list is an O(1) operation. However, in cases where performance matters, it might be best to use a Python list directly, becuase it avoids the overhead of a custom class. For even better performance and for a smalller memory footprint, you can use the collections.deque object, which can act like a stack. We could also write our own linkedlist class for a stack, where we push things onto the head and pop things off the head (effectively reversing it), but that would be less efficient than using a built-in Python list or a collections.deque object. """ def __init__(self, inlist=None): if inlist: self._list = inlist else: self._list = [] def __repr__(self): if not self._list: return "<Stack (empty)" else: return "<Stack tail={} length={}".format(self._list[-1], len(self._list)) def push(self, item): """Adds an item to the end of the stack.""" self._list.append(item) def pop(self): """Removes an item from the end of the stack and returns the item.""" # Ensure that the list is not empty # if it is, raise the stack empty error if not self._list: raise StackEmptyError return self._list.pop() def length(self): """Returns length of stack.""" return len(self._list) def peak(self): """Returns the top item in the stack.""" return self._list[-1] def empty(self): """Empty the stack""" self._list = [] def is_empty(self): """Is the stack empty?""" return not self._list ### Pancake shop class PancakeStack(Stack): """A stack of pancakes.""" def __repr__(self): """A representation of the Pancake stack.""" return "<PancakeStack NEXT: {pancake} REMAINING: {num}".format( def eat_next_pancake(self): """Remove a pancake from the stack.""" print "MMM {} pancakes are tasty.".format(self.pop()) def empty(self): """Clear all of the pancakes from the plate.""" while not self.is_empty(): print "There goes the {} pancake".format(self.pop()) self.print_empty_plate() def check_next_pancake(self): """Display the pancake at the top of the stack.""" next_pancake = self.peak() if next_pancake: print "The next pancake in the stack is a {} pancake".format(next_pancake) print self.print_empty_plate() def check_plate(self): """Print an ASCII-art representation of the pancake stack.""" if not self.is_empty(): print print " ({}) <--top of stack".format(self._list[-1]) for pancake in self._list[-2:-1]: print " {} ".format(pancake) print "\________________________/" print def print_empty_plate(self): """ascii representation of pancake plate without pancakes""" print print "Your plate is empty..." print "\________________________/" print def run_pancake_shop(pancakes=None): """REPL (read, evaluate, print loop) for our pancake dinner.""" if pancakes: plate = PancakeStack(pancakes) else: plate = PancakeStack() print "Welcome to the pancake shop" while True: print "Do you want to: " print "O)rder a pancake, E)at a pancake, C)heck your plate, or L)eave?" user_input = raw_input("> ").upper() if user_input == "O": flavor = raw_input("What flavor pancake would you like? ") plate.push(flavor) elif user_input == "E": plate.eat_next_pancake() elif user_input == "C": plate.check_plate() elif user_input == "L": print "Have a nice day!" break else: print "That is not one of the options, please try again."
"""Using a queue to make a console to make a console task manager""" class Queue(object): """A simple queue, implemented using a list.""" # NOTE: this is a straightforward way to implement a # queue -- but it's also inefficient if you'll have # many items in the queue. For a more efficient queue # implementation, you could build a Queue class # yourself using a doubly-linked list, or you could use # the Queue class included in Python's standard library, # "collections.deque" ("deque" = "double-ended queue") def __init__(self): self._data = [] def enqueue(self, item): """Add an item to the end of the list""" self._data.append(item) def dequeue(self): """Remove an item from the front of the queue""" return self._data.pop(0) def peak(self): """Show the first item in the queue""" return self._data[0] def is_empty(self): """Is the queue empty?""" # If the queue is an empty list, self._data would return False # So if the queue is empty we want to return true # modify with not self._data return not self._data # Instantiate our task_queue task_queue = Queue() while True: # we want to display to the user the next task to be done # we want to ask the user for input to add a task, do the task, or quit if task_queue.is_empty(): next_task = None else: next_task = task_queue.peak() print "Next task:", next_task command = raw_input("A)dd task, D)o first task, or Q)uit? ") if command == "A": new_task = raw_input("Okay, what is your new task? ") task_queue.enqueue(new_task) elif command == "D": print "Okay, finished", task_queue.dequeue() elif command == "Q": break else: print "That is an invalid command; try again"
############################## Linked List Basics ######################## # class Node(object): # """Node in a linked list""" # def __init__(self, data): # self.data = data # self.next = None # apple_node = Node("apple") # berry_node = Node("berry") # cherry_node = Node("cherry") # apple_node.next = berry_node # berry_node.next = cherry_node class LinkedList(object): """LinkedList""" def __init__(self): self.head = None # We can add a tail so that appending will be O(1) self.tail = None ############################## Traversing, Searching, Appending, Removing a linked list ######################## class LinkedList(object): # Traversing the list. Lets assume we have already built the list # We want to traverse the list and print it def print_list(self): """Print all of the items in the list""" current = self.head while current is not None: print current.data curent = current.next # Checking to see if data exists in our linked list def find(self, data): """Does this data exist in our list?""" current = self.head while current is not None: if current.data == data: return True current = current.next return False def append(self, data): """Append node with data to the end of the list.""" # Create a new node with passed in data new_node = Node(data) if self.head is None: self.head = new_node if self.tail is not None: self.tail.next = new_node self.tail = new_node ############################## Removing and Item from a Linked List ######################## class LinkedList(object): def remove(self, value): # If removing the head, you need to point the second item (if any) the new .head # If the head is not None and the head's data is equal to the value if self.head is not None and self.head.data == value: # Set the head equal to the next of the head self.head = self.head.next # Now, if the head is None (the list is empty now) if self.head is None: # Set the tail equal to none and return out of the function self.tail = None return # Removing something other than the head # Set the current to the head current = self.head # Keep traversing until the currents next is None while current.next is not None: # If the current's next data is equal to the value we are looking for, set the current.next to # the currents, next, next if current.next.data == value: current.next = current.next.next # If you're removing the last item and the current.next is None, update the tail if current.next is None: # If removing the last item, update .tail self.tail = current return # Havent found the value yet, keep traversing else: current = current.next
def show_evens(nums): """Given list of ints, return list of *indices* of even numbers in list.' >>> lst = [1, 2, 3, 4, 6, 8] >>> show_evens(lst) [1, 3, 4, 5] """ # using list comprehension: # if num % 2 is equal to zero, return the indices as list return [i for i, num in enumerate(nums) if num % 2 == 0] # without list comprehension: evens = [] for i, num in enumerate(nums): if num % 2 == 0: evens.append(i) return evens # without enumerate evens = [] for i in range(len(nums)): if nums[i] % 2 == 0: evens.append(i) return evens if __name__ == "__main__": import doctest if doctest.testmod().failed == 0: print "Passed tests"
import random class Animal(object): """An animal class""" name = None species = None def __init__(self, name, species): self.name = name self.species = species self.age = random.randint(1, 10) def speak(self): return "Hey! I am a {species} named {name}".format(species=self.species, name=self.name) def graduate(self): self.name = "Dr " + self.name def do_trick(self): print "(Wags tail)" print self.speak() fido = Animal("Fido", "dog") print fido.speak() print fido.name class MyClass(object): """Class attributes vs. instance attributes""" class_attr = 1 def __init__(self): self.instance_attr = 1 # Lets make an instance of my class o = MyClass() print o.class_attr # should be 1 print o.instance_attr # should be 1 MyClass.class_attr = 2 print o.class_attr # should be 2 o.class_attr = 3 print o.class_attr # should be 3 MyClass.class_attr = 4 print o.class_attr # should be 3 class Cat(Animal): """Cat class inherits from animal class.""" def __init__(self, name): # Using the super method, we can inherit the parent class's methods # And manually pass in "cat" for species super(Cat, self).__init__(name, "cat") def purr(self): # Now a cat can both purr and speak return "{} enfurs you!".format(self.name) class Dog(Animal): """Dog class inherits from the animal class""" def __init__(self, name): super(Dog, self).__init__(name, "dog") class FriendlyCat(Cat): """A friendly cat class that inherits from cat""" def greet(self): msg = super(FriendlyCat, self).purr() return " {}. You seem awesome".format(msg)
def deduped(items): """Return new list from items with duplicates removed. >>> deduped([1, 1, 1]) [1] >>> deduped([1, 2, 1, 1, 3]) [1, 2, 3] >>> deduped([1, 2, 3]) [1, 2, 3] >>> a = [1, 2, 3] >>> b = deduped(a) >>> a == b True >>> a is b False >>> deduped([]) [] """ # # create an empty dictionary # # create an emtpy list that we will return # # Loop through the items in the list, if the item is not in the dict, add item to the list, and to the dict # # If the item is in the dict, increase the count by 1 # # If the item is in the dict already, dont add the item to the list # # return list # duplicate_counts = {} # deduped = [] # for item in items: # duplicate_counts[item] = duplicate_counts.get(item, 0) + 1 # if duplicate_counts[item] == 1: # deduped.append(item) # return deduped ##################### HB SOLUTION #################################### # # sets are great for de-duplicating lists: # # sets dont maintain oder though, so if we want our answer to be in order # # we have to do the de-duplicating by hand # # however... this runtime would be O(n^2) becaause we have a for loop # # and nested inside that, we have an in which is a hidden for-loop # # for every charecter that we are looping over, we have to loop in deduped # # to check if that charecter is in there # # we dont want this # deduped = [] # for char in items: # if char not in deduped: # deduped.append(char) # return deduped # instead we can use use a set to keep track of what we have seen and use a list # to hold the final results # keep track of what we have seen seen = set() # deduped will be what we return deduped = [] for item in items: if item not in seen: deduped.append(item) seen.add(item) return deduped if __name__ == "__main__": import doctest if doctest.testmod().failed == 0: print "All tests passed!!"
############################# Merge Sort ####################################### def make_one_sorted_list(lst1, lst2): """Merge two sorted lists""" merged_list = [] while len(lst1) > 0 or len(lst2) > 0: if lst1 == []: merged_list.extend(lst2) elif lst2 == []: merged_list.extend(lst1) elif lst1[0] < lst2[0]: merged_list.append(lst1.pop(0)) else: merged_list.append(lst2.pop(0)) return merged_list ############################# Make Everything a List of One ####################################### def make_everything_a_list_of_one(lst): """Divide lists until we reach lists of length 1.""" # if the length of the list is 1, return the list # find the index of the midpoint of the list # divide the list in half and assign the other half if len(lst) < 2: print lst, return lst mid = int(len(lst) / 2) make_everything_a_list_of_one(lst[:mid]) make_everything_a_list_of_one(lst[mid:]) ########################### Merge Sort ###################################### def merge_sort(lst): """Merge sort a list and return the result.""" # break everything down into a list of one using recursion # If the length of the list is 1, return the list if len(lst) < 2: return lst # index at half of the list mid = int(len(lst) / 2) # divide the list in half lst1 = merge_sort(lst[:mid]) # assign the other half lst2 = merge_sort(lst[mid:]) return make_merge(lst1, lst2) def make_merge(lst1, lst2): """Merge the two lists""" result_list = [] print lst1, lst2 while len(lst1) > 0 or len(lst2) > 0: if lst1 == []: result_list.append(lst2.pop(0)) elif lst2 == []: result_list.append(lst1.pop(0)) elif lst1[0] < lst2[0]: result_list.append(lst1.pop(0)) else: result_list.append(lst2.pop(0)) print result_list return result_list print merge_sort([2, 1, 7, 4])
from tkinter import * '''Por ser um recurso desenvolvido para dois exercícios específicos, o número de nós e suas posições são fixas, mas nada impede de desenhar novas linhas de altura com algumas linhas a mais de código É uma pseudoárvore já que apesar de aparentar ser um grafo, não existem nós, são apenas label esteticamente organizadas sem nenhuma relação entre si. ''' #Troca os rótulos de dois nós ou adiciona uma string y ao nó x. #As variáveis r e c são de controle interno, não há necessidade de mexer nelas def Troca(x, y='', r=1, c=1): if isinstance(y, Label): aux=x['text'] x['text']=y['text'] y['text']=aux else: aux=x['text'] x['text']=str(y) y=aux cont['o']+=c if (r): log.append(('t', x, y)) print(cont) #imprime o log de ações feitas. def printf(*args): print(*args, end=' ') def l(): for f in log: LogToStr(f) def NomeDoObjeto(obj): return 'A'+str(obj)[-1] def LogToStr(k): if True: #Só para não corrigir a identação. if k[0]=='t': printf("Troca" ) printf(NomeDoObjeto(k[1]), k[1]['text']) try: printf(NomeDoObjeto(k[2]), k[2]['text'], '(obj)') except: printf(k[2], '(str)') else: printf('add') print() #Remove a raiz da árvore para uma fila. def add(): sort.append(A1['text']) #Troca(A1, lista1[-len(sort)]) Troca(A1, r=0) Troca(lista1[cont['pointer']], A1, r=0) #Troca(A1, lista1[-len(sort)]) topo['text']=sort log.append(('r', )) cont['pointer']-=1 cont['o']+=1 print(cont) #Basicamente, Ctrl+Z def z(): LastOp=log.pop() print('desfazendo ',end=' ') if LastOp[0]=='t': print('troca') Troca(LastOp[1], LastOp[2], 0, -1) else: print('add') x=sort.pop() cont['pointer']+=1 Troca(A1, lista1[cont['pointer']], 0, -1) Troca(A1, x, 0, -1) topo['text']=sort #Seria utilizado para deixar nós invisíveis, mas não foi necessário. def show(no): #pega as posições de x e y x, y = float(no.place_info()['relx']), float(no.place_info()['rely']) addy=-1 if x<1: addy=1 #está invisível x+=addy y+=addy no.place(relx=x, rely=y) #no.place('rely')+=2 #Reseta o programa def reset(): for k in range(len(lista1)): Troca(lista1[k], lista2[k], c=0) log=[] cont={'o':0, 'pointer':8} sort=[] topo['text']=sort cont={'o':0, 'pointer':8} h=0.05 janela=Tk() A1=Label(janela, text='A1') A1.place(relx=0.5, rely=0.1) #Altura 2 h+=0.2 A2=Label(janela, text='A2') A2.place(relx=0.25, rely=0.3) A3=Label(janela, text='A3') A3.place(relx=0.75, rely=0.3) #Altura 3 h+=0.3 A4=Label(janela, text='A4') A4.place(relx=1/8, rely=h) A5=Label(janela, text='A5') A5.place(relx=3/8, rely=h) A6=Label(janela, text='A6') A6.place(relx=5/8, rely=h) A7=Label(janela, text='A7') A7.place(relx=7/8, rely=h) #Altura 4 h+=0.15 A8=Label(janela, text='A8') A8.place(relx=1/16, rely=h) A9=Label(janela, text='A9') A9.place(relx=3/16, rely=h) sort=[] topo=Label(janela, bg='yellow') topo.pack(fill=X) janela.geometry('300x300+800+200') lista1=[A1, A2, A3, A4, A5, A6, A7, A8, A9] lista2=[45, 34, 78, 90, 12, 57, 80, 56, 15] log=[] reset()
#This small program proves how Numpy is much much faster than traditional python. import numpy as np import matplotlib.pyplot as plt import pandas as pd #Let us store 10 lac elements indexed from 0 to 9,99,999 in a traditional python list. my_list = list(range(1000000)) #Now we will store the same 10 lac elements in a Numpy Array and check which one is faster. my_arr = np.array(range(1000000)) #Time taken by Traditional python list %time for i in range(10): my_list2 = my_list * 2 #Time taken by Numpy array %time for i in range(10): my_arr2 = my_arr * 2 #In ML, it is heavily recommended to use Numpy data structures in place of normal python data structures.
元组(tuple) example: tuple1=12,34,'ma',890 emptyTuple=() notes: 与列表不同的是元组的元组值一旦确定就不能被修改 列表(list) example: list1=[1,2,3,4,] emptyList=[] control lists: 1.元素赋值,list[2]=45 2.删除元素,del list1[2] 3.分片操作,list_2[6:] = list("hello") 4.索引列表,list1[3] 5.循环枚举,for i in list1: print(i) Built-In-Functions:(均以list1为例说明) 1.list1.append(34)//在原列表最后添加34这个元素 2.list1.extend([34,45,456,])//可以在列表的末尾一次性添加多个元素 3.list1.count(3)//用来统计某个元素在列表中出现的次数 4.list1.index()//可以从列表中找出索引位置上元素的值 5.list1.insert(2,909)//可以从列表中找出索引位置上元素的值,在2处插入909 6.list1.pop()//用于移除列表中的一个元素,默认是最后一个,并且返回该元素的值 7.list1.remove(2)//用于移除列表中某个元组值的第一个匹配项 8.list1.reverse()//将列表中的元素逆序 9.list1.sort()//用于给列表中的元素排序,默认升序
''' infile=open("test-1.txt","r") for i in range(5): line=infile.readline() print(line[:-1]) #字典中的遍历 for key in dictionaryName: print(key+":"+str(dictionaryName[])) '''
class Solution(object): def evalRPN(self, tokens): operator=["+","-","*","/"] stack=[] for i in tokens: if i not in operator: stack.append(int(i)) else: num1=stack.pop() num2=stack.pop() if i=="+": stack.append(num2+num1) elif i=="-": stack.append(num2-num1) elif i=="*": stack.append(num2*num1) elif i=="/": if num1*num2>=0: stack.append(num2//num1) else: ans=num2//num1+1 if num2%num1!=0 else num2/num1 stack.append(ans) return stack[0] if __name__=='__main__': print(Solution().evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"])==22)
class Solution(object): def decodeString(self, s): num,char=[],[] i=0 length=len(s) while i <length: index=i+1 if s[i].isdigit(): number=int(s[i]) while index<length: if s[index].isdigit(): number=number*10+int(s[index]) index+=1 else: break num.append(number) elif s[i]=='[' or s[i].isalpha(): char.append(s[i]) else: t=char.pop() tem=[] while t!='[': tem.append(t) t=char.pop() tem_char=num.pop()*''.join(tem[::-1]) char.append(tem_char) i=index return ''.join(char) if __name__=="__main__": assert Solution().decodeString("3[a]2[bc]")=="aaabcbc" assert Solution().decodeString("3[a2[c]]")=="accaccacc"
#credit: https://github.com/ProgrammerRaj-py/Hangman/blob/master/hangman.py # Importing Libraries import random # function def hangman(winning_word, char_guessed): for i in winning_word: if i in char_guessed: print(f' {i} ', end='') else: print(' __ ', end='') print() def over(winning_word, char_guessed): counts = 0 for i in set(winning_word): if i in char_guessed: counts += 1 return counts == len(set(winning_word)) # Word words = ['promote', 'intelligent', 'facebook', 'alphabet', 'objective', 'individual', 'successful', 'character', 'otherwise', 'mountain', 'beautiful', 'processor', 'instagram', 'hamilton', 'musical'] random.shuffle(words) winning_word = random.choice(words) char_guessed = '' # main print(f'The word has {len(winning_word)} characters.\n') user_guess = input('Guess any character: ').lower()[0] counter = 1 while True: if user_guess in char_guessed: user_guess = input('Already guessed.\nGuess again: ') ''' counter = counter + 1 if counter > 3: break; ''' elif (user_guess in winning_word) and (user_guess not in char_guessed): print(f'Yes! "{user_guess}" is in the word.') char_guessed += user_guess hangman(winning_word, char_guessed) game_over = over(winning_word, char_guessed) if game_over: print(f'\nCongrats. You guessed the word "{winning_word.upper()}".') break else: user_guess = input('Guess next character: ') ''' counter = counter + 1 if counter > 3: break; ''' elif user_guess not in winning_word: print(f'Sorry. "{user_guess}" is not in the word.') user_guess = input('Guess again: ') ''' counter = counter + 1 if counter > 3: break; '''
#most credit: https://github.com/AVIGNAN18/kingdom/blob/c669ea1ffc696c79dc9f65fbf8c5303d7ef60966/rock.py from random import randint t = ['Rock','Paper','Scissors'] computer=t[randint(0,2)] player=True while player: player = input("Rock, Paper, Scissors? Type Q for quit: ") if player==computer: print("Tie!") elif player=="Rock": if computer=="paper": print("You lose!",computer,"covers",player) else: print("You win!",player,"smashes",computer) elif player=="Paper": if computer=="Scissors": print("You lose!",computer,"cut",player) else: print("You win!",player,"covers",computer) elif player=="Scissors": if computer=="Rock": print("You lose...",computer,"smashes",player) else: print("You win!",player,"cut",computer) elif player == "Q": player = False break else: print("That's not a valid play. Check your spelling!") player = True computer=t[randint(0,2)]
import pygame, math from pygame.locals import * from tetris_pieces import * pygame.init() # Colors black = (0,0,0) cyan = (0,255,255) blue = (0,0,255) orange = (255,100,10) red = (255,0,0) yellow = (255,255,0) green = (0,255,0) purple = (160,32,240) gray = (190, 190, 190) colors = [black, cyan, blue, orange, yellow, green, purple, red] # Variables for window and tiles clock = pygame.time.Clock() FPS = 60 WIDTH = 640 HEIGHT = 480 TILE_SIZE = 20 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Tetris") def draw_board(board, board_surface): for row in range(ROWS): for col in range(COLS): currentTile = board[row][col] tile_x = col * TILE_SIZE tile_y = row * TILE_SIZE draw_tile(tile_x, tile_y, currentTile, board_surface) def draw_tile(posX, posY, tile, surface): tile_color = colors[tile] rect = Rect((posX,posY), (TILE_SIZE, TILE_SIZE)) pygame.draw.rect(surface, tile_color, rect) pygame.draw.rect(surface, gray, rect.inflate(1,1),1) def draw_play_area(screen_position, screen_surface, board_surface): rows_toShow = 20.5 topY = board_surface.get_height() - rows_toShow * TILE_SIZE screen_surface.blit(board_surface,screen_position, Rect((0, topY), (board_surface.get_width(), rows_toShow * TILE_SIZE))) def draw_tetrimino(posX,posY, tetrimino, board_surface): topX = posX topY = posY rows = len(tetrimino) cols = len(tetrimino[0]) for row in range(rows): for col in range(cols): tile = tetrimino[row][col] if tile != 0: # tile is not black tileX = (topX + col) * TILE_SIZE tileY = (topY + row) * TILE_SIZE draw_tile(tileX, tileY, tile, board_surface) def calculate_drop_time(level): return math.floor(math.pow((0.8 - ((level - 1) * 0.007)), level-1) * 60) # NEW: Add locking method # Basically the same scanning method as collision check, but instead of checking collisions, we'll copy the tetrimino values over. def lock(posX, posY, grid, tetrimino): top_x, top_y = posX, posY tetrimino_height = len(tetrimino) tetrimino_width = len(tetrimino[0]) for y in range(tetrimino_height): for x in range(tetrimino_width): # No need to check blank spaces of the tetrimino. # Should never be out of bounds since we only try to lock after a collision check. tile = tetrimino[y][x] if tile != 0: grid[top_y + y][top_x + x] = tile # NEW: Add method for checking if we need to clear a line after the piece is locked into place def check_and_clear_lines(grid): lines_cleared = 0 # list to keep track of which lines we need to pull out full_lines = [] for y, line in enumerate(grid): if 0 not in line: # if there's no 0 in the line, then it's cleared lines_cleared += 1 # add to the list for later full_lines.append(y) if lines_cleared > 0: for y in full_lines: # remove the element at index y. grid.pop(y) # insert a new empty row at the top. grid.insert(0, [0 for _ in range(COLS)]) level = 1 score = 0 new_level = 5 * level drop_clock = 0 currentDropTime = baseDropTime = calculate_drop_time(level) # Variables for board ROWS = 40 COLS = 10 board = [[0 for _ in range(COLS)] for _ in range(ROWS)] board_surface = pygame.Surface((COLS*TILE_SIZE, ROWS * TILE_SIZE)) # NEW variables for locking pieces locking = False lock_clock = 0 lock_delay = 30 # Game States RESTART = -1 PLAYING = 0 GAME_OVER = 1 game_state = PLAYING # Create first tetrimino active_tetrimino = Tetrimino() active_tetrimino.grid_ref = board active_tetrimino.reset() #Game Loop while True: while game_state == PLAYING: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == KEYDOWN: if event.key == pygame.K_RIGHT: active_tetrimino.move(1,0) elif event.key == pygame.K_LEFT: active_tetrimino.move(-1,0) elif event.key == pygame.K_UP or event.key == pygame.K_x: active_tetrimino.rotate(1) elif event.key == pygame.K_z or event.key == pygame.K_RCTRL: active_tetrimino.rotate(-1) # Increase the drop clock each frame, once we pass current_drop_time, it's time to fall. drop_clock += 1 if drop_clock >= currentDropTime: move = active_tetrimino.move(0, 1) # NEW: determine if something moved and check to see if we need to lock the piece if not move: #we hit something! if not locking: locking = True lock_clock = 0 else: # no longer locking locking = False drop_clock = 0 # NEW: Locking condition / timer #Check for locking if locking: lock_clock += 1 if lock_clock >= lock_delay: lock(active_tetrimino.x, active_tetrimino.y, board, pieces[active_tetrimino.type][active_tetrimino.rotation]) drop_clock = baseDropTime active_tetrimino.reset() lock_clock = 0 locking = False check_and_clear_lines(board) screen.fill(gray) draw_board(board, board_surface) # drawing to the board draw_tetrimino(active_tetrimino.x, active_tetrimino.y, pieces[active_tetrimino.type][active_tetrimino.rotation],board_surface) draw_play_area((10,10), screen, board_surface) pygame.display.update()
# Exercício 3 - Vogais # Escreva a função vogal que recebe um único caractere como parâmetro e devolve True se ele for uma vogal e False se for uma consoante. # Dica: Lembre-se que para passar uma vogal como parâmetro ela precisa ser um texto, ou seja, precisa estar entre aspas. # Nota:10/10 def vogal(a): a = a.lower() if (a=='a' or a=='e' or a=='i' or a=='o' or a=='u'): return True else: return False
# Faça um programa que calcule o IMC de uma pessoa, mostre o IMC e uma das # mensagens abaixo de acordo com seu índice. # Resultado | Mensagem # Abaixo de 17 | Muito abaixo do peso # Entre 17 e 18,49 | Abaixo do peso # Entre 18,5 e 24,99 | Peso normal # Entre 25 e 29,99 | Acima do peso # Entre 30 e 34,99 | Obesidade I # Entre 35 e 39,99 | Obesidade II (severa) # Acima de 40 | Obesidade III (mórbida) peso='' altura='' while peso==0 or not peso.strip() or altura==0 or not altura.strip(): peso = input('Informe o seu peso: (EM KG) ') altura = input('Informe a sua altura: (EM M) ') altura = float(altura) peso = float(peso) imc = peso / (altura*altura) imc = round(imc, 2) if imc<17: print('Seu IMC é de: ', imc , ' e você está muito abaixo do peso') elif imc>=17 and imc<=18.49: print('Seu IMC é de: ' , imc , ' e você está abaixo do peso') elif imc>=18.5 and imc<=24.99: print('Seu IMC é de: ' , imc , ' e você está com o peso normal') elif imc>=25 and imc<=29.9: print('Seu IMC é de: ' , imc , ' e você está acima do peso') elif imc>=30 and imc<=34.99: print('Seu IMC é de: ' , imc , ' e você está obeso') elif imc>=35 and imc<=39.99: print('Seu IMC é de: ' , imc , ' e você está muito obeso') elif imc>=40: print('Seu IMC é de: ' , imc , ' e você está extremamente obeso') else: print('ERRO')
#!/usr/bin/python #Filename : helloworld.py ##### ##### print 'Hello World' print r'This is what??? """hahahhahah/"""' '\\ ' # i = 5 # print i # i = i + 1 # print i # s = '''This is a multi-line string. # This is the second line.''' # print s # ss = 'This is a string. \ # This continues the string.' # print ss # lenght = 5 # breadth = 2 # area = lenght * breadth # print 'Area is',area # print 'Perimeter is', 2 * (lenght + breadth) # number = 23 # if ========================================= # guess = int(raw_input('Enter an integer : ')) # if guess == number: # print 'Congratulatinos, you guessed it.' # print "(But you do not win any prizes!)" # elif guess < number: # print 'No, it is a litter higher than that' # else: # print 'No, it is a littler lower than that' # print 'Done' running = True # while ========================================= # while running: # guess = int(raw_input('Enter an integer : ')) # if guess == number: # print 'Congratulatinos, you guessed it.' # running = False # elif guess < number: # print 'No, it is a litter higher than that' # else: # print 'No, it is a littler lower than that' # else: # print 'The while loop is over.' # print 'Done' # for ========================================= # for i in range(1,10,2): # print i # else: # print 'The for loop is over.' # break, continue ========================================= # while True: # s = raw_input('Enter something : ') # if s == 'quit': # break # if len(s) < 3: # print 'Input is of sufficient lenght' # continue # else: # print 'Lenght of the string is', len(s) # print 'Done' # def sayHello(name): # print 'Hello,', name # sayHello('ning') # def printMax(a, b): # if a > b: # return a # else: # print b, 'is maximun' # printMax(2, 4) # x = 80 # y = 7 # print printMax(x, y) # def func(x): # print 'x is ', x # x = 2 # print 'Changed local x to ', x # y = 50 # func(y) # print 'x is still', y # def say(message = 'ning', times = 1): # print message * times # say() # say('fuck ', 5) # def funx(a, b = 5, c =10): # print 'a is', a, 'and b is', b, 'and c is ', c # funx(1) # funx(3,7) # funx(23, c = 38) # funx(c = 70, a = 10) def printMax(x, y): '''Prints the maximum of two numeber. The two values must be integers.''' x = int(x) y = int(y) if x > y: print x, 'is maximum' else: print y, 'is maximum' printMax(3, 5) print printMax.__doc__ # help(printMax)
# Faça um programa que leia o comprimento # do cateto oposto e do cateto adjacente # de um triângulo retângulo, calule e # mostre o comprimento da hipotenusa. from math import hypot x = float(input('Informe o valor do cateto adjacente: ')) y = float(input('Informe o valor do cateto oposto: ')) print('O valor da hipotenusa é {:.2f}.'.format(hypot(x, y)))
""" Escreva um programa que leia a velocidade de um carro Se ele ultrapassar 80km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$ 7,00 por cada KM acima do limite. It's such a shame for us to part Nobody said it was easy No one ever said it would be this hard The Scientist - Coldplay ♪♫ """ velocidade = float(input('Informe a velocidade do veículo: ')) if velocidade > 80.0: multa = (velocidade - 80) * 7 print('Você foi multado !') print('Total a pagar: R$ {:.2f}.'.format(multa)) else: print('Segue o baile !')
""" Escreva um programa que leia um número n inteiro qualquer e mostre na tela os n primeiros elementos de uma sequência de Fibonacci. Ai, amor Será que tu divide a dor Do teu peito cansado Com alguém que não vai te sarar? Ai, amor - Anavitória ♪♫ """ n = int(input('Insira o valor de n: ')) c = 2 sequence = [0, 1] if n > 2: while c < n: sequence.append( sequence[ c - 1] + sequence[c - 2] ) c += 1 print(sequence)
""" Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros termos dessa progressão. Get up on the floor Dancin' all night long Get up on the floor Dancin' till the break of dawn Get up on the floor Dancin' till the break of dawn Get up on the floor Dancin' Dancin - Aaron Smith ♪♫ """ r = int(input('Informe a razão da PA: ')) p = int(input('Informe o primeiro termo da PA: ')) for c in range(p, p + (10 * r), r): print(c)
""" Crie um programa que leia duas notas de um aluno e calcule sua méia, mostrando uma mensagem no final. m < 5 = reprovado 5 < m < 6.9 = recuperação m >= 7 = aprovado É uma índia com colar A tarde linda que não quer se pôr Dançam as ilhas sobre o mar Sua cartilha tem o A de que cor? Relicário - Nando Reis ♪♫ """ n1 = float(input('Informe a primeira nota: ')) n2 = float(input('Informe a segunda nota: ')) m = (n1 + n2) / 2 print('Média : {:.2f}'.format(m)) if m < 5: print('Reprovado !') elif m >= 5 and m < 6.9: print('Recuperação !') else: print('Aprovado !')
n = s = 0 while True: n = int(input('Digite um número: ')) if n == 9999: break s += n print(f'A somma vale {s}')
""" Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos os valores e qual foi o maior e o menor valor lido. O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores. Mas, ora Você partiu antes de mim Nem me deixou barco frágil Pr'eu me salvar do naufrágio Que foi te dar meu coração Barquinho de papel - Anavotória ♪♫ """ menu = 'S' menor = 0 maior = 0 c = 0 i = 0 somador = 0 while menu.upper() != 'N': n = int(input('Digite um número: ')) somador += n if c == 0: c += 1 menor = n if n > maior: maior = n elif n < menor: menor = n i += 1 menu = input('Deseja continuar ? [S/N]: ') print('Foram digitados {} números e a média é de {:.2f} !'.format(i, somador / i)) print('O maior número digitado foi {}'.format(maior)) print('O menor número digitado foi {}'.format(menor))
""" Já que você não está aqui O que posso fazer é cuidar de mim Quero ser feliz ao menos Lembra que o plano era ficarmos bem? Vento no Litoral - Legião Urbana ♪♫ """ nome = input('Qual é o seu nome ? ') if nome.upper() == 'MATEUS': print('Que nome bosta !') elif nome.upper() == 'PEDRO' or nome.upper() == 'MARIA' or nome.upper() == 'PAULO': print('Seu nome é bem popular !') elif nome in 'Ana Cláudia Jéssica Juliana': print('Belo nome feminino !') else: print('Nome topperson !')
# Crie um programa que leia o nome # de uma pessoa e diga se ela tem # 'SILVA' no nome. nome = input("Diga seu nome: ") print('SILVA' in nome)
'''Exercise 2: Implementing Binary Search Trees.''' from btree import BTree, BTNode class BST(BTree): '''A Binary Search Tree.''' def insert(self, value): '''Insert a new BTNode with value value into this BST. Do not insert duplicates. ''' pass def find(self, value): '''Return a BTNode from this BST that contains the value value. If there is no such BTNode in the tree, raise a NoSuchValueException. ''' pass def depth(self, value): '''Return the depth (the number of BTNodes on the root-to-node path) of a BTNode that contains the value value, in this BST. If there is no such node in this BST, raise a NoSuchValueException. ''' pass def delete(self, value): '''Delete a BTNode that contains value value from this BST. If there is no such BTNode, raise a NoSuchValueException. ''' # this one will take a bit longer :) pass class NoSuchValueException(Exception): pass if __name__ == '__main__': BT = BST(BTNode(5, BTNode(3, BTNode(2, BTNode(1), None), BTNode(4)), BTNode(6, None, BTNode(7)))) # the string shuld be '\n\t\t7\n\n\t6\n\n5\n\n\t\t4\n\n\t3\n\n\t\t2\n\n\t\t\t1\n' print(BT) print(BT.preorder()) print(BT.inorder()) print(BT.postorder()) print(BT.is_bst()) print(BT.size()) print(BT.fringe()) print(BT.height()) print(20*'=') for x in (0, 4.5, 10): BT.insert(x) print(BT) print(20*'=') for x in (0, 5, 7, 10): print('Found {}.'.format(BT.find(x))) for x in (-1, 8): try: BT.find(x) except NoSuchValueException: print('find({}) raised a NoSuchValueException.'.format(x)) print(20*'=') try: BT.find(8) except NoSuchValueException: print('find(8) raised a NoSuchValueException.') for x in (5, 3, 6, 2, 4, 7, 1, 4.5, 10, 0): print('Depth of {} is {}.'.format(x, BT.depth(x))) try: BT.depth(8) except NoSuchValueException: print('depth(8) raised a NoSuchValueException.') print(20*'=') try: BT.delete(8) except NoSuchValueException: print('delete(8) raised a NoSuchValueException.') for x in (0, 4.5, 10, 5, 2, 3, 7, 4, 6, 1): print('Removing {}...'.format(x)) BT.delete(x) print(BT) try: BT.delete(8) except NoSuchValueException: print('delete(8) raised a NoSuchValueException.')
cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() print(cars) cars.sort(reverse = True) print(cars) print(len(cars)) travels = ["Bali","Taiguo","Janpan","America","Australia"] print(travels) print(sorted(travels)) print(travels) #travels.sort() print(travels) travels.reverse() print("-----",travels)
name = "Eric" show_toast = "Hello " show_toast1 = ",would you like to learn some Python today?" show_info = show_toast + name + show_toast1 print(show_info) new_name = "meng" # 首字母大写 print(new_name.title()) # 全部大写 print(new_name.upper()) # 全部小写 print(new_name.lower()) talks = "Albert Einstein once said:" content = "'A person who never made a mistake never tried anything new.'" talks_content = talks + content print(talks_content) my_name = " \t\ndiavid " my_name1 = " fdfsf " print(my_name) # 去除后面的空格 print(my_name1.rstrip()) # 去除前面的空格 print(my_name1.lstrip()) # 去除前后的空格 print(my_name1.strip())
users = ["admin","python","java","android","html"] for user in users: print("Hello," + user) if "admin" in users: print("Hello admin, would you like to see a status report?") else: print("Hello Eric, thank you for logging in again") userss = [] if userss : for using in userss: print("hello,user:" + using) print("OK ") else: print("There is no user")
from random import randint class Die: def __init__(self, sides=6): self.sides = sides def roll_die(self, time): while time <= 10: self.sides = randint(1, 6) print("This sides is " + str(self.sides)) time += 1 my_sides = Die() my_sides.roll_die(1)
#-*- coding:UTF-8 -*- cars = ['bmw', 'audi', 'toyota', 'subaru'] #cars.sort() print(cars) # #cars.sort(reverse=True) print(cars) print(sorted(cars)) print(cars) #Ŵӡ cars.reverse() print(cars) print(len(cars)) print(cars) cars.reverse() print(cars)
class User: def __init__(self, first, last, sex): self.first = first self.last = last self.sex = sex def describe_user(self): print("The user name is " + self.first + " " + self.last + ", the sex is " + str(self.sex)) def greet_user(self): print("Hello," + self.first.title() + " " + self.last.title() + ",nice to meet you!") first = User("kobe", "bryant", "male") first.describe_user() first.greet_user() second = User("kevin", "durant", "male") second.describe_user() second.greet_user() third = User("han", "meimei", "female") third.describe_user() third.greet_user()