text
stringlengths
37
1.41M
"""Contains an representation of a question.""" class Question: """Representation of question.""" def __init__(self, relation): """ Create a question. :type relation: app.types.relation.Relation """ self.relation = relation def __eq__(self, other): """Equality check.""" if other is None: return False elif not isinstance(other, Question): return False else: return self.relation == other.relation def __ne__(self, other): """Inequality check.""" if other is None: return True elif not isinstance(other, Question): return True else: return self.relation != other.relation
import os import sys import time from to_do_list import * def clear(): """Clear the display""" os.system("cls" if os.name == "nt" else "clear") def main(): menu_choices = """ (1) Create an item (2) Display item list (3) Display item details (4) Modify item details (5) Delete item from list (6) Exit program\n """ to_do_list = [] in_menu = True while in_menu: print(menu_choices) menu_choice = input("Select an option: ") if menu_choice == "1": # clear() print("Add new item: \n") add_item_to_list(to_do_list) # clear() elif menu_choice == "2": # clear() display_list(to_do_list) elif menu_choice == "3": # clear() display_item_details(to_do_list) elif menu_choice == "4": # clear() modify_item_attirbutes(to_do_list) elif menu_choice == "5": # clear() delete_item(to_do_list) elif menu_choice == "6": sys.exit() else: # clear() print("Wrong input!") if __name__ == "__main__": main()
# Autor: Elena Itzel Ramírez Tovar # Descripcion: Calcular porcentaje de alumnos por sexo # Escribe tu programa después de esta línea. m=int(input("Ingrese el número de estudiantes de sexo masculino: ")) f=int(input("Ingrese el número de estudiantes de sexo femenino: ")) t=m+f pm=float((m*100)/t) pf=float((f*100)/t) print("Para un grupo de %d estudiantes, los porcentajes por sexo son: " %(t)) print("Femenino: %%%0.2f" %(pf)) print("Masculino: %%%0.2f" %(pm))
#!/usr/bin/env python # -*- coding: utf-8 -*- # 04. 元素記号 # "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can." # という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し, # 取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ. sentence = "Hi He Lied Because Boron Could Not Oxidize Fluorine." \ " New Nations Might Also Sign Peace Security Clause. Arthur King Can." words = {i+1: alf[0] if i+1 in (1, 5, 6, 7, 8, 9, 15, 16, 19) else alf[:2] for i, alf in enumerate(sentence.split(" "))} print words
# coding: UTF-8 # 18. 各行を3コラム目の数値の降順にソート # 各行を3コラム目の数値の逆順で整列せよ(注意: 各行の内容は変更せずに並び替えよ). # 確認にはsortコマンドを用いよ(この問題はコマンドで実行した時の結果と合わなくてもよい). f = open('../data/hightemp.txt') lines = f.readlines() f.close() for i in range(0, len(lines)): for j in range(0, len(lines)-1-i): if lines[j].split('\t')[2] < lines[j+1].split('\t')[2]: a = lines.pop([j]) lines.insert(j+1, a) for line in lines: print line,
# coding: UTF-8 # 24. ファイル参照の抽出 # 記事から参照されているメディアファイルをすべて抜き出せ. import re pattern = r"(File:([^|]*))|(ファイル:([^|]*))" repattern = re.compile(pattern) for line in open("../data/jawiki-country-uk.txt"): match = repattern.search(line) if match: print match.group(1) if match.group(3) is None else match.group(3)
import sys import random class Model(object): def __init__( self, _config = dict()): self.config = _config self.filepath = self.config["filepath"] if "filepath" in self.config else sys.exit("Filename not given") self.load_words() #self.fetch_words() def load_words( self): self.lines = dict() with open( self.filepath, "r", -1, "utf-8") as file_handle: self.lines = file_handle.readlines() self.total_words = len(self.lines) random.shuffle(self.lines) self.lines_tuple = tuple(self.lines) self.counter = -1 def fetch_words( self): if self.counter + 1 == self.total_words: return True self.counter += 1 word_indexes = [] word_indexes.append( self.counter) # Now fetch four other indexes, but don't fetch the current one.. indexes = list() for x in range(0, self.total_words): indexes.append(x) indexes.remove(self.counter) for x in range(4): idx = random.choice(indexes) word_indexes.append( idx) indexes.remove(idx) # Now we have five indexes. # The self.counter == indexes one is the correct one. # Now shuffle this list random.shuffle(word_indexes) # Now load the lines/words. # Randomly fetch N words self.selected_word_pairs = dict() # #random.shuffle(self.lines) n_words = 5 self.chosen_word_idx = self.counter for x in word_indexes: l = self.lines_tuple[x] split_l = l.split("-") self.selected_word_pairs[x] = (split_l[0].strip(), split_l[1].strip())
#Libs necessarias para fazer o banco #Especifico import sqlite3 #Geral import pandas #Import de funcoes import funcoes_gerais #variaveis globais global banco global quebrador_csv banco = "teste.db" quebrador_csv = ";" """ Criando o banco """ #Conectar o banco def contactar_banco(): #garantir que vai abrir o banco try: #Conexao return sqlite3.connect(banco) except: #Erro ao conectar ao banco, vai oa log funcoes_gerais.registrar_log_erros("Nao foi possivel conectar ao banco") contactar_banco() #Criar o banco def criar_banco(): #Tenta coenctar try: #Escolhe onde conecta conn = contactar_banco() cursor = conn.cursor() #tabela de dominios cursor.execute(""" CREATE TABLE IF NOT EXISTS dominios ( ids INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, dominios TEXT(10000) NOT NULL, Qtd INTEGER NOT NULL ); """) conn.commit() #tabela dos classificados cursor.execute(""" CREATE TABLE IF NOT EXISTS classificados ( ids INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Uri TEXT(10000) NOT NULL, Id_modelos TEXT(1000) NOT NULL, Tipo_analise_modelo TEXT(1000) NOT NULL, Tempo_medio_operacao TEXT(1000) NOT NULL, Semente_necessaria TEXT(10) NOT NULL, Aprovacao TEXT(100) NOT NULL ); """) conn.commit() #tabela de paginas cursor.execute(""" CREATE TABLE IF NOT EXISTS paginas ( ids INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Id_Ext_Dominio INTEGER NOT NULL, Url_pagina TEXT(255) NOT NULL, Endereco_IP TEXT(255) NOT NULL, Titulo_pagina TEXT(255) NOT NULL, qtd_linhas_Pagina INTERGER NOT NULL, Idioma_pagina TEXT(255) NOT NULL, Data DATETIME NOT NULL, FOREIGN KEY (Id_Ext_Dominio) REFERENCES dominios(ids) ); """) conn.commit() #Frases cursor.execute(""" CREATE TABLE IF NOT EXISTS frases ( ids INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Id_pagina_ex INTEGER NOT NULL, frases TEXT(10000) NOT NULL, Qtd INTERGER NOT NULL, FOREIGN KEY (Id_pagina_ex) REFERENCES paginas(ids) ); """) conn.commit() #Palavras cursor.execute(""" CREATE TABLE IF NOT EXISTS palavras ( ids INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Id_pagina_ex INTEGER NOT NULL, palavras TEXT(10000) NOT NULL, Qtd INTEGER NOT NULL, FOREIGN KEY (Id_pagina_ex) REFERENCES paginas(ids) ); """) conn.commit() #tags cursor.execute(""" CREATE TABLE IF NOT EXISTS tags ( ids INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Id_pagina_ex INTEGER NOT NULL, tags TEXT(10000) NOT NULL, Qtd INTEGER NOT NULL, FOREIGN KEY (Id_pagina_ex) REFERENCES paginas(ids) ); """) conn.commit() #Images cursor.execute(""" CREATE TABLE IF NOT EXISTS imagens ( ids INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Id_pagina_ex INTEGER NOT NULL, imagens TEXT(10000) NOT NULL, Qtd INTEGER NOT NULL, FOREIGN KEY (Id_pagina_ex) REFERENCES paginas(ids) ); """) conn.commit() #Videos cursor.execute(""" CREATE TABLE IF NOT EXISTS videos ( ids INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Id_pagina_ex INTEGER NOT NULL, videos TEXT(10000) NOT NULL, Qtd INTEGER NOT NULL, FOREIGN KEY (Id_pagina_ex) REFERENCES paginas(ids) ); """) conn.commit() #audio cursor.execute(""" CREATE TABLE IF NOT EXISTS audios ( ids INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Id_pagina_ex INTEGER NOT NULL, audios TEXT(10000) NOT NULL, Qtd INTEGER NOT NULL, FOREIGN KEY (Id_pagina_ex) REFERENCES paginas(ids) ); """) conn.commit() #links cursor.execute(""" CREATE TABLE IF NOT EXISTS links ( ids INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, Id_pagina_ex INTEGER NOT NULL, links TEXT(10000) NOT NULL, Qtd INTEGER NOT NULL, FOREIGN KEY (Id_pagina_ex) REFERENCES paginas(ids) ); """) conn.commit() #Modelos cursor.execute(""" CREATE TABLE IF NOT EXISTS modelos ( ids INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, nome TEXT(10000) NOT NULL, Ids_gerados TEXT(10000) NOT NULL, aprovacao TEXT(100) NOT NULL, descricao TEXT(10000) ); """) conn.commit() #Terminar as operações conn.close() #Deu errado vem para ca except: #Log funcoes_gerais.registrar_log_erros("Falha ao construir o banco") #Fechar operacoes return True """ Operacoes totais com as querys """ #Modelo select def select_banco_sem_parametros(entrada): try: conn = contactar_banco() cursor = conn.cursor() saida = cursor.execute(entrada).fetchall() conn.commit() conn.close() return saida except: funcoes_gerais.registrar_log_erros("Select sem entradas falhou") #Modelo select def select_banco_com_parametros(chamada, parametros): try: conn = contactar_banco() cursor = conn.cursor() saida = cursor.execute(chamada, parametros).fetchall() conn.commit() conn.close() return saida except: funcoes_gerais.registrar_log_erros("Select sem entradas falhou") #Modelo para outras funcoes sem paramentros def banco_sem_parametros(entrada): try: conn = contactar_banco() cursor = conn.cursor() saida = cursor.execute(entrada) conn.commit() conn.close() return saida except: funcoes_gerais.registrar_log_erros("Operacao em banco sem entradas falhou") #Modelo com paramentros def banco_com_paramentros(chamada, parametros): try: conn = contactar_banco() cursor = conn.cursor() saida = cursor.execute(chamada, parametros) conn.commit() conn.close() return saida except: funcoes_gerais.registrar_log_erros("Operacao em banco com entradas falhou") """ Funcoes para operacoes mais especificas """ #Insert de dominios def insert_banco_dominio(dominio): #Confere se o dominio ja existe registrado, se não existe, registra, e se existe, pega o valor do dominio e da insert no atual insert Id_Ext_Dominio_Existe = select_banco_nome(dominio) saida = 0 for i in Id_Ext_Dominio_Existe: saida = i if saida == 0: #Inserir o dominio caso o mesmo nao exista banco_com_paramentros("""INSERT INTO dominios (dominios, Qtd) values (?, ?);""", [dominio, 1]) else: #Atualizar a quantidade de vezes que o dominio é listado saida = select_banco_com_parametros("""SELECT ids, Qtd FROM dominios where dominios = ?;""", [dominio]) Id_Dominio = "" contador_dominio = "" for i in saida: Id_Dominio, contador_dominio = i banco_com_paramentros("""UPDATE dominios SET Qtd = ? WHERE ids = ?;""", [contador_dominio+1, Id_Dominio]) #Execute a instrução #Traz o ID do dominio saida = select_banco_nome(dominio) filtro_saida = 0 valor_saida = 0 for i in saida: filtro_saida = i for i in filtro_saida: valor_saida = i return valor_saida #Subtrair ou deletar dominio def subtrair_dominio(dominio_id): retorno_dominio = banco_com_paramentros("""select Qtd FROM dominios where ids = ?;""", dominio_id) for i in retorno_dominio: retorno_dominio = funcoes_gerais.converte_inteiro(i[0]) if retorno_dominio == 1: banco_com_paramentros("""delete from dominios where ids = ?;""", dominio_id) else: banco_com_paramentros("""UPDATE dominios SET Qtd = ? WHERE ids = ?;""", [retorno_dominio-1, dominio_id[0]]) return True """ Operacoes de select """ """ Select com parametros """ #selecionar os modelos def selecionar_modelos_analise(id_entrada): return select_banco_com_parametros("""select nome from modelos where ids = ?;""", [id_entrada]) #selecionar os modelos e sua aprovacao def selecionar_modelos_aprovados(id_entrada): return select_banco_com_parametros("""select nome, aprovacao from modelos where ids = ?;""", [id_entrada]) #selecionar os modelos e sua aprovacao def select_aprovacoes(id_entrada): return select_banco_com_parametros("""select aprovacao from modelos where ids = ?;""", [id_entrada]) #selecionar os modelos def selecionar_modelos_detalhes(id_entrada): return select_banco_com_parametros("""select * from modelos where ids = ?;""", [id_entrada]) #selecionar os modelos def selecionar_modelos_detalhes_paginas(id_entrada): return select_banco_com_parametros("""select Ids_gerados from modelos where ids = ?;""", [id_entrada]) #selecionar os modelos def select_paginas_url(id_entrada): return select_banco_com_parametros("""select Url_pagina from paginas where ids = ?;""", [id_entrada]) def select_paginas_limit(limite): return select_banco_com_parametros("""select ids from paginas order by ids desc limit ?""", [limite]) #Retorno do dominio ID via o nome do dominio def select_banco_nome(dominio): return select_banco_com_parametros("""select ids from dominios where dominios = ?;""", [dominio]) def select_varios_bancos(id_entrada, tabela): return select_banco_com_parametros("""select fr.{}, fr.Qtd from paginas as pag inner join {} as fr on pag.ids = fr.Id_pagina_ex where fr.Id_pagina_ex = ?;""".format(tabela, tabela), [id_entrada]) #Retorno via ID da página def select_banco_paginas(id_entrada): return select_banco_com_parametros("""select pag.ids, dom.dominios, pag.Url_pagina, pag.Endereco_IP, pag.Titulo_pagina, pag.qtd_linhas_Pagina, pag.Idioma_pagina, pag.data from paginas as pag inner join dominios as dom on pag.Id_Ext_Dominio = dom.ids where pag.ids = ? limit 1;""", [id_entrada]) """ Select sem parametros """ #Selecao dos modelos def select_modelos(): return select_banco_sem_parametros("""select * from modelos order by ids desc;""") #Ultimo insert de pagina no banco def select_ultimo_insert_paginas(): return select_banco_sem_parametros("""select ids from paginas order by ids desc limit 1;""") #Buscar idiomas das paginas acessadas def select_idiomas_extraidos(): return select_banco_sem_parametros("""select Idioma_pagina from paginas group by Idioma_pagina;""") #Todos os modelos ids #selecionar os modelos def selecionar_ids_modelos(): return select_banco_sem_parametros("""select ids from modelos;""") #Select tudo #Select dos extraidos def select_banco_all(): return select_banco_sem_parametros("""select * from paginas;""") #Select dos extraidos def select_banco_extraidos(): return select_banco_sem_parametros("""select paginas.ids, dominios.dominios, paginas.Url_pagina from paginas inner join dominios on paginas.Id_Ext_Dominio = dominios.ids order by paginas.ids desc limit 100;""") #Top 10 dominios mais acessados def select_count_domain(): return select_banco_sem_parametros("""select dominios, Qtd from dominios order by Qtd desc limit 10;""") #Top 10 ultimos classificados def select_count_classificados(): return select_banco_sem_parametros("""select Uri, Id_modelos, Tipo_analise_modelo, Tempo_medio_operacao, Semente_necessaria, Aprovacao from classificados order by ids desc limit 10;""") #Selecao dos modelos def select_modelos(): return select_banco_sem_parametros("""select * from modelos order by ids desc;""") #Top 10 ultimos classificados def select_count_classificados_somente_id(): return select_banco_sem_parametros("""select Id_modelos from classificados order by ids desc limit 10;""") """ Insert """ #Insert paginas classificadas def insert_pagina_classificada(uri, modelos, tipo_analise_modelo, Tempo_medio_operacao, Semente_necessaria, aprovacao): return banco_com_paramentros("""INSERT INTO classificados (Uri, Id_modelos, Tipo_analise_modelo, Tempo_medio_operacao, Semente_necessaria, Aprovacao) values (?,?,?,?,?,?);""", [uri, modelos, tipo_analise_modelo, Tempo_medio_operacao, Semente_necessaria, aprovacao]) #Insert na tabela de modelos def insert_modelos_comparativos(nome, Ids_gerados, aprovacao, descricao): return banco_com_paramentros("""INSERT INTO modelos (nome, Ids_gerados, aprovacao, descricao) values (?,?,?,?);""", [nome, Ids_gerados, aprovacao, descricao]) #Insert geral em varios bancos diferentes dependente a entrada def insert_geral_para_tabelas_secudarias(id_pagina, tabela, entrada): for i in range(0, funcoes_gerais.ler_quantidade_variavel(entrada)): banco_com_paramentros("""INSERT INTO {} (Id_pagina_ex, {}, Qtd) values (?,?,?);""".format(tabela, tabela), [id_pagina, funcoes_gerais.converte_string(entrada[i][0]), entrada[i][1]]) return True #Insert no banco def insert_banco_pagina(Id_Ext_Dominio, Url_pagina, Endereco_IP, Titulo_pagina, qtd_linhas_Pagina, Idioma_pagina, Data): Id_Ext_Dominio = insert_banco_dominio(Id_Ext_Dominio) return banco_com_paramentros("""INSERT INTO paginas (Id_Ext_Dominio, Url_pagina, Endereco_IP, Titulo_pagina, qtd_linhas_Pagina, Idioma_pagina, Data) values (?,?,?,?,?,?,?);""", [Id_Ext_Dominio, Url_pagina, Endereco_IP, Titulo_pagina, qtd_linhas_Pagina, Idioma_pagina, Data]) """ Funcoes de delet """ #Deleta um extraido da tabela def delete_banco(id_entrada): data_tuple = [id_entrada] for i in select_banco_com_parametros("""SELECT Id_Ext_Dominio FROM paginas where ids = ?;""", data_tuple): retorno_dominio = i subtrair_dominio(retorno_dominio) banco_com_paramentros("""delete from paginas where ids = ?;""", data_tuple) banco_com_paramentros("""delete from frases where ids = ?;""", data_tuple) banco_com_paramentros("""delete from palavras where ids = ?;""", data_tuple) banco_com_paramentros("""delete from tags where ids = ?;""", data_tuple) banco_com_paramentros("""delete from imagens where ids = ?;""", data_tuple) banco_com_paramentros("""delete from videos where ids = ?;""", data_tuple) banco_com_paramentros("""delete from audios where ids = ?;""", data_tuple) banco_com_paramentros("""delete from links where ids = ?;""", data_tuple) return True #Destruir modelos def destruir_modelos_classificados(): return banco_sem_parametros("""delete from modelos;""") #Deletar valor classificado def deletar_url_classificada(entrada): banco_com_paramentros("""delete from classificados where Id_modelos like ?;""", [entrada]) #Deletar todos os classificados def deletar_classificada(): banco_sem_parametros("""delete from classificados;""") #Deletar modelos #Deleta um extraido da tabela def delete_modelo_banco(id_entrada): return select_banco_com_parametros("""delete from modelos where ids = ?;""", [id_entrada]) """ Gerando os CSV's para o trabalho nos modelos """ #Listar nomes dos csvs def nomes_arquivos(): arquivos =funcoes_gerais.retorno_arquivos_diretorio("csv") ler_arquivos = [] for arquivo in arquivos: ler_arquivos.append("csv/{}".format(arquivo)) return ler_arquivos #Extracao de banco para CSV I.A def extracao_csv(modelo, dominios): #Criar diretorio para os csv's funcoes_gerais.criar_diretorio("csv") #Tabelas tabelas_bases = ["paginas", "dominios"] tabelas_secundarias = ["frases", "palavras", "tags", "imagens", "videos", "audios", "links"] tabelas_todas = tabelas_bases + tabelas_secundarias #Dominios saida_dominios = [] for i in funcoes_gerais.split_geral(dominios, "-"): if funcoes_gerais.ler_quantidade_variavel(i) != 0: saida_dominios.append(i) dominios = saida_dominios #Escrever header da tabelas nos csv's for tabela in tabelas_todas: #File CSV arquivo = "{}-{}.csv".format(modelo, tabela) arquivo_csv = open(arquivo, "a+", encoding="utf-8") #Nome das colunas colunas = [] for i in select_banco_sem_parametros("""SELECT name FROM PRAGMA_TABLE_INFO('{}');""".format(tabela)): colunas.append(i) colunas = funcoes_gerais.limpeza_header_tabelas(funcoes_gerais.converte_string(colunas), quebrador_csv) #Escrever em um arquivo arquivo_csv.write("{}\n".format(colunas)) arquivo_csv.close() #Tabela de páginas pesquisa_valores_dominios = [] for valor_id in dominios: valor_id = funcoes_gerais.split_simples(valor_id) for tabela in tabelas_bases: #Primeiro executa o pagina para ter os valores e depois executa o de dominios if tabela == "paginas": #File CSV arquivo = "{}-{}.csv".format(modelo, tabela) arquivo_csv = open(arquivo, "a+", encoding="utf-8") #Extrair valores da coluna for linhas in select_banco_com_parametros("""SELECT * FROM paginas where ids = ? limit 1;""", valor_id): saida_coluna = "" contador = 0 for coluna in linhas: arquivo_csv.write("{};".format(funcoes_gerais.converte_string(coluna))) if contador == 1: saida_coluna = funcoes_gerais.converte_string(coluna) contador = contador + 1 arquivo_csv.write("\n") #Contagem de dominios pesquisa_valores_dominios.append(saida_coluna) arquivo_csv.close() #CSV de dominios pesquisa_valores_dominios = sorted(set(pesquisa_valores_dominios)) for pesquisa_select in pesquisa_valores_dominios: pesquisa_select = funcoes_gerais.split_simples(pesquisa_select) for tabela in tabelas_bases: #Primeiro executa o pagina para ter os valores e depois executa o de dominios if tabela == "dominios": #File CSV arquivo = "{}-{}.csv".format(modelo, tabela) arquivo_csv = open(arquivo, "a+", encoding="utf-8") #Extrair valores da coluna for linhas in select_banco_com_parametros("""select * from dominios where ids = ? group by ids;""", pesquisa_select): for coluna in linhas: arquivo_csv.write("{};".format(funcoes_gerais.converte_string(coluna))) arquivo_csv.write("\n") arquivo_csv.close() #Tabela secundarias for ids in dominios: ids = funcoes_gerais.split_simples(ids) for tabela in tabelas_secundarias: arquivo = "{}-{}.csv".format(modelo, tabela) arquivo_csv = open(arquivo, "a+", encoding="utf-8") for linhas in select_banco_com_parametros("""select * from {} where Id_pagina_ex = ?;""".format(tabela), ids): for coluna in linhas: coluna = funcoes_gerais.limpeza_conteudos_tabelas(funcoes_gerais.converte_string(coluna), tabela) arquivo_csv.write("{};".format(funcoes_gerais.converte_string(coluna))) arquivo_csv.write("\n") arquivo_csv.close() #Mover csv for i in funcoes_gerais.retorno_glob_csv(): funcoes_gerais.renomear_arquivo(i) #Saida return True #Ler arquivos csvs #Limpar os arquivos para criar os modelos def gerar_modelos_csv(): #Confirmar consistencia try: arquivos_csv = nomes_arquivos() #Criar dataset's #dataset = [] for i in arquivos_csv: grupo = funcoes_gerais.split_geral(i, "-") arquivo_modelo = funcoes_gerais.split_geral(i, "/") tabelas = funcoes_gerais.split_geral(grupo[1], ".") if tabelas[0] == "dominios": atual = pandas.read_csv(i, sep=';', index_col=0) else: atual = pandas.read_csv(i, sep=';', index_col=1) #Deleta o ID do dataset das tabelas secundarias para avaliação if tabelas[0] != "paginas": atual = atual.drop('ids', axis=1) #Limpar coluna que não deve aparecer atual = atual.loc[:, ~atual.columns.str.contains('^Unnamed')] atual.to_csv("modelos/{}".format(arquivo_modelo[1]), sep=";", encoding='utf-8') except: #Log de erro funcoes_gerais.registrar_log_erros("Nao foi gerado o csv de modelos") return True """ Funcoes de destruir arquivos e diretorios """ #Destruir todas os dados das tabelas def destruir_banco_atual(): try: #Cria uma conexao para fechar o banco e dai conseguir deletar o arquivo conn = contactar_banco() conn.commit() conn.close() #Delete o arquivo caso exista funcoes_gerais.deletar_arquivo(banco) except: #Erro funcoes_gerais.registrar_log_erros("Falha ao destruir o banco") return True #Destruir modelos csv pos analise def destruir_modelos_csv(): try: funcoes_gerais.eliminar_conteudo_diretorio("csv") funcoes_gerais.destruir_diretorio("csv") except: funcoes_gerais.registrar_log_erros("Falha ao destruir diretorio CSV") return True
class Node(object): def __init__(self, data): self.data = data; self.leftChild = None; self.rightChild = None; def insert(self, data): if data < self.data: if not self.leftChild: self.leftChild = Node(data); else: self.leftChild.insert(data); else: if not self.rightChild: self.rightChild = Node(data); else: self.rightChild.insert(data); def remove(self, data, parentNode): if data < self.data: if self.leftChild is not None: self.leftChild.remove(data, self); elif data > self.data: if self.rightChild is not None: self.rightChild.remove(data, self); else: if self.leftChild is not None and self.rightChild is not None: self.data = self.rightChild.getMin(); self.rightChild.remove(self.data, self); elif parentNode.leftChild == self: if self.leftChild is not None: tempNode = self.leftChild; else: tempNode = self.rightChild; parentNode.leftChild = tempNode; elif parentNode.rightChild == self: if self.leftChild is not None: tempNode = self.leftChild; else: tempNode = self.rightChild; parentNode.rightChild = tempNode; def getMin(self): if self.leftChild is None: return self.data; else: return self.leftChild.getMin(); def getMax(self): if self.rightChild is None: return self.data; else: return self.rightChild.getMax(); def traverseInOrder(self): if self.leftChild is not None: self.leftChild.traverseInOrder(); print(self.data); if self.rightChild is not None: self.rightChild.traverseInOrder();
from string import ascii_letters class Trie_Node(object): def __init__(self): self.isWord = False self.s = {c: None for c in ascii_letters} def add(T, w, i=0): if T is None: T = Trie_Node() if i == len(w): T.isWord = True else: T.s[w[i]] = add(T.s[w[i]], w, i + 1) return T def Trie(S): T = None for w in S: T = add(T, w) return T def spell_check(T, w): assert T is not None dist = 0 while True: u = search(T, dist, w) if u is not None: return u dist += 1 def search(T, dist, w, i=0): if i == len(w): if T is not None and T.isWord and dist == 0: return "" else: return None if T is None: return None f = search(T.s[w[i]], dist, w, i + 1) if f is not None: return w[i] + f if dist == 0: return None for c in ascii_letters: f = search(T.s[c], dist - 1, w, i) if f is not None: return c + f f = search(T.s[c], dist - 1, w, i + 1) if f is not None: return c + f return search(T, dist - 1, w, i + 1)
''' Menu example ''' import sys import random import pygame # Constants FPS = 60 SCREEN_WIDTH = 1200 SCREEN_HEIGHT = 800 BTN_PADDING = 10 # How much padding are we going to put around a button? BTN_MARGIN = 10 # How much space do we want around button text? # Colors WHITE = [255, 255, 255] GREY = [175, 175, 175] BLACK = [0, 0, 5] YELLOW = [255, 229, 153] DARKER_YELLOW = [255, 217, 102] pygame.init() # As always, initialize pygame screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) clock = pygame.time.Clock() menu_font = pygame.font.SysFont('impact', 32) # Here's our button font print("Loaded the font!") screen_mode = 'title' # Modes: title, menu menu_btn_color = YELLOW menu_btn_hover_color = DARKER_YELLOW ################################################################################ # Title screen components ################################################################################ title_screen_bg_color = BLACK # === Title text === title_font = pygame.font.SysFont('impact', 128) title_surface = title_font.render('THE MENU GAME', True, WHITE) title_rect = title_surface.get_rect() title_rect.x = (SCREEN_WIDTH / 2) - (title_rect.width / 2) # Put rect in middle of screen (perfectly in middle x) title_rect.y = (SCREEN_HEIGHT / 2) - (title_rect.height) # Put rect in middle of the screen (sitting on top of horizontal midline) # === Open menu button === menu_btn_txt_surface = menu_font.render('open menu', True, BLACK) # setup open menu button background menu_btn_bg_rect = menu_btn_txt_surface.get_rect() menu_btn_bg_rect.width += 2 * BTN_MARGIN # Add some margins to the button menu_btn_bg_rect.height += 2 * BTN_MARGIN # Add margin to the button menu_btn_bg_rect.x = title_rect.midbottom[0] - (menu_btn_bg_rect.width / 2) menu_btn_bg_rect.y = title_rect.midbottom[1] + BTN_PADDING # setup text rectangle (used to determine where we'll draw text) menu_btn_txt_rect = menu_btn_txt_surface.get_rect() menu_btn_txt_rect.x = title_rect.midbottom[0] - (menu_btn_txt_rect.width / 2) menu_btn_txt_rect.y = title_rect.midbottom[1] + BTN_PADDING + BTN_MARGIN ################################################################################ # Menu screen components ################################################################################ menu_screen_bg_color = GREY menu_screen_buttons = ['resume', 'random', 'quit'] # Available buttons cur_menu_btn_id = 0 # What button are we currently on? btn_color = YELLOW # === Resume button === # Render resume btn text onto surface resume_btn_txt_surface = menu_font.render('Resume', True, BLACK) # Setup resume button background resume_btn_bg_rect = resume_btn_txt_surface.get_rect() resume_btn_bg_rect.width += 2 * BTN_MARGIN resume_btn_bg_rect.height += 2 * BTN_MARGIN resume_btn_bg_rect.x = (SCREEN_WIDTH / 2) - (0.5 * resume_btn_bg_rect.width) resume_btn_bg_rect.y = 50 # Setup the resume button text resume_btn_txt_rect = resume_btn_txt_surface.get_rect() resume_btn_txt_rect.x = resume_btn_bg_rect.x + BTN_MARGIN resume_btn_txt_rect.y = resume_btn_bg_rect.y + BTN_MARGIN # === Random button === # Render random btn text onto surface random_btn_txt_surface = menu_font.render('???', True, BLACK) # Setup random button background random_btn_bg_rect = random_btn_txt_surface.get_rect() random_btn_bg_rect.width += 2 * BTN_MARGIN random_btn_bg_rect.height += 2 * BTN_MARGIN random_btn_bg_rect.x = (SCREEN_WIDTH / 2) - (0.5 * random_btn_bg_rect.width) random_btn_bg_rect.y = resume_btn_bg_rect.y + (resume_btn_bg_rect.height + BTN_PADDING) # Setup the random button text random_btn_txt_rect = random_btn_txt_surface.get_rect() random_btn_txt_rect.x = random_btn_bg_rect.x + BTN_MARGIN random_btn_txt_rect.y = random_btn_bg_rect.y + BTN_MARGIN # === Quit button === # Render quit btn text onto surface quit_btn_txt_surface = menu_font.render('Quit', True, BLACK) # Setup quit button background quit_btn_bg_rect = quit_btn_txt_surface.get_rect() quit_btn_bg_rect.width += 2 * BTN_MARGIN quit_btn_bg_rect.height += 2 * BTN_MARGIN quit_btn_bg_rect.x = (SCREEN_WIDTH / 2) - (0.5 * quit_btn_bg_rect.width) quit_btn_bg_rect.y = random_btn_bg_rect.y + (resume_btn_bg_rect.height + BTN_PADDING) # Setup the quit button text quit_btn_txt_rect = quit_btn_txt_surface.get_rect() quit_btn_txt_rect.x = quit_btn_bg_rect.x + BTN_MARGIN quit_btn_txt_rect.y = quit_btn_bg_rect.y + BTN_MARGIN ################################################################################ # Game loop while True: # We need to show different things depending on whether or not we're in 'title' # or 'menu' mode if screen_mode == 'title': # ==== TITLE SCREEN MODE ==== screen.fill(title_screen_bg_color) # Draw the title screen # Render the title text in the middle of the screen screen.blit(title_surface, title_rect) # Draw the menu button, first: the text pygame.draw.rect(screen, menu_btn_color, menu_btn_bg_rect) screen.blit(menu_btn_txt_surface, menu_btn_txt_rect) elif screen_mode == 'menu': # === MENU SCREEN MODE === screen.fill(menu_screen_bg_color) # Draw button rectangles! # - If button is active, color background with hover color and an outline # - otherwise, draw with normal color and no outline if menu_screen_buttons[cur_menu_btn_id] == 'resume': pygame.draw.rect(screen, menu_btn_hover_color, resume_btn_bg_rect) pygame.draw.rect(screen, BLACK, resume_btn_bg_rect, 5) else: pygame.draw.rect(screen, menu_btn_color, resume_btn_bg_rect) if menu_screen_buttons[cur_menu_btn_id] == 'random': pygame.draw.rect(screen, menu_btn_hover_color, random_btn_bg_rect) pygame.draw.rect(screen, BLACK, random_btn_bg_rect, 5) else: pygame.draw.rect(screen, menu_btn_color, random_btn_bg_rect) if menu_screen_buttons[cur_menu_btn_id] == 'quit': pygame.draw.rect(screen, menu_btn_hover_color, quit_btn_bg_rect) pygame.draw.rect(screen, BLACK, quit_btn_bg_rect, 5) else: pygame.draw.rect(screen, menu_btn_color, quit_btn_bg_rect) # Layer button text over button backgrounds screen.blit(resume_btn_txt_surface, resume_btn_txt_rect) screen.blit(random_btn_txt_surface, random_btn_txt_rect) screen.blit(quit_btn_txt_surface, quit_btn_txt_rect) else: # ==== ???? MODE ==== print("AAAH UNRECOGNIZED SCREEN MODE! Exiting") pygame.quit() sys.exit() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # ===== TITLE MODE EVENTS ===== if screen_mode == 'title' and event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() if menu_btn_bg_rect.collidepoint(mouse_pos): screen_mode = 'menu' cur_menu_btn_id = 0 # ===== MENU MODE EVENTS ===== if screen_mode == 'menu' and event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: # player presses down arrow cur_menu_btn_id = (cur_menu_btn_id + 1) % len(menu_screen_buttons) if event.key == pygame.K_UP: # player presses up arrow cur_menu_btn_id = (cur_menu_btn_id - 1) % len(menu_screen_buttons) if event.key == pygame.K_RETURN: # Player presses return (selects current option) if menu_screen_buttons[cur_menu_btn_id] == 'resume': # if on resume button, go back to title screen screen_mode = 'title' elif menu_screen_buttons[cur_menu_btn_id] == 'random': # if on random ('???') button, randomize background color menu_screen_bg_color = [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)] elif menu_screen_buttons[cur_menu_btn_id] == 'quit': # if on quit button, quit the game pygame.quit() sys.exit() clock.tick(FPS) pygame.display.update()
# https://github.com/denisbalyko/checkio-solution/blob/master/friendly-number.py def friendly_number(number, base=1000, decimals=0, suffix='', powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']): """ Format a number as friendly text, using common suffixes. """ index, pow = enumerate(powers) # truncate the number, per base and decimals if number < base: return str(number) num = number / base print(num) # round the number using some unclear rule # if there are fewer digits to the right of the decimal than the decimals parameter, pad with 0s # append power and suffix num = str(num) + return str(number) #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert friendly_number(102) == '102', '102' assert friendly_number(10240) == '10k', '10k' assert friendly_number(12341234, decimals=1) == '12.3M', '12.3M' assert friendly_number(12461, decimals=1) == '12.5k', '12.5k' assert friendly_number(1024000000, base=1024, suffix='iB') == '976MiB', '976MiB'
import numpy as np from math import ceil import itertools BLACK_COLOR = "black" WHITE_COLOR = "white" # strings identifying move and boom actions MOVE_ACTION = "MOVE" BOOM_ACTION = "BOOM" # the x/y length of the board BOARD_SIZE = 8 # explosion radius ER = 1 # the starting board in a flattened byte array when positive entries are white # stacks and negative entries are black stacks BOARD_START = np.array([1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, -1, -1, 0, -1, -1, -1, -1, 0, -1, -1, 0, -1, -1], dtype=np.int8) # empty board, for debugging BOARD_EMPTY = np.zeros(BOARD_SIZE ** 2, dtype=np.int8) """ Represents a state of the game Attributes: board: a numpy byte array of length BOARD_INDEX ** 2. Each entry corresponds to a position on the board (see functions ptoi and itop) Positive entries are the players stacks, negative the opponent's stacks and Zero entries a free space. The absolute value of an entry is the height of the stack at that position. """ def to_string(s): board_2d = np.reshape(s, (BOARD_SIZE, BOARD_SIZE)) out = "" for y, row in reversed(list(enumerate(board_2d))): out += f" {y} |" for h in row: if h == 0: out += " |" elif h > 0: out += f" p{abs(h)} |" else: out += f" o{abs(h)} |" out += "\n" out += "---+" + 8 * "----+" + "\n" out += "y/x| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |\n" return out def move(s, num_tokens, si, ei, opponent): """ Returns a new state object which is the result of applying move. No validation is done. May not throw an error if move is invalid. Args: s: the board state num_tokens: the number of tokens being moved. si: the starting board index of the move ei: the ending board index of the move opponent: set to True if the oponent is making the move Returns: A new State object which is the result of executing the move on this state object. """ # opponent stacks are stored as negative values if opponent: num_tokens = -num_tokens next_state = s.copy() next_state[si] -= num_tokens next_state[ei] += num_tokens return next_state def boom(s, i): """ Returns a new state object which is the result of the token at pos exploding. No validation is done. May not throw an error if the move is invalid. Args: s: the board state i: the board index at which to boom Returns: A new State object which is the result of execting the boom on this state object. """ next_board = s.copy() to_boom = {i} while to_boom: boom = to_boom.pop() # remove piece next_board[boom] = 0 # set all token indexes (the non-zero entries of board) in radius to boom radius = boom_radius(boom) to_boom.update(radius[next_board[radius] != 0]) return next_board # ------------------------------ END GAME MOVES ----------------------------------- # # Normal Move Ordering ----------------------------- # def next_states(s, opponent, avoid=dict()): """ A generator for the states accessible from this state via valid moves. Produces the State as well as an identifier for the action taken. Args: opponent: set to True if the opponent is making the move. Yields: tuples of the form (name, state) where name is the identifier of the action and state is the State object resulting from the action. """ # get the indexes of the stacks of the player making the move stacks = np.flatnonzero(s < 0) if opponent else np.flatnonzero(s > 0) # All booms generated first for si in stacks: # Assumes that opponent also wont blow up. If it does, thats fine but dont need to generate the move. if not opponent and any(pos < 0 for pos in s[boom_radius(si)]): yield boom_name(si), boom(s, si) if opponent and any(pos > 0 for pos in s[boom_radius(si)]): yield boom_name(si), boom(s, si) # All moves generated next for si in stacks: height = abs(s[si]) for to_i in move_positions(si, height): # checks if to_i is either empty or the same color as si if s[to_i] * s[si] >= 0: # Moves generated from moving least first, to moving all last. for n in range(1, height + 1): next_state = move(s, n, si, to_i, opponent) if next_state.tobytes() not in avoid: yield move_name(n, si, to_i), next_state def move_positions(stack_i, height): """ Finds the board indexes which a stack at board index stack_i can move to Args: stack_i: a board index of the stack height: the height of the stack Returns: The board indexes which stack_i may move to """ mp = [] x0, y0 = itop(stack_i) # iterate over move distances # Moves generated from furthest first to closest last for d in range(height, 0, -1): if 0 <= y0 - d: mp.append(ptoi(x0, y0 - d)) if BOARD_SIZE > y0 + d: mp.append(ptoi(x0, y0 + d)) if 0 <= x0 - d: mp.append(ptoi(x0 - d, y0)) if BOARD_SIZE > x0 + d: mp.append(ptoi(x0 + d, y0)) return np.array(mp) # End game move ordering --------------------------------- # def move_positions_end(stack_i, height): """ Finds the board indexes which a stack at board index stack_i can move to Args: stack_i: a board index of the stack height: the height of the stack Returns: The board indexes which stack_i may move to """ mp = [] x0, y0 = itop(stack_i) # iterate over move distances # Moves generated from furthest first to closest last for d in range(height, 0, -2): if 0 <= y0 - d: mp.append(ptoi(x0, y0 - d)) if BOARD_SIZE > y0 + d: mp.append(ptoi(x0, y0 + d)) if 0 <= x0 - d: mp.append(ptoi(x0 - d, y0)) if BOARD_SIZE > x0 + d: mp.append(ptoi(x0 + d, y0)) return np.array(mp) def next_states_end(s, opponent, avoid=dict()): """ A generator for the states accessible from this state via valid moves. Produces the State as well as an identifier for the action taken. Args: s: the board state opponent: set to True if the opponent is making the move. Yields: tuples of the form (name, state) where name is the identifier of the action and state is the State object resulting from the action. """ # get the indexes of the stacks of the player making the move stacks = np.flatnonzero(s < 0) if opponent else np.flatnonzero(s > 0) # All booms generated first for si in stacks: # Assumes that opponent also wont blow up. If it does, thats fine but dont need to generate the move. if not opponent and any(pos < 0 for pos in s[boom_radius(si)]): yield boom_name(si), boom(s, si) if opponent and any(pos > 0 for pos in s[boom_radius(si)]): yield boom_name(si), boom(s, si) # All moves generated next for si in stacks: height = abs(s[si]) for to_i in move_positions_end(si, height): # checks if to_i is either empty or the same color as si if s[to_i] * s[si] >= 0: for n in range(height, 0, -1): next_state = move(s, n, si, to_i, opponent) if next_state.tobytes() not in avoid: yield move_name(n, si, to_i), next_state def is_gameover(s): return np.all(s >= 0) or np.all(s <= 0) def create_start_state(color): """ Creates the starting baord state. Args: color: the color of the player (either BLACK_COLOR or WHITE_COLOR) Returns: A State object """ if color == BLACK_COLOR: return (-1) * BOARD_START.copy() elif color == WHITE_COLOR: return BOARD_START.copy() def ptoi(x, y): """ Converts a board position to a board index """ return x + BOARD_SIZE * y def itop(i): """ Converts a board index to a board coordinate """ return (i % BOARD_SIZE, i // BOARD_SIZE) def boom_radius(i): """ Finds the board indexes which are in the radius of a boom at i Args: i: a board index Returns: A numpy array of vaid board indexes in the radius of i (excluding i) """ x0, y0 = itop(i) poss = [(x0 - 1, y0 - 1), (x0 - 1, y0), (x0 - 1, y0 + 1), (x0, y0 - 1), (x0, y0 + 1), (x0 + 1, y0 - 1), (x0 + 1, y0), (x0 + 1, y0 + 1)] return np.array([ ptoi(x, y) for x, y in poss if 0 <= x < BOARD_SIZE and 0 <= y < BOARD_SIZE ]) def move_name(num_tokens, si, ei): """ Gets the identifier for a move sending num_tokens from board index si to board index ei """ return (MOVE_ACTION, num_tokens, itop(int(si)), itop(int(ei))) def boom_name(i): """ Gets the identifier for a boom at board index i""" return (BOOM_ACTION, itop(int(i))) if __name__ == "__main__": pass
#!/usr/bin/env python3 """Planets.py: Description of how planets in solar system move. __author__ = "Liu Yuxin" __pkuid__ = "1800011832" __email__ = "1800011832@pku.edu.cn" """ import turtle wn = turtle.Screen() turtle.screensize(800, 600) wn.delay(0) def initialization(t, r, a, c, colors): # t standing for planets,r standing for radius,a standing for major semi-axis,c standing for semi focal distance t.shape("circle") t.shapesize(r, r, r) t.color(colors) t.pencolor(colors) t.penup() t.speed(0) t.setx(a+c) t.pd() def orbits(t, a, c, i, x): # i is used in the while loop t.speed(0) import math t.goto(a*(math.cos(math.pi*(i+1)/x))+c, (math.sqrt(a**2-c**2))*math.sin(math.pi*(i+1)/x)) def main(): sun = turtle.Turtle() sun.color("orange") sun.dot(7) sun.hideturtle() mercury = turtle.Turtle() venus = turtle.Turtle() earth = turtle.Turtle() mars = turtle.Turtle() jupiter = turtle.Turtle() saturn = turtle.Turtle() initialization(mercury, 0.1, 8.7, 4.2, "blue") initialization(venus, 0.2, 16.2, 0.26, "green") initialization(earth, 0.21, 22.5, 0.875, "brown") initialization(mars, 0.15, 34.2, 7.455, "red") initialization(jupiter, 0.358, 116, 13.3, "sea green") initialization(saturn, 0.303, 200, 28, "yellow") while True: for y in range(960): orbits(mercury, 8.7, 4.2, y, 60) orbits(venus, 16.2, 0.26, y, 96) orbits(earth, 22.5, 0.875, y, 120) orbits(mars, 34.2, 7.455, y, 160) orbits(jupiter, 116, 13.3, y, 240) orbits(saturn, 200, 28, y, 480) if __name__ == "__main__": main()
class Garden: plant_dict = { 'V': 'Violets', 'G': 'Grass', 'C': 'Clover', 'R': 'Radishes', } def __init__(self, garden, students=None): if students is None: students = [ 'Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny', 'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry' ] self.garden = garden self.students = sorted(students) self.garden_rows = self.garden.split('\n') def plants(self, student): student_pos = self.students.index(student) p = 2 * student_pos correct_plants = ''.join([row[p:p+2] for row in self.garden_rows]) return [Garden.plant_dict[plant] for plant in correct_plants]
Python 3.6.3 (default, Oct 3 2017, 21:45:48) [GCC 7.2.0] on linux Type "copyright", "credits" or "license()" for more information. >>> set={1,9,5,4,3} >>> print(set) {1, 3, 4, 5, 9} >>> tuple=(1,4,5,6,7) >>> print(tuple) (1, 4, 5, 6, 7) >>> list=[1,2,3,4,7] >>> print(list) [1, 2, 3, 4, 7] >>> dictionary={6:"muskan","taj":31} >>> print(dictionary) {6: 'muskan', 'taj': 31} >>> dictionary[6] 'muskan' >>> dictionary[taj] Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> dictionary[taj] NameError: name 'taj' is not defined >>> dictionary["taj"] 31 >>>
# Modules import os import csv # Set path for budget file csvpath = os.path.join('Resources', 'budget_data.csv') # Use total to calculate the Profit/Loss # Use months to count the number of months in the dataset total = 0 months = 0 sum_change = 0 previous = 0 change_values = [] # Open the CSV with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csv_header = next(csvreader) # Loop through file for row in csvreader: # Total P&L and number of months total = total + float(row[1]) months = months + 1 # Find avg change and greatest increase and decrease if months > 1: change = float(row[1]) - previous sum_change = sum_change + change change_values.append(change) # Set previous to current row P/L previous = float(row[1]) average = sum(change_values) / len(change_values) print("Financial Analysis") print("--------------------------") print(f"Total Months: {months}") print(f"Total: ${total:.0f}") print(f"Average Change: ${average:.2f}") print(f"Greatest Increase in Profits: (${max(change_values):.0f})") print(f"Greatest Decrease in Profits: (${min(change_values):.0f})") #path = os.path.join('..', 'Analysis', 'output.txt') with open('Analysis/output.txt', 'w') as txt_file: txt_file.write(f"Financial Analysis \n") txt_file.write(f"--------------------------------- \n") txt_file.write(f"Total Months: {months} \n") txt_file.write(f"Total: ${total:.0f} \n") txt_file.write(f"Average Change: ${average:.2f} \n") txt_file.write(f"Greatest Increase in Profits: (${max(change_values):.0f}) \n") txt_file.write(f"Greatest Decrease in Profits: (${min(change_values):.0f})")
#!/usr/bin/env python # coding: utf-8 # In[2]: df4=pd.read_csv('https://raw.githubusercontent.com/akhil12028/Bank-Marketing-data-set-analysis/master/bank-additional-full.csv',sep=';') df4 # In[6]: #1:read data from below ur #https://raw.githubusercontent.com/akhil12028/Bank-Marketing-data-set-analysis/master/bank-additional-full.csv import pandas as pd df4=pd.read_csv('https://raw.githubusercontent.com/akhil12028/Bank-Marketing-data-set-analysis/master/bank-additional-full.csv',sep=';') df4 # In[9]: #2 print first 5 rows df4=pd.read_csv('https://raw.githubusercontent.com/akhil12028/Bank-Marketing-data-set-analysis/master/bank-additional-full.csv',sep=';') df4[:5] # In[11]: #3: print last 2 rows df4.tail(2) # In[15]: #4:change same column names change=df4.rename(columns={'age':'Age'}) change # In[20]: #5: select a column and print its type type=df4.dtypes['age'] type # In[22]: #6. print datatype of dataset type=df4.dtypes type # In[24]: #7. check any data dats is null check=pd.isnull(df4) check # In[25]: #8. skip random rows like 20,21, and 45 df4 = pd.read_csv('https://raw.githubusercontent.com/akhil12028/Bank-Marketing-data-set-analysis/master/bank-additional-full.csv',sep=';', skiprows = [20, 21, 45]) df4
#!usr/bin/python # Write a Python program that accepts a string and calculate the number of digits and letters # Sample Data : "Python 3.2" # Expected Output : # Letters 6 # Digits 2 q=raw_input("enter your string \n") we=q.replace(" ","") print q count1=0 count2=0 count3=0 for i in q: if(i.isdigit()) : count1+=1 elif (i.isalpha()): count2+=1 else: count3+=1 print ("Letters",count2) print ("Digits",count1) print ("other special characters",count3)
def mergeArray(nums1,nums2): nums3=nums1+nums2 nums3.sort() print nums3 nums1 = [1,2,3,0,0,0] nums2 = [2,5,6] mergeArray(nums1,nums2)
class queue(object): def __init__(self): self.items=[] def isEmpty(self): return self.items==[] def firstIn(self,newElement): return self.items.insert(0,newElement) def firstOut(self): return self.items.pop() x=queue() print x.isEmpty() print x.firstIn(45) print x.firstIn(4) print x.firstIn(0,78) print x.firstOut()
def groupAnagrams(arr): dict={} result=[] for word in arr: sortedword ="".join(sorted(word)) dict.setdefault(sortedword,[]) if sortedword not in dict: dict["sortedword"] = word else: dict[sortedword].append(word) for item in dict.values(): result.append(item) return result arr= ["eat", "tea", "tan", "ate", "nat", "bat"] print groupAnagrams(arr)
#!usr/bin/python count =False def is_Sublist(a,b): a.sort() b.sort() for i in range(len(a)): for j in range(len(b)): if a[i]==b[j]: count=True else: count=False if count == True: print "Its a sublist" else: print "Its not a sublist" a=[2,4,3,5,7] b=[4,7,3,1] is_Sublist(a,b)
def longestPalindromicSubstring(string): # Write your code here longest="" for i in range(len(string)): for j in range(i,len(string)): substring=string[i:j+1] if len(substring)>len(longest) and isPalindrome(substring): longest=substring return longest def isPalindrome(substring): leftIndex=0 rightIndex=len(substring)-1 while leftIndex<rightIndex: if substring[leftIndex] != substring[rightIndex]: return False else: rightIndex-=1 leftIndex+=1 return True string="abaxyzzyx" print longestPalindromicSubstring(string)
#!/usr/bin/python # Generate a random number between 1 and 9 (including 1 and 9). # Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. import random try: n1=input("enter the number you want to guess \n") n2=input("enter the range of the random number \n") print "\n" i=random.randint(1,n2) print ("The actual random number is \n",i) if i<n1: print "guessed too high " elif i>n1: print "you guessed too low" else: print "You are correct" except: print"Check whats the error"
def climbing_stairs(n): a = b = 1 for i in range(n-1): a, b = a + b, a return a '''for i in range(2,n+2): ways[i]=ways[i-2]+ways[i-1] n=n+2 return ways[n] ''' print climbing_stairs(4)
import tkinter from tkinter.constants import* from tkinter import* import math from tkinter import messagebox #<----------Factors\\\Dont forget-----------> tk = tkinter.Tk() tk.title('Quadratic Equation') tk.maxsize(width = 550, height = 275) tk.minsize(width = 460, height = 200) frame = tkinter.Frame(tk, relief = FLAT, borderwidth= 8, bg='orange') frame.pack(fill=BOTH, expand=1) label = tkinter.Label(frame, text='This interface is for solving quadradic equation', fg='teal', underline= True) label.pack(side=TOP) frame2 = tkinter.Frame(tk, relief = FLAT, borderwidth= 10, bg='powder blue' ) frame2.pack(fill=BOTH, expand=1) ans_display = StringVar() ans_display1 = StringVar() text_a = StringVar() text_b = StringVar() text_c = StringVar() #error = StringVar() #FUNC FOR EXITING THE PROGRAM def Exit(): Exit = messagebox.askyesno('Exiting System', 'Do you want to exit from SAMSKI') if Exit > 0: tk.destroy() return #FUNC FOR BRINGING THE CALC def Go_To_Calc(): import Calculator_part_two if Go_To_Calc: tk.destroy() return #FUNC FOR BRINGING THE BIONOMIAL def Go_To_Bio(): import tkinter_f_math_bionomial if Go_To_Bio: tk.destroy() return #FUNC FOR BRINGING THE HERON'S def Go_To_Hrn(): import tkinter_f_math_herons if Go_To_Hrn: tk.destroy() return #FUNC FOR BRINGING THE MATRICE def Go_To_Mat(): import tkinter_matrice if Go_To_Mat: tk.destroy() return #CREATING A DROP DOWN FUNCTIONALITY My_Menu = Menu(tk) tk.config(menu = My_Menu) S_Menu = Menu(My_Menu) My_Menu.add_cascade(label = 'Other Functions', menu = S_Menu) CALC = S_Menu.add_command(label = 'Calculator', command = Go_To_Calc) ss_menu = Menu(S_Menu) S_Menu.add_cascade(label = 'Further Math Functions', menu = ss_menu) bio = ss_menu.add_command(label = 'Bionomial Theorem (a+x)\u00b11', command = Go_To_Bio) Heron = ss_menu.add_command(label = 'Area(Heron\'s Formula A(x1,y1), B(x2,y2), C(x3,y3))', command = Go_To_Hrn) mat = ss_menu.add_command(label = 'Matrice(3x3) Solver ', command = Go_To_Mat) S_Menu.add_separator() exit = S_Menu.add_command(label = 'Exit...', command = Exit) #--------------------------------EXCEPTIION HANDLING BLOCK------------------------------------# try: def quadratic(a,b,c): a = (a_entry.get()) b = (b_entry.get()) c = (c_entry.get()) x1= int(b)**2 x2= 4*int(a)*int(c) x3= 2*int(a) x4= -(-(int(x1)) + (int(x2))) x5= math.sqrt(x4) return (round((-(int(b)) + (x5)))/x3) #for x2 def quadratic1(a, b, c): a = (a_entry.get()) b = (b_entry.get()) c = (c_entry.get()) x6 = int(b)**2 x7 = 4*int(a)*int(c) x8 = 2*int(a) x9 = -(-(int(x6)) + (int(x7))) x10 = math.sqrt(x9) return (round((-(int(b)) - (x10)))/x8) def final(): ans_display.set(quadratic(a,b,c)) ans_display1.set(quadratic1(a,b,c)) def clear(): ans_display.set('') ans_display1.set('') text_a.set('') text_b.set('') text_c.set('') except ValueError as msg: #raise ValueError("Mistaken us........") #print('Error while solving') #m = messagebox.askretrycancel('Quadratic Error', 'An error occurred while solving.\nInput a valid Quadratic Equation') '''if m != 'Retry': tk.destroy()''' errorBox = tkinter.Label(frame2, text = msg, fg='black', relief= FLAT) errorBox.grid(sticky=E, row = 11, column = 3) print('error: %s' % (msg)) try: #------------------------------X1-----------------------------------# x1 = tkinter.Label(frame2, text='X1 = ', fg='steel blue', bg='powder blue') x1.grid(sticky=W, column=7, row=8) x1_ent = tkinter.Entry(frame2, relief=FLAT, bg = 'powder blue', fg = 'black', textvariable= ans_display) x1_ent.grid(sticky=W, column= 8, row=8) #------------------------------X2-------------------------------# x2 = tkinter.Label(frame2, text='X2 = ', fg='steel blue', bg='powder blue') x2.grid(sticky=W, column=7, row=10) x2_ent = tkinter.Entry(frame2, relief=FLAT, bg = 'powder blue', fg = 'black', textvariable= ans_display1) x2_ent.grid(sticky=W, column=8, row=10) #-------------------------------------IF ERROR----------------------------------------------------------# #error_box = tkinter.Entry(frame2, relief=FLAT, state='readonly', textvariable= error) # #error_box.grid(sticky=W, column=2, row=11) # #-----------------------------------------------------------------------------------------------# #a a = tkinter.Label(frame2, text='A : ', fg= 'teal', relief=FLAT) a.grid(column=1, row=2) a_entry = tkinter.Entry(frame2, relief=FLAT, textvariable= text_a) a_entry.grid(column=3, row=2) #b b = tkinter.Label(frame2, text='B : ', fg= 'teal', relief=FLAT) b.grid(column=1, row=3) b_entry = tkinter.Entry(frame2, relief=FLAT, textvariable= text_b) b_entry.grid(column=3, row=3) #c c = tkinter.Label(frame2, text='C : ', fg= 'teal', relief=FLAT) c.grid(column=1, row=4) c_entry = tkinter.Entry(frame2, relief=FLAT, textvariable= text_c) c_entry.grid(column=3, row=4) #answer buootn ans = tkinter.Button(frame2, text='SEE ANSWER', fg='teal', bg = 'black', relief= FLAT, command=final, activebackground = 'aqua', activeforeground = 'black') ans.grid(sticky=E) #ans.bind("<Key-Up>", quadratic,quadratic1) clear = tkinter.Button(frame2, text='CLEAR', fg='black', bg = 'teal', relief= FLAT, command=clear, activebackground = 'red', activeforeground = 'aqua') clear.grid(sticky=E, column=1, row=11) #exit btn exit = tkinter.Button(frame2, text='EXIT', fg='black', bg = 'red', relief= FLAT, command=Exit, activebackground = 'black', activeforeground = 'red') exit.grid(sticky=E, column=2, row=11) except ValueError as msg: #raise ValueError("Mistaken us........") #print('Error while solving') #m = messagebox.askretrycancel('Quadratic Error', 'An error occurred while solving.\nInput a valid Quadratic Equation') '''if m != 'Retry': tk.destroy()''' errorBox = tkinter.Label(frame2, text = msg, fg='black', relief= FLAT) errorBox.grid(sticky=E, row = 11, column = 3) print('error: %s' % (msg)) #-------------------------------------------------------# if __name__ == '__main__': mainloop()
#this will ask for user input import sys print("What is your name") name = sys.stdin.readline() print("Hello, " + name) print("Well that's cool, what did you eat") eat = sys.stdin.readline(); e = eat; if (e == "bread and beans"): print("gafsabhdgnde") else: print("nothing")
import re, tkinter, math from tkinter.constants import* from tkinter import* from tkinter import messagebox #<----------Factors\\\Dont forget-----------> tk = tkinter.Tk() tk.title('MATRICE(3x3) SOLVER') tk.maxsize(width = 585, height = 300) tk.minsize(width = 475, height = 215) frame = tkinter.Frame(tk, relief = FLAT, borderwidth= 8, bg='orange') frame.pack(fill=BOTH, expand=1) label = tkinter.Label(frame, text='This interface is for solving matrices(3x3)', fg='teal', underline= True) label.pack(side=TOP) frame2 = tkinter.Frame(tk, relief = FLAT, borderwidth= 10, bg='powder blue' ) frame2.pack(fill=BOTH, expand=1) ans_display = StringVar() ans_display1 = StringVar() ans_display2 = StringVar() eq_a = StringVar() eq_b = StringVar() eq_c = StringVar() #error = StringVar() #FUNC FOR EXITING THE PROGRAM def Exit(): Exit = messagebox.askyesno('Exiting System', 'Do you want to exit from SAMSKI') if Exit > 0: tk.destroy() return #FUNC FOR BRINGING THE CALCULATOR def Go_To_Calc(): import Calculator_part_two if Go_To_Calc: tk.destroy() return #FUNC FOR BRINGING THE BIONOMAIL def Go_To_Bio(): import tkinter_f_math_bionomial if Go_To_Bio: tk.destroy() return #FUNC FOR BRINGING THE HERON'S def Go_To_Hrn(): import tkinter_f_math_herons if Go_To_Hrn: tk.destroy() return #FUNC FOR BRINGING THE QUADRATIC def Go_To_Quad(): import tkinter_quadratic_eq if Go_To_Quad: tk.destroy() return #CREATING A DROP DOWN FUNCTIONALITY My_Menu = Menu(tk) tk.config(menu = My_Menu) S_Menu = Menu(My_Menu) My_Menu.add_cascade(label = 'Other Functions', menu = S_Menu) CALC = S_Menu.add_command(label = 'Calculator', command = Go_To_Calc) ss_menu = Menu(S_Menu) S_Menu.add_cascade(label = 'Further Math Functions', menu = ss_menu) bio = ss_menu.add_command(label = 'Bionomial Theorem (a+x)\u00b11', command = Go_To_Bio) Heron = ss_menu.add_command(label = 'Area(Heron\'s Formula A(x1,y1), B(x2,y2), C(x3,y3))', command = Go_To_Hrn) Quad = ss_menu.add_command(label = 'Quadratic Equations ax\u00b2 + bx + c', command = Go_To_Quad) S_Menu.add_separator() exit = S_Menu.add_command(label = 'Exit...', command = Exit) #--------------------------------EXCEPTIION HANDLING BLOCK------------------------------------# try: #a eqa = tkinter.Label(frame2, text='Equation A : ', fg= 'teal', relief=FLAT) eqa.grid(column=1, row=2) a_entry = tkinter.Entry(frame2, relief=FLAT, textvariable= eq_a) a_entry.grid(column=3, row=2) #b eqb = tkinter.Label(frame2, text='Equation B : ', fg= 'teal', relief=FLAT) eqb.grid(column=1, row=3) b_entry = tkinter.Entry(frame2, relief=FLAT, textvariable= eq_b) b_entry.grid(column=3, row=3) #c eqc = tkinter.Label(frame2, text='Equation C : ', fg= 'teal', relief=FLAT) eqc.grid(column=1, row=4) c_entry = tkinter.Entry(frame2, relief=FLAT, textvariable= eq_c) c_entry.grid(column=3, row=4) def matrices(): global a_entry global b_entry global c_entry eqA = str(a_entry.get()) eqB = str(b_entry.get()) eqC = str(c_entry.get()) #PATTERNS TO MATCH pattern1 = r'(?P<num1_1>\d*)(?P<letter1_1>\w).\+.(?P<num1_2>\d*)(?P<letter1_2>\w).\+.(?P<num1_3>\d*)(?P<letter1_3>\w).\=.(?P<num1_4>\d*)' pattern2 = r'(?P<num2_1>\d*)(?P<letter2_1>\w).\+.(?P<num2_2>\d*)(?P<letter2_2>\w).\+.(?P<num2_3>\d*)(?P<letter2_3>\w).\=.(?P<num2_4>\d*)' pattern3 = r'(?P<num3_1>\d*)(?P<letter3_1>\w).\+.(?P<num3_2>\d*)(?P<letter3_2>\w).\+.(?P<num3_3>\d*)(?P<letter3_3>\w).\=.(?P<num3_4>\d*)' #SEARCHES search1 = re.search(pattern1, eqA, re.S) search2 = re.search(pattern2, eqB, re.S) search3 = re.search(pattern3, eqC, re.S) #VARIABLES '''#<------For Eq1------> var1_1 = search1.group('letter1_1') var1_2 = search1.group('letter1_2') var1_3 = search1.group('letter1_3') #<------For Eq2------> var2_1 = search2.group('letter2_1') var2_2 = search2.group('letter2_2') var2_3 = search2.group('letter2_3') #<------For Eq3------> var3_1 = search3.group('letter3_1') var3_2 = search3.group('letter3_2') var3_3 = search3.group('letter3_3')''' #if search1: #print('a= %s, b= %s, c= %s' % (search1.group('num1_1'), search1.group('num1_2'), search1.group('num1_3'))) A = int(search1.group('num1_1')) B = int(search1.group('num1_2')) C = int(search1.group('num1_3')) AEquals = eq1 = int(search1.group('num1_4')) #if search2: #print('x= %s, y= %s, z= %s' % (search2.group('num2_1'), search2.group('num2_2'), search2.group('num2_3'))) D = int(search2.group('num2_1')) E = int(search2.group('num2_2')) F = int(search2.group('num2_3')) BEquals = eq2 = int(search2.group('num2_4')) #if search3: #print('p= %s, q= %s, r= %s' % (search3.group('num3_1'), search3.group('num3_2'), search3.group('num3_3'))) G = int(search3.group('num3_1')) H = int(search3.group('num3_2')) I = int(search3.group('num3_3')) CEquals = eq3 = int(search3.group('num3_4')) #Get our True Matrice First a1 = int(E*I)-(H*F) b1 = int(D*I)-(G*F) c1 = int(D*H)-(G*E) a2 = int(A*a1) b2 = int(B*b1) c2 = int(C*c1) DetOfTrueMat = a2 - b2 + c2 #Find our Ax a3 = int(E*I)-(H*F) b3 = int(eq2*I)-(eq3*F) c3 = int(eq2*H)-(eq3*E) a4 = int(eq1*a3) b4 = int(B*b3) c4 = int(C*c3) DetOfAxMat = a4 - b4 + c4 #Find our Ay a5 = int(eq2*I)-(eq3*F) b5 = int(D*I)-(G*F) c5 = int(D*eq3)-(eq2*G) a6 = int(A*a5) b6 = int(eq1*b5) c6 = int(C*c5) DetOfAyMat = a6 - b6 + c6 #Find our Az a7 = int(E*eq3)-(H*eq2) b7 = int(D*eq3)-(eq2*G) c7 = int(D*H)-(G*E) a8 = int(A*a7) b8 = int(B*b7) c8 = int(eq1*c7) DetOfAzMat = a8 - b8 + c8 x_value = round(DetOfAxMat/DetOfTrueMat, 3) y_value = round(DetOfAyMat/DetOfTrueMat, 3) z_value = round(DetOfAzMat/DetOfTrueMat, 3) return (ans_display.set('%s or %s/%s' % (x_value, DetOfAxMat, DetOfTrueMat)), ans_display1.set('%s or %s/%s' % (y_value, DetOfAyMat, DetOfTrueMat)), ans_display2.set('%s or %s/%s' % (z_value, DetOfAzMat, DetOfTrueMat))) '''class final(): matrices() def x_func(): x_value = DetOfAxMat/DetOfTrueMat return x_value def y_func(): y_value = DetOfAyMat/DetOfTrueMat return y_value def z_func(): z_value = DetOfAzMat/DetOfTrueMat return z_value''' def clear(): ans_display.set('') ans_display1.set('') ans_display2.set('') eq_a.set('') eq_b.set('') eq_c.set('') #------------------------------X1-----------------------------------# x1 = tkinter.Label(frame2, text='X = ', fg='steel blue', bg='powder blue') x1.grid(sticky=W, column=7, row=8) x1_ent = tkinter.Entry(frame2, relief=FLAT, bg = 'powder blue', fg = 'black', textvariable= ans_display) x1_ent.grid(sticky=W, column= 8, row=8) #------------------------------X2-------------------------------# x2 = tkinter.Label(frame2, text='Y = ', fg='steel blue', bg='powder blue') x2.grid(sticky=W, column=7, row=10) x2_ent = tkinter.Entry(frame2, relief=FLAT, bg = 'powder blue', fg = 'black', textvariable= ans_display1) x2_ent.grid(sticky=W, column=8, row=10) #------------------------------X3-------------------------------# x3 = tkinter.Label(frame2, text='Z = ', fg='steel blue', bg='powder blue') x3.grid(sticky=W, column=7, row=12) x3_ent = tkinter.Entry(frame2, relief=FLAT, bg = 'powder blue', fg = 'black', textvariable= ans_display2) x3_ent.grid(sticky=W, column=8, row=12) #-------------------------------------IF ERROR----------------------------------------------------------# #error_box = tkinter.Entry(frame2, relief=FLAT, state='readonly', textvariable= error) # #error_box.grid(sticky=W, column=2, row=11) # #-----------------------------------------------------------------------------------------------# #answer buootn ans = tkinter.Button(frame2, text='SEE ANSWER', fg='teal', bg = 'black', relief= FLAT, command=matrices, activebackground = 'aqua', activeforeground = 'black') ans.grid(sticky=E, column = 0, row = 11) #ans.bind("<Key-Up>", quadratic,quadratic1) clear = tkinter.Button(frame2, text='CLEAR', fg='black', bg = 'teal', relief= FLAT, command=clear, activebackground = 'red', activeforeground = 'aqua') clear.grid(sticky=E, column=1, row=11) #exit btn exit = tkinter.Button(frame2, text='EXIT', fg='black', bg = 'red', relief= FLAT, command=Exit, activebackground = 'black', activeforeground = 'red') exit.grid(sticky=E, column=2, row=11) except ValueError: raise ValueError("Mistaken us........") #print('Error while solving') m = messagebox.askretrycancel('Quadratic Error', 'An error occurred while solving.\nInput a valid Quadratic Equation') '''if m != 'Retry': tk.destroy()''' #-------------------------------------------------------# if __name__ == '__main__': mainloop()
import datetime, winsound, time #alarm_hour = input('HOUR: ') #alarm_minute = input('MINUTE: ') #alarm_second = input('SECOND: ') sound_file = "C:\\Users\\Sambou\\Desktop\\W3SCHOOLS\\gggg\\www.w3schools.com\\jsref\\horse.wav" def alarm(): for i in range(0, 10):#while(True): i = winsound.PlaySound(sound_file , 1) return i def snooze(): global snooze_min snooze_min = input('HOW MANY MINUTES\n') snooze_min = int(snooze_min) snooze_sec = snooze_min * 60 if snooze_min > 1: print('SNOOZE Set For: %s mins\n' %(snooze_min)) else: print('SNOOZE Set For: %s min\n' %(snooze_min)) time.sleep(snooze_sec) return winsound.PlaySound(sound_file, 1) '''def snooze_timeout(): try: snooze_sec = snooze_min * 60 snooze_apex = datetime.timedelta(seconds = snooze_sec) current_time = datetime.datetime.now() remaining_time = current_time - snooze_apex return remaining_time except Exception as msg: print('%s' %(msg)) ''' def SetAlarm(hours, mins, sec): print('\rALARM TIME: \r', end = '') print('\t%s:%s:%s\n' %(hours, mins, sec)) alarm_hour = hours alarm_minute = mins alarm_second = sec alert = False while(alert == False): #current_time = datetime.datetime.time(datetime.datetime.now()) setime = time.localtime() if setime.tm_hour > 12: current_hour = setime.tm_hour - 12 else: current_hour = setime.tm_hour current_minute = setime.tm_min current_second = setime.tm_sec print('%s:%s:%s' %(current_hour, current_minute, current_second)) if ( (int(current_hour) == int(alarm_hour)) and (int(current_minute) == int(alarm_minute)) and (int(current_second) == int(alarm_second)) ): print('\r\r\nIT\'S TIME\r\r\n') alarm() while(True): option = input('DO YOU WANT TO SNOOZE(y/Y or n/N)\n') if option == 'y' or option == 'Y': snooze() else: alert = True break else: #print(current_time) time.sleep(1) print('not time\n') ''' from socket import socket, AF_INET, SOCK_STREAM sock = socket(AF_INET, SOCK_STREAM) sock.connect(('localhost', 5000)) msg = input('What is your name: ') sock.send(bytes(msg, 'UTF-8')) sock.recv(8192) '''
#----------------------------------------Solving Logical Questions---------------------------------------# import re print("\t\t\tThis Interface Solves logical Questions\n\t\t\tIf you wish to Exit, Just Type 'Quit'") class Solver(): def __init__(self,num_one, num_two): self.num_one = num_one self.num_two = num_two while(True): ques_logic = input("Enter Your Question In Full:\n\n") if (ques_logic == "Quit"): print("You Just Exit from Sam.App") print("Have a nice day") break else: #patterns to be matched pattern_1 = r'(\w+)(?P<num_one>\W+)([-]|([a][n][d]))(?P<num_two>\W+)(\w+)?' pattern_2 = r'(.+)(?P<num_one_2>\W+)(.+)(?P<num_two_2>\W+)(.+)?' #additional stuff searches in other not to raise errors or exceptions search = re.search(pattern_1, ques_logic) other_form = re.search(pattern_2, ques_logic) if search: num_1 = int(search.group('num_one')) num_2 = int(search.group('num_two')) for i in range(num_1,num_2): i += 1 if (i % 7) == 0: print(i) elif other_form: num_3 = int(other_form.group('num_one_2')) num_4 = int(other_form.group('num_two_2')) for i in range(num_3,num_4): i += 1 if (i % 7) == 0: print(i) else: print("Incorrect Format!!!") print("Good Day") def main(Solver): Solver()
# Program to display file pointer after reading two lines # Created by: Siddhartha # Created on: 1st April 2020 fileName = "files/story.txt" # open file in read mode Fn = open(fileName, 'r') # read two lines one by one for iter in range(2): Fn.readline() # print the position of pointer print("Position of pointer {}".format(Fn.tell())) Fn.close()
# Program to count no. of you and me in a text file # Created by: Siddhartha # Created on: 1st April 2020 # Function to count me def Me(file): count = 0 for line in file.readlines(): # removing escape seq. and converting to lower case line = line.lower().strip().split(" ") # Counting number of me count += line.count("me") file.seek(0) # return count return count # Same as above function but for counting you def You(file): count = 0 for line in file.readlines(): line = line.lower().strip().split(" ") count += line.count("you") file.seek(0) return count # Driver function to open file and process it def main(fileName, mode): with open(fileName, mode) as file: no_of_you = You(file) no_of_me = Me(file) yield no_of_you yield no_of_me if __name__ == "__main__": fileName = input('Enter the file path: ') mode = 'r' list_output = list(main(fileName, mode)) print('number of you: {} and me: {}'.format( list_output[0], list_output[1] ) )
fim = int( input( "digite seu número aqui: ")) x = 3 while x <= fim: print (x) x = x + 3
print( "Olá, seja bem vindo") print( "Digite dois numeros inteiros e saiba sua soma!") numero1 = int(input("digite o primeiro número:")) numero2 = int(input("digite o segundo número:")) soma = ( numero1 + numero2) print (" o resultado da soma é: ", soma)
print(" Saiba se você tomou multa ou não!!") velocidade = int( input( "Digite a sua velocidade aqui: ")) if velocidade > 80: print (" Você tomou uma multa de R$5,00! ") else: print (" Você não tomou multa!")
print("Digite o preço de uma mercadoria e seu desconto para saber quanto você irá pagar!") mercadoria = int( input( "Digite o preço da mercadoria aqui: ")) percentual = int (input(" Digite o percentual do desconto aqui: ")) desconto = mercadoria * percentual /100 precoFinal = mercadoria - desconto print( "Você vai pagar: " , precoFinal)
print ( ' Saiba quantos dias de vida um fumante perde!!') cigarros = int(input(' Digite o numero de cigarros fumados por dia: ')) anos = int(input(' Agora digite a qantidade de anos fumados: ')) dias = anos * 365 diasCigarro = cigarros * 10 / 1440 diasPerdidos = dias * diasCigarro print ( ' O numero de dias perdidos por esse fumante foi: ', diasPerdidos)
idade = int( input( "Digite a idade do seu carro aqui: ")) if idade <= 3: print ("Seu carro é novo!!") else: print (" Seu carro é velho!!")
""" * Author :Ravindra * Date :12-11-2020 * Time :15:30 * Package:BasicCorePrograms * Statement:Computes the prime factorization of N using brute force. """ class PrimeFactors: number=0 def __init__(self,number): """Constructor Definition """ self.number=number def calculatePrimeFactors(self): """Method Definition Operation:Calculate Prime Factors of given number, input taken from user :return: Does not return any value """ for i in range(2,self.number): while self.number%i==0: print("Prime Factor Of that Number ",i) self.number=self.number/i if number>2: print(number) if __name__ == '__main__': """Mai mehod call """ while True: try: numberValue=int(input("please Enter number Value ")) p1=PrimeFactors(numberValue) p1.calculatePrimeFactors() break except ValueError: print("OOPs"" Plz Enter Valide Number ")
""" * Author :Ravindra * Date :18-11-2020 * Time :19:10 * Package:Functional Programs * Statement:A library for reading in 2D arrays of integers, doubles, or booleans from standard input and printing them out to standard output. """ class TwoDArray: def inputArrayParameters(self): """ Method Definition Operation:Taking input for 2d array from user for number of rows and columns and all elements in array :return:does not return any value """ while True: try: numberOfColumns = int(input("Enter number of columns: ")) numberOfRows = int(input("Enter number of rows: ")) if (numberOfColumns or numberOfRows) <= 0: print("number of columns and rows should be one or above ") continue break except ValueError: print("Opps You enter wrong input plz enter in digit and not zero") self.array = [] for column in range(numberOfColumns): rowElements = [] for row in range(numberOfRows): while True: try: element = int(input("Enter element in array: ")) rowElements.append(element) break except ValueError: print("Opps you enter wrong input plz enter in digit only ") self.array.append(rowElements) def printArray(self): """ Method definition Operation:printing array :return:does not return any value """ print(self.array) if __name__ == "__main__": """Main method""" twoDArray =TwoDArray() twoDArray.inputArrayParameters() twoDArray.printArray()
# filter(func, iterable) def has_o(string): return 'o' in string.lower() words = ['One', 'two', 'three', '23Fkjsf'] filtered_list = list(filter(has_o, words)) print('filtered_list:', filtered_list) lambda_filtered_list = list(filter(lambda string: 'o' in string.lower(), words)) print('lambda_filtered_list:', lambda_filtered_list) comp_list = [string for string in words if has_o(string)] print('comp_list:', comp_list)
def Ceacar_encrypt(P,offset): C = "" for i in range(len(P)): if not P[i].isalpha(): C += " " C += chr(ord(P[i])+offset) return C def Ceacar_decrypt(C, offset): P = "" for i in range(len(C)): if not C[i].isalpha(): P += " " P += chr(ord(C[i])-offset) return P Plaintext="abcdefghijklmnopqrstuvwxyz" Cipertext=Ceacar_encrypt(Plaintext, 3) print(Cipertext) print(Ceacar_decrypt(Cipertext,3))
h = int(input("введиет часы: ")) m = int(input("введите минуты: ")) s = int(input("введте секунды: ")) print("суммарное число секунд: " ,str(h * 3600 + m * 60 + s))
#!/usr/bin/python3 import sys class Parser: def __init__(self, file_path): with open(file_path, "r") as f: self.file = f.readlines() self.current_command = None self.index = -1 def hasMoreCommands(self): return (self.index + 1) in range(len(self.file)) def advance(self): ## use this function only if hasMoreCommands line = self.file[self.index+1].strip() while (len(line) == 0 or line[0] == "/"): self.file.pop(self.index + 1) line = self.file[self.index+1].strip() if line.find("/") >= 0: self.current_command = line[0:line.find("/")].strip() else: self.current_command = line.strip() if self.current_command is not None and \ len(self.current_command) > 0 and \ self.commandType() != "L_COMMAND": self.index = self.index + 1 else: self.file.pop(self.index + 1) return def commandType(self): assert self.current_command is not None and len(self.current_command) > 0 if self.current_command[0] == "@": return "A_COMMAND" elif self.current_command[0] == "(": return "L_COMMAND" else: return "C_COMMAND" def symbol(self): assert self.commandType() == "A_COMMAND" or \ self.commandType() == "L_COMMAND" if self.current_command[0] == "@": return self.current_command[1:] else: return self.current_command[1:(len(self.current_command)-1)] def dest(self): assert self.commandType() == "C_COMMAND" pos_colon = self.current_command.find(";") pos_equal = self.current_command.find("=") if pos_equal > 0: return self.current_command[0:pos_equal] else: return "null" def comp(self): assert self.commandType() == "C_COMMAND" pos_colon = self.current_command.find(";") pos_equal = self.current_command.find("=") if pos_equal > 0: pos_start = pos_equal + 1 else: pos_start = 0 if pos_colon > 0: pos_end = pos_colon else: pos_end = len(self.current_command) return self.current_command[pos_start:pos_end] def jump(self): assert self.commandType() == "C_COMMAND" pos_colon = self.current_command.find(";") pos_equal = self.current_command.find("=") if pos_colon > 0: return self.current_command[(pos_colon+1):] else: return "null" class Code: def __init__(self): self.comp_table = { # left col # right col "0" : "0"+"101010", "1" : "0"+"111111", "-1" : "0"+"111010", "D" : "0"+"001100", "A" : "0"+"110000", "M" : "1"+"110000", "!D" : "0"+"001101", "!A" : "0"+"110001", "!M" : "1"+"110001", "-D" : "0"+"001111", "-A" : "0"+"110011", "-M" : "1"+"110011", "D+1": "0"+"011111", "A+1": "0"+"110111", "M+1": "1"+"110111", "D-1": "0"+"001110", "A-1": "0"+"110010", "M-1": "1"+"110010", "D+A": "0"+"000010", "D+M": "1"+"000010", "D-A": "0"+"010011", "D-M": "1"+"010011", "A-D": "0"+"000111", "M-D": "1"+"000111", "D&A": "0"+"000000", "D&M": "1"+"000000", "D|A": "0"+"010101", "D|M": "1"+"010101" } self.dest_table = { "null": "000", "M" : "001", "D" : "010", "MD" : "011", "A" : "100", "AM" : "101", "AD" : "110", "AMD": "111" } self.jump_table = { "null": "000", "JGT" : "001", "JEQ" : "010", "JGE" : "011", "JLT" : "100", "JNE" : "101", "JLE" : "110", "JMP" : "111" } return def dest(self, mnemonic): return self.dest_table["".join([e for e in mnemonic if e != " "])] def comp(self, mnemonic): return self.comp_table["".join([e for e in mnemonic if e != " "])] def jump(self, mnemonic): return self.jump_table["".join([e for e in mnemonic if e != " "])] class SymbolTable: def __init__(self): self.table = {("R"+str(i)): i for i in range(16)} self.table["SCREEN"] = 16384 self.table["KBD"] = 24576 self.table["SP"] = 0 self.table["LCL"] = 1 self.table["ARG"] = 2 self.table["THIS"] = 3 self.table["THAT"] = 4 return def addEntry(self, symbol, address): self.table[symbol] = address return def contains(self, symbol): return symbol in self.table def getAddress(self, symbol): return self.table[symbol] def main(): file_name = sys.argv[1] # Initialization parser = Parser(file_name) symbol_table = SymbolTable() code = Code() # First Pass while parser.hasMoreCommands(): parser.advance() if parser.commandType() == "L_COMMAND": symbol_table.addEntry(parser.symbol(), parser.index+1) # Restart reading and translating commands # Main Loop: # Get the next Assembly Language Command and parse it # For A-commands: Translate symbols to binary addresses # For C-commands: get code for each part and put them together # Output the resulting machine language command parser = Parser(file_name) n = 16 new_file_name = file_name.split(".asm")[0] + ".hack" with open(new_file_name, 'w') as f: f.write("") f = open(new_file_name, "a") while parser.hasMoreCommands(): parser.advance() if parser.commandType() == "A_COMMAND": if symbol_table.contains(parser.symbol()): f.write("0"+f"{symbol_table.getAddress(parser.symbol()):015b}"+"\n") else: if parser.symbol().isnumeric(): f.write("0"+f"{int(parser.symbol()):015b}"+"\n") else: symbol_table.addEntry(parser.symbol(), n) f.write("0"+f"{n:015b}"+"\n") n = n + 1 elif parser.commandType() == "C_COMMAND": f.write("111" + \ code.comp(parser.comp()) + \ code.dest(parser.dest()) + \ code.jump(parser.jump()) + \ "\n") f.close() return if __name__ == "__main__": main()
if {}: print "hi" d = {"maggie": "uk", "ronnie": "usa"} d.items() #items returns [('maggie', 'uk'), ('ronnie', 'usa')] i.e. the contents of the dictionary in their paired tuples d.keys() #keys returns ['maggie', 'ronnie'] d.values() #values returns ['uk', 'usa'] d.get("maggie", "nowhere") #returns uk d.get("ringo", "nowhere") #returns nowhere res = d.setdefault("mikhail", "ussr") print res, d["mikhail"] #returns ussr ussr
forward = [] backward = [] values = ["a", "b", "c"] for item in values: forward.append(item) backward.insert(0, item) print "forward is:", forward print "backward is:", backward forward.reverse() print forward ==backward
a = set([0, 1, 2, 3, 4, 5]) b = set([2, 4, 6, 8]) print a.union(b) #union means show all the elements in both sets as one list but each element appears only once print a.intersection(b) #intersection shows which elements appear in both sets
s = 'I love to write Python' split_s = s.split() #unless told otherwise it assumes split by spaces, if want to split commans then need x.split(',') print split_s for word in split_s: if word.find("i") > -1: #if not there gives -1, here we're saying if it's more than -1 then it's true it's there print "I found 'i' in: '{0}'".format(word) #outputs gives i in 'write' if 'i' in word: print "I found 'i' in '{0}'".format(word)
class Word_Pair: def __init__(self, german_word, english_word): assert (type(german_word) == str and type(english_word) == str) self.german = german_word self.english = english_word def __str__(self): return ("Word_Pair(\'" + self.german + "\', \'" + self.english + "\')") def Generate_Vocab_List(): vocab_list = [] while True: new_german_word = raw_input('German word: ') if new_german_word == "DONE": break new_english_word = raw_input('English translation: ') if new_english_word == "DONE": break new_pair = Word_Pair(new_german_word, new_english_word) vocab_list = vocab_list + [str(new_pair)] print str(vocab_list).replace('\"', '') # remove all double quotes from around Word_Pair() in the printed output; this will format it properly for pasting directly into chapter vocab list
import turtle turtle.setup(800,600) # Set the width and height be 800 x 600 number_of_divisions = 8 # The number of subdivisions around the centre turtle_width = 3 # The width of the turtles # Don't show the animation turtle.tracer(False) # Draw the background lines backgroundTurtle = turtle.Turtle() backgroundTurtle.width(1) backgroundTurtle.down() backgroundTurtle.color("gray88") # Draw the centered line for i in range(number_of_divisions): backgroundTurtle.forward(500) backgroundTurtle.backward(500) backgroundTurtle.left(360 / number_of_divisions) backgroundTurtle.up() # Show the instructions backgroundTurtle.color("purple") backgroundTurtle.goto(-turtle.window_width()/2+50, 100) backgroundTurtle.write("""s - change a colour for one of the colour buttons m - all 8 drawing turtles go to middle c - clear all drawings made by the 8 drawing turtles """, font=("Arial", 14, "normal")) backgroundTurtle.hideturtle() # Set up a turtle for handling message on the turtle screen messageTurtle = turtle.Turtle() # This sets the colour of the text to red messageTurtle.color("red") # We do not want it to show/draw anything, except the message text messageTurtle.up() # Set it the be at center, near the colour selections messageTurtle.goto(0, -200) # We do not want to show it on the screen messageTurtle.hideturtle() # Part 2 Preparing the drawing turtles # The drawing turtles are put in a list allDrawingTurtles = [] # Part 2.1 Add the 8 turtles in the list for _ in range(number_of_divisions): temp = turtle.Turtle() temp.speed(0) temp.width(turtle_width) temp.hideturtle() allDrawingTurtles.append(temp) # Part 2.2 Set up the first turtle for drawing dragTurtle = allDrawingTurtles[0] dragTurtle.shape("circle") dragTurtle.shapesize(2) dragTurtle.showturtle() # Part 3 Preparing the basic drawing system def draw(x, y): dragTurtle.ondrag(None) turtle.tracer(False) messageTurtle.clear() dragTurtle.goto(x, y) x_transform = [1, 1, -1, -1, 1, 1, -1, -1] # This represents + + - - + + - - y_transform = [1, -1, 1, -1, 1, -1, 1, -1] # This represents + - + - + - + - for i in range(1, number_of_divisions): if i < 4: new_x = x * x_transform[i] # x with sign change new_y = y * y_transform[i] # y with sign change else: new_x = y * y_transform[i] # Note that we assign y as new x new_y = x * x_transform[i] # Note that we assign x as new y allDrawingTurtles[i].goto(new_x, new_y) turtle.tracer(True) dragTurtle.ondrag(draw) dragTurtle.ondrag(draw) # Part 5.2 clear all drawings made by the 8 drawing turtles def clearDrawing(): for c in allDrawingTurtles: c.clear() messageTurtle.clear() messageTurtle.write("The screen is cleared", \ align="center", font=("Arial", 14, "normal")) turtle.onkeypress(clearDrawing, 'c') # Part 5.3 all 8 drawing turtles go to middle def goToMiddle(): for c in allDrawingTurtles: c.up() c.goto(0, 0) c.down() messageTurtle.clear() messageTurtle.write("All 8 turtles returned to the middle", \ align="center", font=("Arial", 14, "normal")) turtle.onkeypress(goToMiddle, 'm') # Part 4 handling the colour selection # Here is the list of colours colours = ["black", "orange red", "lawn green", "medium purple", "light sky blue", "orchid", "gold"] # Part 4.2 Set up the onclick event def handleColourChange(x, y): if x <= -130: for m in range(len(allDrawingTurtles)): allDrawingTurtles[m].color(colours[0]) elif x <= -80: for m in range(len(allDrawingTurtles)): allDrawingTurtles[m].color(colours[1]) elif x <= -20: for m in range(len(allDrawingTurtles)): allDrawingTurtles[m].color(colours[2]) elif x <= 30: for m in range(len(allDrawingTurtles)): allDrawingTurtles[m].color(colours[3]) elif x <= 80: for m in range(len(allDrawingTurtles)): allDrawingTurtles[m].color(colours[4]) elif x <= 130: for m in range(len(allDrawingTurtles)): allDrawingTurtles[m].color(colours[5]) elif x <= 180: for m in range(len(allDrawingTurtles)): allDrawingTurtles[m].color(colours[6]) # Part 5.4 change a colour in the colour selection def changeColour(): index = turtle.textinput( \ "Change colour", \ "Please enter the index number for the turtle(0-6)") if index != None: while (int(index)<0 or int(index)>6): messageTurtle.clear() messageTurtle.write("Wrong Input", \ align="center", font=("Arial", 14, "normal")) index = turtle.textinput( \ "Change colour", \ "Please enter the index number for the turtle(0-6)") col = turtle.textinput( \ "Change colour", \ "Please enter the colour you want to use") if col != None: colours[int(index)] = col colourSelectionTurtles[int(index)].color(col) messageTurtle.clear() messageTurtle.write("The colour is set and can be used", \ align="center", font=("Arial", 14, "normal")) turtle.listen() turtle.onkeypress(changeColour, 's') # Part 4.1 Make the colour selection turtles colourSelectionTurtles = [] for i in range(len(colours)): temp = turtle.Turtle() temp.color(colours[i]) temp.shape("square") temp.shapesize(2, 2) temp.up() temp.goto(-150 + (i*50), -250) temp.down() temp.onclick(handleColourChange) colourSelectionTurtles.append(temp) turtle.tracer(True) turtle.listen() turtle.done()
import matplotlib.pyplot as plt import pandas as pd # from PIL import Image # age = [5,10,15,20,25,30] # height = [30, 45, 100, 120,150,180] # plt.plot(age,height, color='red', alpha=0.5) # plt.xlabel('age') # plt.ylabel('height') # plt.title('My Growth') # plt.show() # Puppy behavior thoroughout the day # pup_pic = Image.open('http://e2ua.com/data/wallpapers/203/WDF_2411532.jpg') # pup_pic.show() # puppy_ranking= [7.5, 6, 2, 5.5, 6.8, 9, 8] # plt.plot(puppy_ranking, alpha=0.75, color='fuchsia') # plt.title('Puppy Behavior throughout the day') # plt.xlabel('Times throughout the day') # plt.ylabel('Puppy Behavior Score') # plt.show() # shows = ['Scandal', 'Real Housewives', 'Catfish', 'Teen Mom'] # ranking = [2,1,3,4] # x = [1,2,3,4] # plt.barh(x, ranking, align='center', xerr=0.2, color='green', alpha=0.5) # plt.yticks(x, shows) # plt.ylabel('Who likes TV?') # plt.axis([0,5, 0,5]) # plt.text(3, 2, 'When does the Bachelor start?') # plt.show() text = u'&#10084' test = str(text) print text import matplotlib.pyplot as plt import pandas as pd df = {'name': ['Amndaa', 'Lauren H.', 'Lauren B.', 'JoJo'], 'job': ['Nutrition', 'Teacher', 'Flight Attendant', 'Flipper'], 'age': [25, 26, 27, 28], 'max_week':[4, 8, 12, 12]} bach = pd.DataFrame(df, columns=['name', 'job', 'age', 'max_week']) print bach plt.scatter(bach['age'], bach['max_week'], marker=('5, 1, 0)', color ='purple', alpha = 0.75, s=300) # plt.set_markersize(5) plt.xlabel('age') plt.ylabel('Week They Lasted To') plt.text(27, 4, 'hey, gurl!') plt.show()
""" 结果一定在S中,因此我们没有必要把S展开再求。而且这样做(当测试样例"y959q969u3hb22odq595")会出现内存溢出的现象。因此可以想办法在原始S中求第K为,1.算出展开S的长度为N,2所求位置为k%S。因此倒序遍历S,遇见数字d,N=N/d,遇见字母N=N-1;直到K%N==0。输出此处字符 """ class Solution: def decodeAtIndex(self, S, K): """ :type S: str :type K: int :rtype: str """ length = 0 for ch in S: if ch.isdigit(): length *= int(ch) else: length += 1 for ch in reversed(S): K %= length if K == 0 and ch.isalpha(): return ch if ch.isdigit(): length /= int(ch) else: length -= 1
import queue class Solution: def slidingPuzzle(self, board): """ :type board: List[List[int]] :rtype: int """ goal = "123450" start = "" for i in range(0, len(board)): for j in range(0, len(board[0])): start += str(board[i][j]) dir = [[1, 0], [0, 1], [-1, 0], [0, -1]] visited = set() visited.add(start) pathQueue = queue.Queue() pathQueue.put((start, 0)) while not pathQueue.empty(): curPath, curStep = pathQueue.get() if curPath == goal: return curStep index0 = curPath.index("0") path = list(curPath) x, y = int(index0/3), index0%3 for pair in dir: tx = x + pair[0] ty = y + pair[1] if tx < 0 or tx >= 2 or ty < 0 or ty >= 3: continue path[int(tx*3+ty)], path[int(x*3+y)] = path[int(x*3+y)], path[int(tx*3+ty)] pathStr = "".join(path) if pathStr not in visited: pathQueue.put((pathStr, curStep+1)) visited.add(pathStr) path[int(tx*3+ty)], path[int(x*3+y)] = path[int(x*3+y)], path[int(tx*3+ty)] return -1
import os import csv from typing import Text #paths to csv os.chdir(os.path.dirname(os.path.realpath(__file__))) bank_data_cvs= os.path.join("Resources", "budget_data.csv") #reads csv with open(bank_data_cvs, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter=",") header = next(csvreader) file = open(bank_data_cvs) reader = csv.reader(file) header = next(reader) # Constants total_months = 0 prev_revenue = 0 month_of_change = [] revenue_change_list = [] greatest_increase = ["", 0] greatest_decrease = ["", 9999999999999] total_revenue = 0 DATE_COL = 0 REVENUE_COL = 1 # Calcuating the number of months, and total renevue in the period. for row in reader: total_months = total_months + 1 total_revenue = total_revenue + int(row[REVENUE_COL]) # Greatest increase and decrease. revenue_change = int(row[REVENUE_COL]) - prev_revenue prev_revenue = int(row[REVENUE_COL]) revenue_change_list = revenue_change_list + [revenue_change] month_of_change = month_of_change + [row[DATE_COL]] if (revenue_change > greatest_increase[1]): greatest_increase[0] = row[DATE_COL] greatest_increase[1] = revenue_change if (revenue_change < greatest_decrease [1]): greatest_decrease[0] = row[DATE_COL] greatest_decrease[1] = revenue_change # Calculating the average change. revenue_avg = sum(revenue_change_list) / total_months #Print out Data: output =( "\nFinancial Analysis\n" "\n-------------------\n" f"Total Months: {total_months}\n" f"Total Revenue: {total_revenue}\n" f"Average Change: {revenue_avg}\n" f"Greatest Increase in Revenue: {greatest_increase[0]} ${greatest_increase[1]}\n" f"Greatest Decrease in Revenue: {greatest_decrease[0]} ${greatest_decrease[1]}\n" ) print(output) # open the output file, create a header row, and then write the text file file_output = os.path.join("financial_analysis.txt") with open(file_output, "w") as textfile: textfile.write(output)
""" 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。 函数能提高应用的模块性,和代码的重复利用率。 python 内置: print函数 type函数 input函数 open函数 函数的分类: 参数 返回值 有参 有返回值 有参 无返回值 无参 有返回值 无参 无返回值 函数的定义: def 函数名(参数,参数1,参数2=默认值): 函数代码块 [return] """ # 求和 有参有返回值 def add(a,b): return a+b # 求和 有参无返回值 def printAdd(a,b): print(a+b) # 无参有返回值 def getStr(): return "Hello World!!" # 无参无返回值 def printGood(): print("好好学习 天天向上!!") if __name__ == '__main__': print(add(10,20)) printAdd(100,200) print(getStr()) printGood()
import os import sqlite3 import pandas as pd # Save the filepath for the DB to a variable DB_FILEPATH = os.path.join(os.path.dirname(__file__), "rpg_db.sqlite3") # Intanstiate the connection connection = sqlite3.connect(DB_FILEPATH) # print("CONNECTION:", connection) # Instantiate the cursor cursor = connection.cursor() # print("CURSOR:", cursor) # Question 1: How many total characters are there? query = """ SELECT count(distinct character_id) as character_count FROM charactercreator_character """ result = cursor.execute(query).fetchone() print("How many total characters are there?", result[0]) # Question 2: How many of each specific subclass? charachter_types_items = ['charactercreator_mage', 'charactercreator_thief', 'charactercreator_cleric', 'charactercreator_fighter'] subclasses = ['mage','thief','cleric','fighter'] print("How many of each specific subclass?") i = 0 for items in charachter_types_items: subclass_query = f""" SELECT count(distinct character_ptr_id) as subclass_count FROM {items} """ subclass_result = cursor.execute(subclass_query).fetchone() print(f"There are {subclass_result[0]} charcters of subclass {subclasses[i]}") i += 1 # Question 3: How many total items item_query = """ SELECT count(distinct item_id) as item_count FROM armory_item """ item_result = cursor.execute(item_query).fetchone() print("How many total items are there?", item_result[0]) # Question 4: How many of the items are weapons? How many are not? weapon_query = """ SELECT count(distinct item_ptr_id) as weapon_count FROM armory_weapon """ weapon_result = cursor.execute(weapon_query).fetchone() print(f"In all the items, there are {weapon_result[0]} weapons and {item_result[0]-weapon_result[0]} non-weapons") # Question 5: How many items does each character have? print("How many items does each character have? (First 20 Rows") char_item_query = """ SELECT character_id ,count(distinct item_id) as item_count FROM charactercreator_character_inventory GROUP BY character_id LIMIT 20 """ char_item_result = cursor.execute(char_item_query).fetchall() char_item_df = pd.DataFrame(char_item_result, columns = ['Character_ID','Item_Count']) char_item_df = char_item_df.set_index('Character_ID') print(char_item_df) # Question 6: How many weapons does each character have? (First 20 rows) # print("How many weapons does each character have? (First 20 rows)") char_weapon_query = """ SELECT c.character_id ,c.name as char_name ,count(inv.item_id) as item_count ,count(w.item_ptr_id) as weapon_count FROM charactercreator_character c LEFT JOIN charactercreator_character_inventory inv ON inv.character_id = c.character_id LEFT JOIN armory_weapon w on inv.item_id = w.item_ptr_id GROUP BY c.character_id -- row per what? LIMIT 20 """ char_weapon_result = cursor.execute(char_weapon_query).fetchall() char_weapon_df = pd.DataFrame(char_weapon_result, columns=['charachter_id', 'char_name', 'item_count', 'weapon_count']) char_weapon_df.set_index('charachter_id') print(char_weapon_df) # Question 7: On average, how many items does each character have? print("On average, how many items does each character have?") ch_avg_items_query = """ SELECT character_id ,count(distinct item_id) as item_count FROM charactercreator_character_inventory GROUP BY character_id """ avg_char_item_result = cursor.execute(ch_avg_items_query).fetchall() avg_char_item_df = pd.DataFrame(avg_char_item_result, columns = ['Character_ID','Item_Count']) avg_char_item_df = avg_char_item_df.set_index('Character_ID') avg_char_item = avg_char_item_df['Item_Count'].mean() print(f"The average item count is {avg_char_item:,.2f}") # Question 8: On average, how many weapons does each chararacter have print("On average, how many weapons does each character have?") print(char_weapon_df['weapon_count'].mean())
import itertools from typing import Iterable, Iterator, List, Optional, Tuple, TypeVar T = TypeVar('T') def window(iterator: Iterable[T], behind: int = 0, ahead: int = 0) -> Iterator[Tuple[Optional[T], ...]]: """ Sliding window for an iterator. Example: >>> for prev, i, nxt in window(range(10), 1, 1): >>> print(prev, i, nxt) None 0 1 0 1 2 1 2 3 2 3 None """ # TODO: move into utils iters: List[Iterator[Optional[T]]] = list(itertools.tee(iterator, behind + 1 + ahead)) for i in range(behind): iters[i] = itertools.chain((behind - i) * [None], iters[i]) for i in range(ahead): iters[-1 - i] = itertools.islice( itertools.chain(iters[-1 - i], (ahead - i) * [None]), (ahead - i), None ) return zip(*iters)
# Run this script and enter 3 numbers separated by space # example input '5 5 5' a,b,c=map(int,raw_input().split()) for i in range(b+c+1):print(' '*(c-i)+((' /|'[(i>c)+(i>0)]+'_'*4)*(a+1))[:-4]+('|'*(b+c-i))[:b]+'/')[:5*a+c+1]
""" 7.4 – Ingredientes para uma pizza: Escreva um laço que peça ao usuário para fornecer uma série de ingredientes para uma pizza até que o valor 'quit' seja fornecido. À medida que cada ingrediente é especificado, apresente uma mensagem informando que você acrescentará esse ingrediente à pizza. """ while True: ingrediente = input("Digite um ingrediente, 'quit' para sair: ").strip() if ingrediente == "quit": print("Obrigado!") break print(f"Ingrediente {ingrediente} acrescentado à pizza.\n")
""" 8.13 – Perfil do usuário: Comece com uma cópia de user_profile.py, da página 210. Crie um perfil seu chamando build_profile(), usando seu primeiro nome e o sobrenome, além de três outros pares chave-valor que o descrevam. """ def build_profile(first_name, last_name, **user_info): """Constrói um dicionário contendo tudo que sabemos sobre um usuário.""" profile = {} profile['first_name'] = first_name profile['last_name'] = last_name for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('Thiago', 'Souza', age=31, profession='Developer') print(user_profile)
""" 4.12 – Mais laços: Todas as versões de foods.py nesta seção evitaram usar laços for para fazer exibições a fim de economizar espaço. Escolha uma versão de foods.py e escreva dois laços for para exibir cada lista de comidas """ my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] my_foods.append('cannoli') friend_foods.append('ice cream') print("minhas comidas favoritas são:") for food in my_foods: print(f" {food}") print("\nAs comidas favoritas de meu amigo são:") for food in friend_foods: print(f" {food}")
""" 5.3 – Cores de alienígenas #1: Suponha que um alienígena acabou de ser atingido em um jogo. Crie uma variável chamada alien_color e atribua-lhe um alor igual a 'green', 'yellow' ou 'red'. • Escreva uma instrução if para testar se a cor do alienígena é verde. Se for, mostre uma mensagem informando que o jogador acabou de ganhar cinco pontos. • Escreva uma versão desse programa em que o teste if passe e outro em que ele falhe. (A versão que falha não terá nenhuma saída.) """ alien_color = 'green' if alien_color == 'green': print("Você acabou de ganhar 5 pontos!") if alien_color == 'yellow': pass if alien_color == 'green': print('Você acertou!')
""" 6.4 – Glossário 2: Agora que você já sabe como percorrer um dicionário com um laço, limpe o código do Exercício 6.3 (página 148), substituindo sua sequência de instruções print por um laço que percorra as chaves e os valores do dicionário. Quando tiver certeza de que seu laço funciona, acrescente mais cinco termos de Python ao seu glossário. Ao executar seu programa novamente, essas palavras e significados novos deverão ser automaticamente incluídos na saída. """ glossario = { 'string': 'conjunto de caracteres numa determinada ordem.', 'variavel': 'são elementos que armazenam algum tipo de valor.', 'codigo de maquina': 'Código que a máquina consegue entender e executar.', 'bug': 'Problema no código que faz com que ele não execute sua função corretamente.', 'algoritmo': 'Conjunto de passos para execução de uma tarefa.' } for palavra, significado in glossario.items(): print(f"{palavra.capitalize()}: {significado.capitalize()}\n") # Adicionar mais 5 palavras com seu significado e executar novamente o laço.
""" 7.10 – Férias dos sonhos: Escreva um programa que faça uma enquete sobre as férias dos sonhos dos usuários. Escreva um prompt semelhante a este: Se pudesse visitar um lugar do mundo, para onde você iria? Inclua um bloco de código que apresente os resultados da enquete. """ enquete = {} participantes = 0 while True: if not participantes: participar = input("Deseja participar da enquete [s/n]: ").strip()[0] else: participar = input("Deseja continuar participando da enquete [s/n]: ").strip()[0] if participar not in 'sn': print("Opção inválida, digite s ou n\n") continue if participar == "n": break nome = input("Digite seu nome: ").strip() resposta = input("Se pudesse visitar um lugar do mundo, para onde você iria?: ").strip() enquete[nome] = resposta participantes += 1 if participantes: print("\nResultado da enquete:") for nome, resposta in enquete.items(): print(f" {nome.title()}: {resposta.title()}") print(f"\nTotal de partipiantes: {participantes}") else: print("\nA enquete não teve participantes")
""" 8.11 – Mágicos inalterados: Comece com o trabalho feito no Exercício 8.10. Chame a função make_great() com uma cópia da lista de nomes de mágicos. Como a lista original não será alterada, devolva a nova lista e armazene-a em uma lista separada. Chame show_magicians() com cada lista para mostrar que você tem uma lista de nomes originais e uma lista com a expressão o Grande adicionada ao nome de cada mágico. """ def make_great(magicians): for i in range(0, len(magicians)): magicians[i] = f'O Grande {magicians[i]}' return magicians def show_magicians(magicians): for magician in magicians: print(magician) names_magicians = ['David Copperfield', 'Lance Burton', 'David Blaine', 'Derren Brown'] names_magicians_changed = make_great(names_magicians[:]) show_magicians(names_magicians) print() show_magicians(names_magicians_changed)
""" 5.9 – Sem usuários: Acrescente um teste if em hello_admin.py para garantir que a lista de usuários não esteja vazia. • Se a lista estiver vazia, mostre a mensagem Precisamos encontrar alguns usuários! • Remova todos os nomes de usuário de sua lista e certifique-se de que a mensagem correta seja exibida. """ users = ['erik', 'jose', 'admin', 'maria', 'joana'] if users: for user in users: if user == 'admin': print("Olá admin, gostaria de ver um relarório de status?") else: print(f"Olá {user.capitalize()}, obrigado por fazer login novamente.") else: print("Precisamos encontrar alguns usuários!") print() users = [] if users: for user in users: if user == 'admin': print("Olá admin, gostaria de ver um relarório de status?") else: print(f"Olá {user.capitalize()}, obrigado por fazer login novamente.") else: print("Precisamos encontrar alguns usuários!")
""" 4.10 – Fatias: Usando um dos programas que você escreveu neste capítulo, acrescente várias linhas no final do programa que façam o seguinte: • Exiba a mensagem Os três primeiros itens da lista são: Em seguida, use uma fatia para exibir os três primeiros itens da lista desse programa. • Exiba a mensagem Três itens do meio da lista são:. Use uma fatia para exibir três itens do meio da lista. • Exiba a mensagem Os três últimos itens da lista são:. Use uma fatia para exibir os três últimos itens da lista. """ # Criando uma lista com valores no intervalo [1, 20] numeros = list(range(1, 21)) print(f"Os três primeiros itens da lista são: {numeros[0:3]}") print(f"Três itens do meio da lista são: {numeros[8:11]}") print(f"Os três últimos itens da lista são: {numeros[-3:]}")
""" 10.1 – Aprendendo Python: Abra um arquivo em branco em seu editor de texto e escreva algumas linhas que sintetizem o que você aprendeu sobre Python até agora. Comece cada linha com a expressão Em Python podemos.... Salve o arquivo como learning_python.txt no mesmo diretório em que estão seus exercícios deste capítulo. Escreva um programa que leia o arquivo e mostre o que você escreveu, três vezes. Exiba o conteúdo uma vez lendo o arquivo todo, uma vez percorrendo o objeto arquivo com um laço e outra armazenando as linhas em uma lista e então trabalhando com ela fora do bloco with. """ filename = 'learning_python.txt' # # Lendo o arquivo todo # with open(filename, encoding='UTF-8') as file_object: # lines = file_object.read() # print(lines) # # Percorrendo o objeto arquivo com um laço # with open(filename, encoding='UTF-8') as file_object: # for line in file_object: # print(line.strip()) # percorrendo o objeto arquivo com um laço e outra armazenando as linhas em uma lista with open(filename, encoding='UTF-8') as file_object: lines = file_object.readlines() for line in lines: print(line.strip())
""" 10.13 – Verificando se é o usuário correto: A última listagem de remember_me.py supõe que o usuário já forneceu seu nome ou que o programa está executando pela primeira vez. Devemos modificá-lo para o caso de o usuário atual não ser a pessoa que usou o programa pela última vez. Antes de exibir uma mensagem de boas-vindas de volta em greet_user(), pergunte ao usuário se seu nome está correto. Se não estiver, chame get_new_username() para obter o nome correto. """ import json def get_stored_username(): """Obtém o nome do usuário já armazenado se estiver disponível.""" filename = 'username.json' try: with open(filename) as file_object: username = json.load(file_object) except FileNotFoundError: return None else: return username def get_new_username(): """Pede um novo nome de usuário""" username = input('Qual é o seu nome?: ').strip() filename = 'username.json' with open(filename, 'w') as file_object: json.dump(username, file_object) return username def greet_user(): """Saúda o usuário pelo nome.""" username = get_stored_username() if username: print(f'Último visitante: {username}') confirm = input('Este usuário é você [s/n]: ').strip().lower()[0] while confirm not in 'sn': print('\nOpção inválida, tente novamente.') print(f'Último visitante: {username}') confirm = input('Este usuário é você [s/n]: ').strip().lower()[0] if confirm == 's': print(f'Bem vindo de volta, {username}!') else: username = get_new_username() print(f'Nós vamos lembrá-lo quando você voltar, {username}!') else: username = get_new_username() print(f'Nós vamos lembrá-lo quando você voltar, {username}!') greet_user()
""" 6.8 – Animais de estimação: Crie vários dicionários, em que o nome de cada dicionário seja o nome de um animal de estimação. Em cada dicionário, inclua o tipo do animal e o nome do dono. Armazene esses dicionários em uma lista chamada pets. Em seguida, percorra sua lista com um laço e, à medida que fizer isso, apresente tudo que você sabe sobre cada animal de estimação. """ pets = [ { 'lion': { 'tipo': 'gato', 'idade': '3 anos' } }, { 'tony': { 'tipo': 'cachorro', 'idade': '2 anos' } }, { 'Louro': { 'tipo': 'papagaio', 'idade': '5 anos' } } ] for pet in pets: for name, data in pet.items(): print(f'Nome: {name.capitalize()}') for field, value in data.items(): print(f'{field.capitalize()}: {value.capitalize()}') print()
""" 10.8 – Gatos e cachorros: Crie dois arquivos, cats.txt e dogs.txt. Armazene pelo menos três nomes de gatos no primeiro arquivo e três nomes de cachorro no segundo arquivo. Escreva um programa que tente ler esses arquivos e mostre o conteúdo do arquivo na tela. Coloque seu código em um bloco try-except para capturar o erro FileNotFound e apresente uma mensagem simpática caso o arquivo não esteja presente. Mova um dos arquivos para um local diferente de seu sistema e garanta que o código no bloco except seja executado de forma apropriada. """ file_cats = 'cats.txt' file_dogs = 'dogs.txt' try: with open(file_cats) as file_object: names_cats = file_object.readlines() except FileNotFoundError: print(f'Desculpe, o arquivo {file_cats} não foi encontrado.') else: print('\nOs nomes dos gatos são:') for cat in names_cats: print(cat.strip()) print() try: with open(file_dogs) as file_object: names_dogs = file_object.readlines() except FileNotFoundError: print(f'Desculpe, o arquivo {file_dogs} não foi encontrado.') else: print('Os nomes dos cachorros são:') for dog in names_dogs: print(dog.strip()) print()
""" BirdsEyeTransformation.py This program converts the input video into a “bird’s eye” output video. It converts a frame into the bird’s eye transformation, so that the road is rectangular Give path to directory with images as input after running the program @author: Anushree Das (ad1707) """ import cv2 as cv from os import path import numpy as np def canny_edge_detector(image): # Convert the image color to grayscale gray_image = cv.cvtColor(image, cv.COLOR_RGB2GRAY) # Reduce noise from the image blur = cv.GaussianBlur(gray_image, (5, 5), 0) canny = cv.Canny(blur, 50, 150) return canny def region_of_interest(image): height = image.shape[0] polygons = np.array([ [(200, height), (1100, height), (550, 250)] ]) mask = np.zeros_like(image) # Fill poly-function deals with multiple polygon cv.fillPoly(mask, polygons, 255) # Bitwise operation between canny image and mask image masked_image = cv.bitwise_and(image, mask) return masked_image def create_coordinates(image, line_parameters): # print(line_parameters) slope, intercept = line_parameters y1 = image.shape[0] y2 = 0 x1 = int((y1 - intercept) / slope) x2 = int((y2 - intercept) / slope) return np.array([x1, y1, x2, y2]) def average_slope_intercept(image, lines): left_fit = [] right_fit = [] for line in lines: x1, y1, x2, y2 = line.reshape(4) # It will fit the polynomial and the intercept and slope parameters = np.polyfit((x1, x2), (y1, y2), 1) slope = parameters[0] intercept = parameters[1] if slope < 0: left_fit.append((slope, intercept)) else: right_fit.append((slope, intercept)) left_fit_average = np.average(left_fit, axis=0) right_fit_average = np.average(right_fit, axis=0) left_line = create_coordinates(image, left_fit_average) right_line = create_coordinates(image, right_fit_average) return np.array([left_line, right_line]).astype('uint32') def processVideo(filename): print('Processing video..', filename) # Create a capture object cap = cv.VideoCapture(cv.samples.findFileOrKeep(filename)) cap.set(cv.CAP_PROP_POS_FRAMES, 0) found = False # get coordinates of center lane to warp it later while not found: ret,frame = cap.read() # get edges canny_image = canny_edge_detector(frame) # keep only white lines of center lane cropped_image = region_of_interest(canny_image) # get coordinates for white lines of center lane lines = cv.HoughLinesP(cropped_image, 2, np.pi / 180, 100, np.array([]), minLineLength=40, maxLineGap=5) # if more than one line found if lines is not None and len(lines)>1: # extend the white lines of center lane to cover complete lane and get left and right line coordinates averaged_lines = average_slope_intercept(frame, lines) x1l, y1l, x2l, y2l = averaged_lines[0] x1r, y1r, x2r, y2r = averaged_lines[1] found = True # reset video cap.set(cv.CAP_PROP_POS_FRAMES, 0) # Read until video is completed or 500 frames are processed while True: # if video file successfully open then read frame from video if (cap.isOpened): # to store list of frames to select brightest of them ret, frame = cap.read() # exit when we reach the end of the video if ret == 0: break width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT)) warped_img = birdsEyeTransformation(frame, width, height, x1l, y1l, x2l, y2l,x1r, y1r, x2r, y2r) cv.imshow('video', warped_img) if cv.waitKey(1) & 0xFF == ord('q'): break # close the video file cap.release() # destroy all the windows that is currently on cv.destroyAllWindows() def birdsEyeTransformation(frame, width, height, x1l, y1l, x2l, y2l,x1r, y1r, x2r, y2r): # the corners of the polygon created by lane edges src = np.float32([[x2r, y2r], [x2l, y2l],[x1l, y1l],[x1r, y1r] ]) # the corners of rectangle to which the previous polygon should be mapped to dst = np.float32([[x2r, y2r], [x2l, y2l],[x2l, y1l],[x2r, y1r] ]) # the transformation matrix M = cv.getPerspectiveTransform(src, dst) # bird’s eye transformation warped_img = cv.warpPerspective(frame, M, (width, height) ) # Image warping # resize image to quarter of the resolution dim = (int(0.25*width), int(0.25*height)) resized = cv.resize(warped_img, dim, interpolation=cv.INTER_AREA) return resized def main(): # filename = 'road_videos/MVI_2201_CARS_ON_590_FROM_BRIDGE.MOV' # filename = 'road_videos/MVI_2207_CARS_ON_590_FROM_BRIDGE.MOV' # filename = 'road_videos/MVI_2208_CARS_ON_590_FROM_BRIDGE.MOV' # list of video formats ext = [".mov"] # take filename or directory name from user filename = input('Enter filepath:') if path.exists(filename): _, file_extension = path.splitext(filename) if file_extension.lower() in ext: processVideo(filename) else: print("File isn't supported") else: print("File doesn't exist") if __name__ == "__main__": main()
#!/usr/bin/env python # Module import sys import sys def celsius_to_fahr(temp_c): temp_f=temp_c* (9.0/5.0) +32 return temp_f def main() try: cels=float(sys.argv[1]) print(celsious_to_fahr(cels)) except: print("First argument must ne a number! if _name_ ="_main_") print('hello') print('These are the arguments: ',sys.argv) print('This is the first arguments: ',sys.argv[0]) print('This is the first arguments: ',sys.argv[1])
y = 1 num = int(input('Enter you number--')) for x in range(1,num+1): y=y*x print('factorial of '+ str(num) +' is ='+ str(y))
# Importing libraries import cv2 # Deffining a function for detecting motion def imageDifference(x,y,z): # Taking difference between frames image1=cv2.absdiff(x,y) image2=cv2.absdiff(y,z) # Calculating differences in two frames finalDifference=cv2.bitwise_and(image1,image2) # Returning the frame with difference return finalDifference # Create a object of VideoCapture # Use 0 if using the camera of laptop else 1 capture=cv2.VideoCapture(0) # Taking 3 consistant frames frame1=capture.read()[1] frame2=capture.read()[1] frame3=capture.read()[1] # Converting them into grayscale gray1=cv2.cvtColor(frame1,cv2.COLOR_BGR2GRAY) gray2=cv2.cvtColor(frame2,cv2.COLOR_BGR2GRAY) gray3=cv2.cvtColor(frame3,cv2.COLOR_BGR2GRAY) # Starting a infinite loop while capture.isOpened(): # Passing arguments to above function image_difference=imageDifference(gray1,gray2,gray3) # Showing the fame with difference in 2 consecutive frames cv2.imshow('Difference',image_difference) # Capturing new frame status,frame=capture.read() # Showing the live video which is captured by the camera cv2.imshow("Normal",frame) # Swaping the frames with each other gray1=gray2 gray2=gray3 gray3=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) # Writing code to close the windows if cv2.waitKey(1) & 0xFF == ord('q'): break # destroying all the opened windows cv2.destroyAllWindows() capture.release()
names = ['zhangyang','guyun','guozi','helloworld'] print(names) # 查 print(names[0]) print(names[1]) print(names[2]) print(names[1:3]) # 顾头不顾尾 切片 print(names[0:4]) # 顾头不顾尾 切片 print(names[:4]) # 顾头不顾尾 切片 names.append('leihaidong') print(names[-3:-1]) print(names[-3:]) print(names) # 增 names.insert(1,'insert') print(names) # 改 names[2]='xiedi' print(names) # 删除 names.remove('helloworld') print(names) del names[0] print(names) names.pop() print(names) names.pop(1) print(names) ##### print(names.index('insert')) names.insert(1,'insert') print(names) print(names.count('insert')) # 查数目 names.reverse() # 翻转 print(names) names.reverse() # 翻转 print(names) names.sort() print(names) names2 = [1,2,3,4] names.extend(names2) print(names) print(names2) print(names) names.clear() names2.append([1,2,3]) names3 = names2.copy() print(names3) print(names2) names2[2] = 99 names2[4][0]= 77 print(names3) print(names2) import copy names3 =copy.deepcopy(names2) # 深克隆
reply = int(input()) if reply % 3 == 0 and reply % 5 == 0: print("FizzBuzz") elif reply % 3 == 0: print("Fizz") elif reply % 5 == 0: print("Buzz") else: print("")
class Time: # Конструктор, принимающий четыре целых числа: часы, минуты, секунды и миллисекунды. # В случае, если передан отрицательный параметр, вызвать исключение ValueError. # После конструирования, значения параметров времени должны быть корректными: # 0 <= GetHour() <= 23 # 0 <= GetMinute() <= 59 # 0 <= GetSecond() <= 59 # 0 <= GetMillisecond() <= 999 def __init__(self, hours=0, minutes=0, seconds=0, milliseconds=0): if (hours < 0) or (minutes < 0) or (seconds < 0) or (milliseconds < 0): raise ValueError('Wrong init') else: self.hours = hours self.minutes = minutes self.seconds = seconds self.milliseconds = milliseconds def GetHour(self): return self.hours def GetMinute(self): return self.minutes def GetSecond(self): return self.seconds def GetMillisecond(self): return self.milliseconds # Прибавляет указанное количество времени к текущему объекту. # После выполнения этой операции параметры времени должны остаться корректными. def Add(self, time): self.milliseconds += time.GetMillisecond() seconds = 0 if self.milliseconds > 999: seconds = int(self.milliseconds / 1000) self.milliseconds %= 1000 self.seconds += time.GetSecond() + seconds minutes = 0 if self.seconds > 59: minutes = int(self.seconds / 60) self.seconds %= 60 self.minutes += time.GetMinute() + minutes hours = 0 if self.minutes > 59: hours = int(self.minutes / 60) self.minutes %= 60 self.hours += time.GetHour() + hours self.hours %= 24 # Операторы str и repr должны представлять время в формате # HH:MM:SS.ms def __str__(self): return (str(self.GetHour())).zfill(2) + ':' + (str(self.GetMinute())).zfill(2) + ':' + (str(self.GetSecond()).zfill(2)) + '.' + str(self.GetMillisecond())
import pandas as pd import numpy as np def get_catecorials(data, drop_features=None): """Get categorical data from a dataset Input ===== """ features = np.setdiff1d(data.columns.tolist(), drop_features).tolist() # Which one are objects types data_objects = data[features].loc[:, data.dtypes == object] categorial_features = [] for feat in data_objects.columns.tolist(): values = pd.unique(data_objects[feat]) values = values[pd.notnull(values)] # Don't need to use the Bool with missing values tmp = np.setdiff1d(values, [True, False]) # There is no need to keep the features with only one unique value if len(tmp) > 0: categorial_features.append(feat) return categorial_features def get_dummies(data_categorial): """Convert categorials to dummies """ df_dummies = pd.DataFrame() for feat in data_categorial.columns.tolist(): df = pd.get_dummies(data_categorial[feat], dummy_na=True, prefix=feat) df_dummies = pd.concat([df_dummies, df], axis=1) return df_dummies
# Function to calculate the minimum # number of elements to be removed # satisfying the conditions def minimumDeletions(arr, N): # Stores the final answer ans = 0 # Map to store frequency # of each element mp = {} # Traverse the array arr[] for i in arr: mp[i] = mp.get(i,0)+1 # Traverse the array arr[] for i in range(N): # Stores whether current # element needs to be # removed or not flag = 0 # Iterate over the range # [0, 30] for j in range(31): # Stores 2^j pw = (1 << j) # If 2^j -arr[i] equals # to the arr[i] if i >= len(arr): break if (pw - arr[i] == arr[i]): # If count of arr[i] # is greater than 1 if (mp[arr[i]] > 1): flag = 1 break # Else if count of 2^j-arr[i] # is greater than 0 elif (((pw - arr[i]) in mp) and mp[pw - arr[i]] > 0): flag = 1 break # If flag is 0 if (flag == 0): ans += 1 # Return ans return -1 if ans == N else ans # Driver Code if __name__ == '__main__': arr= [1, 2, 3, 4, 5, 6] N = len(arr) print (minimumDeletions(arr, N)) arr1= [1, 5, 10, 25, 50] N = len(arr) print (minimumDeletions(arr1, N)) #Contributed by Akash Srivastava
f = open('archivo.txt', 'w') lines = [] op = '' while op != 'T': if op == 'A': line = input('Ingrese el texto: ') lines.append(line + '\n') op = input('¿Deseas añadir una línea al archivo (A) o terminar (T)?') f.writelines(lines) f.close() f = open('archivo.txt', 'r') for line in f: print(line)
from picoh import picoh # Reset Picoh picoh.reset() ''' The picoh.move() function needs at least 2 arguments: movement name and desired position. picoh.HEADTURN picoh.HEADNOD picoh.EYETURN picoh.EYETILT picoh.BOTTOMLIP picoh.LIDBLINK position can be any number 0-10. ''' # Move the HEADTURN motor to 2. picoh.move(picoh.HEADTURN,2) picoh.say("head turn to 2") # Move the HEADTURN motor to 5. picoh.move(picoh.HEADTURN,5) picoh.say("head turn to 5") # Move the HEADNOD motor to 9. picoh.move(picoh.HEADNOD,9) picoh.say("head nod to 9") # Move the HEADNOD motor to 5. picoh.move(picoh.HEADNOD,5) picoh.say("head nod to 5") ''' The picoh.move() function can also take an optional third arguement 'spd' to change the speed of the movement. If unspecified speed defaults to 5. ''' # Move HEADTURN motor to position 0 at speed 1. picoh.move(picoh.HEADTURN,0,spd=1) picoh.say("Head turn to 0, speed 1") # Wait for motor to move picoh.wait(2) # Move HEADTURN motor to position 10 at speed 1. picoh.move(picoh.HEADTURN,10,spd=1) picoh.say("Head turn to 10, speed 1") # Wait for motor to move picoh.wait(1) # Move HEADTURN motor to position 0 at speed 10. picoh.move(picoh.HEADTURN,0,spd=10) picoh.say("Head turn to 0, speed 10") # Wait for motor to move picoh.wait(0.5) picoh.move(picoh.HEADTURN,10,spd=10) picoh.say("Head turn to 10, speed 10") # Wait for motor to move picoh.reset() picoh.wait(1) ''' Finally the move function supports another optional argument 'eye'. This will only have an effect when moving, EYETURN, EYETILT or LIDBLINK. The eye arguments allows the eyes to be move individually, 0 - Both, 1 - Right, 2 - Left If unspecified, default value 0 (Both) is used. ''' # Wink Left for x in range(10,0,-1): picoh.move(picoh.LIDBLINK,x,eye = 1) picoh.wait(0.04) for x in range(0,10): picoh.move(picoh.LIDBLINK,x,eye = 1) picoh.wait(0.04) # Wink Right for x in range(10,0,-1): picoh.move(picoh.LIDBLINK,x,eye = 2) picoh.wait(0.04) for x in range(0,10): picoh.move(picoh.LIDBLINK,x,eye = 2) picoh.wait(0.04) # Blink for x in range(10,0,-1): picoh.move(picoh.LIDBLINK,x,eye = 0) picoh.wait(0.04) for x in range(0,10): picoh.move(picoh.LIDBLINK,x,eye = 0) picoh.wait(0.04) # Move right eye for x in range(0,10): picoh.move(picoh.EYETILT,x,eye = 1) picoh.wait(0.1) # Move left eye for x in range(0,10): picoh.move(picoh.EYETILT,x,eye = 2) picoh.wait(0.1) # Set both eyes back to 5. picoh.move(picoh.EYETILT,5) picoh.close()
#PROGRAM TO FIND AREA AND PERIMETER OF RECTANGLE l=int(input("Enter the length ")) b=int(input("Enter the breadth ")) area=l*b perimeter=2*(l+b) print("The area is",area) print("The perimeter is",perimeter)
# https://programmers.co.kr/learn/courses/30/lessons/12937 # Difficulty : Level 1 1) First Solution def solution(num): ans=["Even","Odd"] return ans[num%2] # Example : # solution(3) ==> "Odd" # solution(4) ==> "Even"
# Funciones lambda (funciones anonimas), abreviar la sintaxis. Consiste en resumir una funcion en python por una funcion lambda. # Python 3.7 # Jr2r # #Funcion tradicional '''def area_triangulo(base, altura): return (base*altura)/2 print(area_triangulo(5, 7))''' #Funcion reducida con lambda, toma argumentos y despues de los dos puntos realiza la operacion. #Las operaciones logicas o ciclos no son validos en lambda. #Funciones rapidas(on the go, on demand, online) para utilizar por un momento. area_triangulo = lambda base, altura:(base*altura)/2 alcubo = lambda numero:pow(numero, 3) #Lambda con format. destValor = lambda comision:"¡{}!$".format(comision) comisionEmple=1890 print(destValor(comisionEmple))
# Python 3.7 #jr2r # Counting Valleys l = "" c = 0 myRe = [] #Path list to iterate path = list("DDUUDDUDUUUD") for i in path: if l == "": l = i c += 1 else: if l == i: c += 1 else: if c >= 3: myRe.append(c) c = 1 l = i else: c = 1 l = i print(len(myRe))
# Function to estimate insurance cost: def estimate_insurance_cost(name, age, sex, bmi, num_of_children, smoker): estimated_cost = 250*age - 128*sex + 370*bmi + 425*num_of_children + 24000*smoker - 12500 print(name + "'s Estimated Insurance Cost: " + str(estimated_cost) + " dollars.") return estimated_cost # Estimate Maria's insurance cost maria_insurance_cost = estimate_insurance_cost(name = "Maria", age = 31, sex = 0, bmi = 23.1, num_of_children = 1, smoker = 0) # Estimate Rohan's insurance cost rohan_insurance_cost = estimate_insurance_cost(name = "Rohan", age = 25, sex = 1, bmi = 28.5, num_of_children = 3, smoker = 0) # Estimate Valentina's insurance cost valentina_insurance_cost = estimate_insurance_cost(name = "Valentina", age = 53, sex = 0, bmi = 31.4, num_of_children = 0, smoker = 1) # Add your code here names = ["Maria", "Rohan", "Valentina"] names.append("Akira") insurance_costs = [4150.0, 5320.0, 35210.0] insurance_costs.append(2930.0) insurance_data = list(zip(names, insurance_costs)) print("Here is the actual insurance cost data: " + str(insurance_data)) estimated_insurance_data = [] estimated_insurance_data.append(("Maria", maria_insurance_cost)) estimated_insurance_data.append(("Rohan", rohan_insurance_cost)) estimated_insurance_data.append(("Valentina", valentina_insurance_cost)) print("Here is the estimated insurance cost data: " + str(estimated_insurance_data)) insurance_cost_difference = [] insurance_cost_difference_maria = maria_insurance_cost - insurance_costs[0] insurance_cost_difference_rohan = rohan_insurance_cost - insurance_costs[1] insurance_cost_difference_valentina = valentina_insurance_cost - insurance_costs[2] insurance_cost_difference.append(("Maria", insurance_cost_difference_maria)) insurance_cost_difference.append(("Rohan", insurance_cost_difference_rohan)) insurance_cost_difference.append(("Valentina", insurance_cost_difference_valentina)) print("Here is the difference between the actual insurance cost and estimated insurance cost for each person: " + str(insurance_cost_difference)) #Estimate Akira's insurance cost akira_insurance_cost = estimate_insurance_cost(name = "Akira", age = 19, sex = 1, bmi = 27.1, num_of_children = 0, smoker = 0) estimated_insurance_data.append(("Akira", akira_insurance_cost)) print("Here is the estimated insurance cost data: " + str(estimated_insurance_data)) insurance_cost_difference_akira = akira_insurance_cost - insurance_costs[-1] insurance_cost_difference.append(("Akira", insurance_cost_difference_akira)) print("Here is the difference between the actual insurance cost and estimated insurance cost for each person: " + str(insurance_cost_difference))
# Simple Linear Regression # importing libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # importing datasets dataset = pd.read_csv("Salary_Data.csv") X=dataset.iloc[:,:-1].values y=dataset.iloc[:,1].values # splitting dataset into traing and testing from sklearn.cross_validation import train_test_split X_train,X_test,y_train,y_test =train_test_split(X, y, test_size=0.2, random_state=0) # Fitting the model from sklearn.linear_model import LinearRegression regressor=LinearRegression() regressor.fit(X_train,y_train) # Predicting y_pred=regressor.predict(X_test) # Visualising the training results plt.scatter(X_train,y_train,color="red") plt.plot(X_train,regressor.predict(X_train),color="blue") plt.title("Salary VS Experience ( Training Set)") plt.xlabel("Experience") plt.ylabel("Salary") plt.show() # Visualising the test results plt.scatter(X_test,y_test,color="black") plt.plot(X_train,regressor.predict(X_train),color="blue") plt.title("Salary VS Experience ( Test Set)") plt.xlabel("Experience") plt.ylabel("Salary") plt.show() regressor.score(X_train,y_train)
__author__ = 'trunghieu11' import random def sumOfDegit(x): answer = 0 for c in str(x): answer += int(ord(c) - ord('0')) return answer if answer < 10 else sumOfDegit(answer) def bruteForce(begin, distance, left, right): answer = 0 left -= 1 for i in range(0, right): if i >= left: answer += sumOfDegit(begin + i * distance) return answer def solve(begin, distance, left, right): left -= 1 right -= 1 begin = sumOfDegit(begin + left * distance) distance = sumOfDegit(distance) visited = [] total = 0 firstTotal = 0 circleLen = 0 answer = 0 step = 0 cur = begin i = left while i <= right: if cur in visited: while begin != cur: left += 1 circleLen -= 1 firstTotal += sumOfDegit(begin) begin = sumOfDegit(begin + distance) answer += firstTotal step = total - firstTotal break else: circleLen += 1 total += sumOfDegit(cur) visited.append(cur) cur = sumOfDegit(cur + distance) i += 1 if i > right: return total answer += ((right - left + 1) / circleLen) * step remain = (right - left + 1) % circleLen for i in range(remain): answer += sumOfDegit(cur + i * distance) return answer if __name__ == '__main__': testCase = int(raw_input()) for test in range(testCase): begin, distance, left, right = map(int, raw_input().split()) print solve(begin, distance, left, right) # for i in range(100): # begin = random.randint(1, 20) # distance = random.randint(1, 10) # right = random.randint(20, 100) # left = random.randint(1, right) # answer1 = bruteForce(begin, distance, left, right) # answer2 = solve(begin, distance, left, right) # if answer1 != answer2: # print begin, distance, left, right # print "Expected: " + str(answer1) # print "Received: " + str(answer2)
class ValueOfString: def findValue(self, strx): sumx=0 for i in strx: t = 0 for j in strx: if j <= i: t += 1 sumx += (ord(i)-96)*t return (sumx) ########################## # BEGIN TEST # ########################## import sys import time def RunTest(testNum, p0, hasAnswer, p1): obj = ValueOfString() startTime = time.clock() answer = obj.findValue(p0) endTime = time.clock() testTime.append(endTime - startTime) res = True if hasAnswer: res = answer == p1 if res: print(str("Test #") + str(testNum) + ": Passed") return res print(str("Test #") + str(testNum) + str(":")) print(("[") + str(p0) + str("]")) if (hasAnswer): print(str("Expected:")) print(str(p1)) print(str("Received:")) print(str(answer)) print(str("Verdict:")) if (not res): print(("Wrong answer!!")) elif ((endTime - startTime) >= 20): print(str("FAIL the timeout")) res = False elif (hasAnswer): print(str("OK!!")) else: print(str("OK, but is it right?")) print("Time: %.11f seconds" % (endTime - startTime)) print(str("-----------------------------------------------------------")) return res all_right = True tests_disabled = False testTime = [] # ----- test 0 ----- disabled = False p0 = "babca" p1 = 35 all_right = (disabled or RunTest(0, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 1 ----- disabled = False p0 = "zz" p1 = 104 all_right = (disabled or RunTest(1, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 2 ----- disabled = False p0 = "zyxwvutsrqponmlkjihgfedcba" p1 = 6201 all_right = (disabled or RunTest(2, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 3 ----- disabled = False p0 = "topcoder" p1 = 558 all_right = (disabled or RunTest(3, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 4 ----- disabled = False p0 = "charlie" p1 = 297 all_right = (disabled or RunTest(4, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 5 ----- disabled = False p0 = "valueofstring" p1 = 1502 all_right = (disabled or RunTest(5, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 6 ----- disabled = False p0 = "abcdefghijklmnopqrstuvwxyz" p1 = 6201 all_right = (disabled or RunTest(6, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 7 ----- disabled = False p0 = "thequickbrownfoxjumpsoverthelazydog" p1 = 11187 all_right = (disabled or RunTest(7, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 8 ----- disabled = False p0 = "a" p1 = 1 all_right = (disabled or RunTest(8, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 9 ----- disabled = False p0 = "b" p1 = 2 all_right = (disabled or RunTest(9, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 10 ----- disabled = False p0 = "z" p1 = 26 all_right = (disabled or RunTest(10, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 11 ----- disabled = False p0 = "itwasthebestoftimesitwastheworstoftimesitwastheage" p1 = 23206 all_right = (disabled or RunTest(11, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 12 ----- disabled = False p0 = "ofwisdomitwastheageoffoolishnessitwastheepochofbel" p1 = 20393 all_right = (disabled or RunTest(12, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 13 ----- disabled = False p0 = "iefitwastheepochofincredulityitwastheseasonoflight" p1 = 20660 all_right = (disabled or RunTest(13, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 14 ----- disabled = False p0 = "itwastheseasonofdarknessitwasthespringofhopeitwast" p1 = 22276 all_right = (disabled or RunTest(14, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 15 ----- disabled = False p0 = "hewinterofdespairwehadeverythingbeforeuswehadnothi" p1 = 20124 all_right = (disabled or RunTest(15, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 16 ----- disabled = False p0 = "ngbeforeuswewereallgoingdirecttoheavenwewereallgoi" p1 = 19714 all_right = (disabled or RunTest(16, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 17 ----- disabled = False p0 = "ngdirecttheotherwayinshorttheperiodwassofarlikethe" p1 = 21097 all_right = (disabled or RunTest(17, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 18 ----- disabled = False p0 = "presentperiodthatsomeofitsnoisiestauthoritiesinsis" p1 = 22556 all_right = (disabled or RunTest(18, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 19 ----- disabled = False p0 = "tedonitsbeingreceivedforgoodorforevilinthesuperlat" p1 = 20182 all_right = (disabled or RunTest(19, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 20 ----- disabled = False p0 = "ivedegreeofcomparisononlytherewereakingwithalargej" p1 = 19402 all_right = (disabled or RunTest(20, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 21 ----- disabled = False p0 = "awandaqueenwithaplainfaceonthethroneofenglandthere" p1 = 18478 all_right = (disabled or RunTest(21, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 22 ----- disabled = False p0 = "wereakingwithalargejawandaqueenwithafairfaceonthet" p1 = 18599 all_right = (disabled or RunTest(22, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 23 ----- disabled = False p0 = "hroneoffranceinbothcountriesitwasclearerthancrysta" p1 = 20826 all_right = (disabled or RunTest(23, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 24 ----- disabled = False p0 = "ltothelordsofthestatepreservesofloavesandfishestha" p1 = 21337 all_right = (disabled or RunTest(24, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 25 ----- disabled = False p0 = "tthingsingeneralweresettledforeveritwastheyearofou" p1 = 21648 all_right = (disabled or RunTest(25, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 26 ----- disabled = False p0 = "rlordonethousandsevenhundredandseventyfivespiritua" p1 = 21762 all_right = (disabled or RunTest(26, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 27 ----- disabled = False p0 = "lrevelationswereconcededtoenglandatthatfavouredper" p1 = 19759 all_right = (disabled or RunTest(27, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 28 ----- disabled = False p0 = "iodasatthismrssouthcotthadrecentlyattainedherfivea" p1 = 20915 all_right = (disabled or RunTest(28, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 29 ----- disabled = False p0 = "ndtwentiethblessedbirthdayofwhomapropheticprivatei" p1 = 20691 all_right = (disabled or RunTest(29, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 30 ----- disabled = False p0 = "nthelifeguardshadheraldedthesublimeappearancebyann" p1 = 17219 all_right = (disabled or RunTest(30, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 31 ----- disabled = False p0 = "ouncingthatarrangementsweremadefortheswallowingupo" p1 = 20876 all_right = (disabled or RunTest(31, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 32 ----- disabled = False p0 = "flondonandwestminstereventhecocklaneghosthadbeenla" p1 = 18832 all_right = (disabled or RunTest(32, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 33 ----- disabled = False p0 = "idonlyarounddozenofyearsafterrappingoutitsmessages" p1 = 21857 all_right = (disabled or RunTest(33, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 34 ----- disabled = False p0 = "asthespiritsofthisveryyearlastpastsupernaturallyde" p1 = 23665 all_right = (disabled or RunTest(34, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 35 ----- disabled = False p0 = "ficientinoriginalityrappedouttheirsmeremessagesint" p1 = 20608 all_right = (disabled or RunTest(35, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 36 ----- disabled = False p0 = "heearthlyorderofeventshadlatelycometotheenglishcro" p1 = 20200 all_right = (disabled or RunTest(36, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 37 ----- disabled = False p0 = "wnandpeoplefromacongressofbritishsubjectsinamerica" p1 = 19529 all_right = (disabled or RunTest(37, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 38 ----- disabled = False p0 = "whichstrangetorelatehaveprovedmoreimportanttothehu" p1 = 21637 all_right = (disabled or RunTest(38, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 39 ----- disabled = False p0 = "manracethananycommunicationsyetreceivedthroughanyo" p1 = 20784 all_right = (disabled or RunTest(39, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 40 ----- disabled = False p0 = "fthechickensofthecocklanebroodfrancelessfavouredon" p1 = 18065 all_right = (disabled or RunTest(40, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 41 ----- disabled = False p0 = "thewholeastomattersspiritualthanhersisteroftheshie" p1 = 22046 all_right = (disabled or RunTest(41, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 42 ----- disabled = False p0 = "ldandtridentrolledwithexceedingsmoothnessdownhillm" p1 = 20087 all_right = (disabled or RunTest(42, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 43 ----- disabled = False p0 = "akingpapermoneyandspendingitundertheguidanceofherc" p1 = 18436 all_right = (disabled or RunTest(43, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 44 ----- disabled = False p0 = "hristianpastorssheentertainedherselfbesideswithsuc" p1 = 21060 all_right = (disabled or RunTest(44, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 45 ----- disabled = False p0 = "hhumaneachievementsassentencingayouthtohavehishand" p1 = 19772 all_right = (disabled or RunTest(45, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 46 ----- disabled = False p0 = "scutoffhistonguetornoutwithpincersandhisbodyburned" p1 = 22042 all_right = (disabled or RunTest(46, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 47 ----- disabled = False p0 = "alivebecausehehadnotkneeleddownintheraintodohonour" p1 = 19050 all_right = (disabled or RunTest(47, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 48 ----- disabled = False p0 = "toadirtyprocessionofmonkswhichpassedwithinhisviewa" p1 = 21791 all_right = (disabled or RunTest(48, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 49 ----- disabled = False p0 = "tadistanceofsomefiftyorsixtyyardsitislikelyenought" p1 = 22741 all_right = (disabled or RunTest(49, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 50 ----- disabled = False p0 = "hatrootedinthewoodsoffranceandnorwaythereweregrowi" p1 = 21439 all_right = (disabled or RunTest(50, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 51 ----- disabled = False p0 = "ngtreeswhenthatsuffererwasputtodeathalreadymarkedb" p1 = 20890 all_right = (disabled or RunTest(51, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 52 ----- disabled = False p0 = "ythewoodmanfatetocomedownandbesawnintoboardstomake" p1 = 20584 all_right = (disabled or RunTest(52, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 53 ----- disabled = False p0 = "acertainmovableframeworkwithasackandaknifeinitterr" p1 = 18995 all_right = (disabled or RunTest(53, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 54 ----- disabled = False p0 = "ibleinhistoryitislikelyenoughthatintheroughouthous" p1 = 22263 all_right = (disabled or RunTest(54, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 55 ----- disabled = False p0 = "esofsometillersoftheheavylandsadjacenttoparisthere" p1 = 20162 all_right = (disabled or RunTest(55, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 56 ----- disabled = False p0 = "wereshelteredfromtheweatherthatverydayrudecartsbes" p1 = 21782 all_right = (disabled or RunTest(56, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 57 ----- disabled = False p0 = "patteredwithrusticmiresnuffedaboutbypigsandroosted" p1 = 21514 all_right = (disabled or RunTest(57, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 58 ----- disabled = False p0 = "inbypoultrywhichthefarmerdeathhadalreadysetapartto" p1 = 20901 all_right = (disabled or RunTest(58, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 59 ----- disabled = False p0 = "behistumbrilsoftherevolutionbutthatwoodmanandthatf" p1 = 21592 all_right = (disabled or RunTest(59, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 60 ----- disabled = False p0 = "armerthoughtheyworkunceasinglyworksilentlyandnoone" p1 = 22258 all_right = (disabled or RunTest(60, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 61 ----- disabled = False p0 = "heardthemastheywentaboutwithmuffledtreadtheratherf" p1 = 20679 all_right = (disabled or RunTest(61, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 62 ----- disabled = False p0 = "orasmuchastoentertainanysuspicionthattheywereawake" p1 = 22095 all_right = (disabled or RunTest(62, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 63 ----- disabled = False p0 = "aaabbc" p1 = 47 all_right = (disabled or RunTest(63, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 64 ----- disabled = False p0 = "y" p1 = 25 all_right = (disabled or RunTest(64, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 65 ----- disabled = False p0 = "abcabc" p1 = 56 all_right = (disabled or RunTest(65, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 66 ----- disabled = False p0 = "mmm" p1 = 117 all_right = (disabled or RunTest(66, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 67 ----- disabled = False p0 = "mamzmmwijfqpoaiponqoerjq" p1 = 5033 all_right = (disabled or RunTest(67, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 68 ----- disabled = False p0 = "jfjjfjjjjfjjfjfjjfjjjfjfj" p1 = 4634 all_right = (disabled or RunTest(68, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 69 ----- disabled = False p0 = "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww" p1 = 57500 all_right = (disabled or RunTest(69, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 70 ----- disabled = False p0 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" p1 = 1225 all_right = (disabled or RunTest(70, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 71 ----- disabled = False p0 = "abc" p1 = 14 all_right = (disabled or RunTest(71, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 72 ----- disabled = False p0 = "bbbcccdddaaazzz" p1 = 1440 all_right = (disabled or RunTest(72, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ # ----- test 73 ----- disabled = False p0 = "acdgknz" p1 = 368 all_right = (disabled or RunTest(73, p0, True, p1) ) and all_right tests_disabled = tests_disabled or disabled # ------------------ print("===========================================================") if all_right: if tests_disabled: print(str("All test Passed!! (but some test cases were disabled)!")) else: print(str("All test Passed!!")) else: print(str("Some of the test cases had errors.")) print("Run time: %.11f seconds" % max(testTime))
__author__ = 'trunghieu11' def gcd(a, b): a, b = abs(a), abs(b) while b != 0: a, b = b, a % b return a class GCDGraph: def possible(self, n, k, x, y): lstFrom = [] lstTo = [] for i in range(k + 1, x + 1): if x % i == 0: lstFrom.append(i) for i in range(k + 1, y + 1): if y % i == 0: lstTo.append(i) print lstFrom print lstTo for a in lstFrom: for b in lstTo: value = a * b / gcd(a, b) print value if value <= n or a == b: return "Possible" return "Impossible"
__author__ = 'trunghieu11' def check(first, second): if first == second: return True if len(first) % 2 == 1: return False half = len(first) / 2 return (check(first[:half], second[half:]) and check(first[half:], second[:half])) or (check(first[:half], second[:half]) and check(first[half:], second[half:])) def solve(first, second): return "YES" if check(first, second) else "NO" if __name__ == '__main__': first = raw_input() second = raw_input() print solve(first, second)
__author__ = 'trunghieu11' def solve(hexagon): answer = hexagon[0] + hexagon[1] + hexagon[2] answer = answer * answer - hexagon[0] * hexagon[0] * 3 return answer if __name__ == '__main__': hexagon = list(map(int, raw_input().split(" "))) print solve(hexagon)
# age=int(input("Enter your age")) # if age==18: # print("Wait for some days") # elif age>18: # print("You are able to drive.") # else: # print("You are not able to drive")
# Strings """ 7. Write a Python program to get a string from a given string where all occurrences of the last character have been changed to ‘*’, except the last character itself. """ st="GREATER" length=len(st) ch=st[length-1] st=st.replace(ch,"*") ch=st[length-1] print(st)
# List """ 8. Write a Python program to find the maximum of a list of numbers. """ lis=[1,2,3,4,5,6,7,8,100] a=max(lis) print("THE MAXIMUM NUMBER OF THIS LIST IS ",a)
# 股票买卖的最大利润 # 一次买入卖出:双指针,找股票最低点买入 prices = [1,2,3,0,2] def oneMaxProfit(prices): res = 0 minp = prices[0] for p in prices: if p<minp: minp = p elif p-minp>res: res = p-minp return res # 多次买入卖出:赚差价:只要前一天价格比后一天低,就买入卖出 def moreMaxProfit(prices): res = 0 for i in range(1,len(prices)): if prices[i]>prices[i-1]: res += prices[i]-prices[i-1] return res def moreMaxProfit1(prices): # 动态规划解法 sell = 0 hold = -prices[0] for i in range(1,len(prices)): sell = max(sell,hold+prices[i]) hold = max(hold,sell-prices[i]) return sell # 多次买卖+手续费 def moreMaxProfit2(prices): sell = 0 fee = 2 hold = -prices[0] for i in range(1,len(prices)): sell = max(sell,hold+prices[i]-fee) hold = max(hold,sell-prices[i]) return sell # 多次购买+冷冻期 def moreMaxProfit3(prices): n = len(prices) dp = [[0 for i in range(3)] for j in range(n)] dp[0][0]=-prices[0] dp[0][1] = 0 dp[0][2] = 0 for i in range(1,n): # 持仓 dp[i][0] = max(dp[i-1][0],dp[i-1][2]-prices[i]) # 空仓冷静 dp[i][1] = dp[i-1][0]+prices[i] # 空仓非冷静 dp[i][2] = max(dp[i-1][1],dp[i-1][2]) # 从空仓的两个里面选一个更大的 res = max(dp[n-1][1],dp[n-1][2]) return res # res = oneMaxProfit(prices) res = moreMaxProfit3(prices) print(res) # 可以两次买入卖出 # 可以k次买入卖出
import figures figuresList = [] for i in range(3): choice = input("Круг(к), прямоугольник(п) или треугольник(т): ") if choice == 'к': figure = figures.Circle(float(input("Радиус: "))) elif choice == 'п': l = float(input("Длина: ")) w = float(input("Ширина: ")) figure = figures.Rectangle(w, l) elif choice == 'т': a = float(input("Первая сторона: ")) b = float(input("Вторая сторона: ")) c = float(input("Третья сторона: ")) figure = figures.Triangle(a, b, c) figuresList.append(figure) maxS = 0 maxP = 0 maxSType = '' maxPType = '' for i in figuresList: s = i.getSquare() p = i.getPerimeter() if maxS < s: maxS = s maxSType = i.getName() if maxP < p: maxP = p maxPType = i.getName() choice2 = input('Select parameter for calculation: Square(s) or Perimeter(p): ') if choice2 == 's': print('Max square is %4s; figure: %4s' % (maxS, maxPType)) elif choice2 == 'p': print('Max Perometer is %4s; figure: %4s' % (maxP, maxPType)) else: print('invalid input \n') print('Max square is %4s; figure: %4s' % (maxS, maxPType)) print('Max Perometer is %4s; figure: %4s' % (maxP, maxPType))
#Grading a multiple choice exam is easy. # But how much do multiple choice exams tell us about what a student really knows? # Dr. Dirac is administering a statistics midterm exam and wants to use Bayes’ Theorem to help him understand the following: # - Given that a student answered a question correctly, what is the probability that she really knows the material? # Dr. Dirac knows the following probabilities based on many years of teaching: # - There is a question on the exam that 60% of students know the correct answer to. # - Given that a student knows the correct answer, there is still a 15% chance that the student picked the wrong answer. # - Given that a student does not know the answer, there is still a 20% chance that the student picks the correct answer by guessing. # Using these probabilities, we can answer the question. import numpy as np # In order to use Bayes Theorem, we need to phrase our question as P(A|B). # What is A and B in this case? # P(A) = P(knows the material) # P(B) = P(answers correctly) # P(A|B) = P(knows the material | answers correctly) # What is the probability that the student knows the material? # P(knows the material) = 0.60 # Given that the student knows the material, what is the probability that she answers correctly? # P(answers correctly | knows material) = 1 - 0.15 # What is the probability of any student answering correctly? # P(answers correctly | knows material) * P(knows material) and (+) P(answers correctly| does not know material) *P(does not know material) # = 0.85 * 0.6 + 0.2 * 0.4 # = 0.59 # Using the three probabilities and Bayes’ Theorem, calculate P(knows material | answers correctly) # P(knows material | answers correctly)= P(A|B) = P(B|A) * P(A) / P(B) = 0.85 * 0.6 / 0.59 p_knows_material_given_answers_correctly = 0.85 * 0.6 / 0.59 print(p_knows_material_given_answers_correctly)