text stringlengths 37 1.41M |
|---|
"""
Conjuntos
- Conjuntos em qualquer linguagem de programação, estamos fazendo referencia á Teoria dos conjuntos
da matemática
- aqui no python, os conjuntos são chamados de Sets.
Dito isso, da mesma dorma que na matemática:
- Sets (conjuntos) não possuem valores duplicados:
- Sets (conjuntos) não possuem valores ordenados:
- elementos não são acessados via índice, ou seja, conjuntos não são indexados
Conjuntos são bons para se utilizar quando precisamos armazenar elementos
mas não nos importamos com a ordenação deles. quando não precisamos se preocupa
com chaves valores e itens duplicados.
Os conjuntos Sets São referenciados em python com chaves {}
Diferença entre Conjuntos (Sets) e Mapas (Dicionarios)
- Um dicionario tem chave/valor;
- Um conjunto tem valor;
"""
# # Definindo um conjunto
#
# # forma 1
#
# s = set({1, 2, 3, 4, 5, 6, 5, 3, 4})
#
# # Obs: ao criar um conjunto, caso seja adicionado um valor ja existente, o mesmo
# # será ignorado sem gerar error e não fara parte do conjunto
# print(s)
# print(type(s))
#
# # forma 2 - mais comum
# s = {1, 2, 3, 4, 5, 5}
# print(s)
# print(type(s))
#
# # Podemos verificar se determinado elemento esta contido no conjunto
#
# if 3 in s:
# print('Tem o 3')
# else:
# print('Não tem o 3')
# # converter string para dentro do conjunto
# s = set('erickson')
# print(s)
#
# # convertendo lista para conjunto
# lista = [1, 2, 3, 4, 5, 5]
# print(set(lista))
#
# # convertendo tupla para conjunto
# tupla = (1, 2, 3, 5, 4, 4, 5)
# print(set(tupla))
# importante lembrar que alem de nao termos valores duplicados, não temos ordem
# dados = 99, 4, 54, 2, 1, 5, 2, 5
#
# lista = list(dados)
# tupla = tuple(dados)
# dicionario = {}.fromkeys(dados, 'dict')
# s = set(dados)
#
# print(lista, '-', len(lista), 'elementos') # aceitam valores duplicados
# print(tupla, '-', len(tupla), 'elementos') # Tuplas aceitam valores duplicados
# print(s, '-', len(s), 'elementos') # não repete valores
# print(dicionario, '-', len(dicionario), 'elementos') # Não repete chaves
#
# # Assim como todo outro conjunto Puthon podemos colocar todos os tipos de dados misturados em Sets
# s = {1, 'b', 1.40, 55.22, True}
# print(s)
# print(type(s))
#
# # podemos iterar em um Set normalmente
# for valor in s:
# print(valor)
# Uso interessantes com sets
# imagine que fizemos um formulario de cadastro de visitantes em uma feira ou museu e os visitantes
# informam manualmente a cidade de onde vieram .
# nós adicionamos cada cidade em uma lista Python, ja que podemos adicionar novos elementos
# e ter repetição.
# cidades = ['Belo Horizonte', 'São paulo', 'Campo grande', 'cuiaba', 'São paulo', 'Campo grande', 'cuiaba']
# print(len(cidades))
#
# # Agora precisamos saber quantas cidades destindas, ou seja, unica, temos.
#
# # podemos utilizar o set para isso
#
# print(len(set(cidades)))
# # adicionando elementos em um conjunto
# # são mutaveis, e tuplas são imutaveis
# s = {1, 2, 3}
# s.add(4)
# s.add(4) # duplicidade não gera erro, duplicidade não gera erro mas é ignorado e nao adicionado
# print(s)
#
# # Remover elementos em um conjunto
# # forma 1
# s.remove(3) # Não é indice, informamos o valor pra ser adicionado
# print(s)
#
# # forma 2
# s.discard(2)
# print(s)
#
# # copiando um conjunto
# # Forma 1 - Deep Copy
# print('\n')
#
# novo = s.copy()
# print(novo)
# novo.add(5)
#
# print(novo)
# print(s)
#
# print('\n')
# # Forma 2 = Shallow Copy
# novoS = s
# novoS.add(5)
#
# print(novo)
# print(s)
#
# # apaga todos os elementos
# s.clear()
# # Métodos Matemáticos de conjuntos
# estudantes_python = {'Marcos', 'Patricia', 'pedro', 'elen', 'gabriel', 'Julia'}
# estudantes_java = {'Julia', 'Fernando', 'Gustavo', 'Patricia'}
#
# # Veja que existe repetições
# # Gerar um conjunto com estudantes unicos
#
# # forma 1 - utilizando union
# unicos1 = estudantes_python.union(estudantes_java)
# # {'Gustavo', 'Fernando', 'Patricia', 'elen', 'Marcos', 'pedro', 'Julia', 'gabriel'}
#
# # unicos1 = estudantes_java.union(estudantes_python)
# # {'Gustavo', 'gabriel', 'Julia', 'Patricia', 'Marcos', 'pedro', 'elen', 'Fernando'}
# print(unicos1)
#
# # forma 2 - utilizando o carectere pipe |
# unicos2 = estudantes_java | estudantes_python
# print(unicos2)
# estudantes_python = {'Marcos', 'Patricia', 'pedro', 'elen', 'gabriel', 'Julia'}
# estudantes_java = {'Julia', 'Fernando', 'Gustavo', 'Patricia'}
#
# # gerar um conjunto que estão com ambos elementos
#
# # forma 1 - utilizando intersection
# ambos1 = estudantes_python.intersection(estudantes_java)
# print(ambos1)
#
# # forma 2 - utulizando o &
# ambos2 = estudantes_java.intersection(estudantes_python)
# print(ambos2)
# estudantes_python = {'Marcos', 'Patricia', 'pedro', 'elen', 'gabriel', 'Julia'}
# estudantes_java = {'Julia', 'Fernando', 'Gustavo', 'Patricia'}
#
# # Gerar um conjunto de estudantes que não estão no outro
#
# so_python = estudantes_python.difference(estudantes_java)
# print(so_python)
#
# so_java = estudantes_java.difference(estudantes_python)
# print(so_java)
# Soma, valor maximo. valor minimo, tamanho
# se os valores dorem reais ou reais
s = {1, 2, 3, 4, 5, 6}
print(sum(s))
print(max(s))
print(min(s))
print(len(s))
|
lista = ['primeiro', 2, 85, 4, 125, 5, 'ultimo']
n1, *n2 = lista
print(n1)
print(n2, '\n')
*n1, n2 = lista
print(n1)
print(n2, '\n')
n1, *n2, n3 = lista
print(n1)
print(n2)
print(n3, '\n')
n1, *_, n3 = lista
print(n1)
print(n3, '\n') |
# tudo sobre tuplas
# tupla = (1, 2)
for item in dir(tuple):
print(item)
# Tuplas são imutaveis
# # Devolve o número de vezes em que x aparece na lista.
# tupla = (1, 2, 3, 4, 4, 4, 6, 7, 8, 9, )
# num_vezes = tupla.count(4)
# print(num_vezes)
# verifica o index do elemento
tupla = (1, 2, 3, 4, 6, 7, 8, 9, )
print(tupla.index(4))
|
import pandas as pd
import numpy as np
df = pd.read_csv('dados.csv')
print(df.head(), '\n')
# O np.nan é um valor especial definido no Numpy,
# sigla para Not a Number, o pandas preenche células sem valores em um DataFrame lido com np.nan.
print('ubstituir um valor específico por um NaN.')
df2 = df.replace({"pm2": {12031.25: np.nan}})
print(df2, '\n')
print('Retorna as linhas que não contém NaN')
print(df2.dropna(), '\n')
print('Preenxher todos os valores de NaN por um outro específico')
print(df2.fillna('Não contém nada'), '\n')
print('Indica quais valores da dataframe são NaN com True')
print(df2.isna())
|
from tkinter import *
janela = Tk()
janela.title('012')
janela.geometry('500x200')
label1 = Label(janela,
text='Frase de teste\nteste\nteste\ndfdfgdf',
font='Arial 20',
bd=1,
relief='solid',
width=20,
height=5,
justify=LEFT,
anchor=W)
label1.pack()
# label1 = Label(janela,
# text='Frase de teste\nteste\nteste',
# font='Arial 20',
# bd=1,
# relief='solid',
# pady=50,
# padx=50,
# justify=RIGHT)
# label1.pack()
janela.mainloop()
|
"""
Reduce
OBS: A partir do python3+ a função reduce() não é mais uma função integrada (built - in)
agora temos que importar a utilizar esta função do módulo 'functools'
guido van Rossum: utilize a função reduce() se você realmente precisa dela . em todo caso,
99% das vezes um loop for é mais legível.
Para entender o reduce()
a função reduce recebe dois parâmtros: a função e o iterável.
reduce(funcao, dados) - funcao que recebe dois parâmetros
"""
from functools import reduce
dados = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# utilizando
res = reduce(lambda x, y: x + y, dados)
print(res)
# Utilizando umk loop normal
res = 0
for n in dados:
res = res + n
print(res)
|
"""
Seek e Cursors
Seek - Utiliza-se para moveimentar o cursor pelo arquivo
Cursors -
"""
# Seek
# arquivo = open('texte.txt', encoding='UTF-8')
# print(arquivo.read())
# print()
# # movimentar o cursos pelo aarquivo com a função Seek
# arquivo.seek(12)
# print(arquivo.read())
# # imprimir linha e separando strings
# arquivo = open('texte.txt', encoding='UTF-8')
# ret = arquivo.readline() # Imprime uma linha
# print(ret)
# print(ret.split(' ')) # Separa cada palavra por string
# cria uma lista com todas as linhas
arquivo = open('texte.txt', encoding="UTF-8")
arquivo = arquivo.readlines()
print(len(arquivo))
# # Curcors
# arquivo = open('texte.txt', encoding='UTF-8')
# print(arquivo.read())
|
class Televisao:
def __init__(self):
self.ligada = False
self.canal = 5
def power(self):
if self.ligada:
self.ligada = False
else:
self.ligada = True
def aumenta_canal(self):
if self.ligada:
self.canal += 1
def diminuir_canal(self):
if self.ligada:
self.canal -= 1
televisao = Televisao()
print('A televisão esta: {}'.format(televisao.ligada))
televisao.power()
print('A televisão esta: {}'.format(televisao.ligada))
print('Canal selecionado: {}'.format(televisao.canal))
televisao.aumenta_canal()
print('Canal aumentado para o : {}'.format(televisao.canal))
televisao.diminuir_canal()
print('Cancal diminuido para: {}'.format(televisao.canal))
|
import pandas as pd
# Criando Series de dados com index
notas = pd.Series([1, 2, 4, 8, 7, 5], [["Wilfred", "Abbie", "Harry", "Julia", "Carrie", "Carlos"]])
# imprimindo os index
print(notas.index)
# imprimindo os valores
print(notas.values, "\n")
# imprimindo o objeto com os valores de modo organizado pelo pandas
print(notas, "\n")
# imprimindo o index definido
print(notas['Julia'])
|
"""
Utilizando lambdas
Conhecidas por expressões lambdas ou simplesmente lambdas são funções sem nome,
ou seja, funções anônimas
"""
# # função python
#
#
# def funcao(x):
# return 3 * x + 1
#
#
# print(funcao(4))
#
# # expressão lambda
# # lambda x: 3 * x + 1
#
# # como utilizar
# calc = lambda x: 3 * x + 1
#
# print(calc(4))
# # podemos ter expressões lambdas com varias entradas
#
# nome_completo = lambda nome, sobrenome: nome.strip().title() + ' ' + sobrenome.strip().title()
# print(nome_completo('erickson', 'Lopes'))
# print(nome_completo(' zacarias', 'ds dd'))
# # em funções python podemos ter nenhuma ou varias entradas em lambdas tbm
#
# amo_python = lambda: 'como não amar python'
# print(amo_python())
#
# uma = lambda x: 3 * x + 1
# duas = lambda x, y: (x * y) ** 0.5
# tres = lambda x, y, z: f'{x},{y},{z}'
#
# print(uma(5), duas(4, 5), tres(6, 5, 7))
# # outro exemplo
#
# autores = ['luiz aasconcelo', 'zezé de bamargo', ' luciano com c', 'x dom d', 'varjar eomingues']
#
# print(autores)
#
# # ordenando com sort
# autores.sort(key=lambda sobrenome: sobrenome.split(' ')[-1].lower())
# print(autores)
# função quadratica
# f(x) = a * x ** 2 + b * x + c
# definindo a funcao
def geradora_quadratica(a, b, c):
"""retorna a função f(x) = a * x ** 2 + b * x + c"""
return lambda x: a * x ** 2 + b * x + c
teste = geradora_quadratica(2, 3, -5)
print(teste(0))
print(teste(1))
print(teste(2))
|
"""
Bloco with
Passo apra trabalhar com arquivos
-abrir
-manipular
-fechar
O bloco with é utilizado para trabalhar com algo.
with ja abre e fecha o arquivo.
"""
# with - Forma pythonica de manipulaçao de arquivos
with open('texte.txt') as arquivo:
print(arquivo.readlines())
if arquivo.close:
print('o arquivo esta: fechado')
else:
print('o aqrquivo esta: aberto') |
num1 = int(input('Digite um valor: '))
num2 = int(input('Digite outro valor:' ))
print(num1 + num2) |
"""
recebendo dados do usuário
input -> Todo dado recebido via input é do tipo String
em python,tudo que estiver entre :
- Aspas simples ''
- Aspas duas ""
- Aspas simples triplas ''''''
- Aspas duas triplas """"""
"""
# entrada de dados
# print("Qual é o seu nome? ")
# nome = input() # input -> entrada
nome = input('qual é o seu nome? ')
# exemplo de print 'antigo' 2.x
# print('Seja bem-vindo(a) {0}' .format(nome))
# Exemplo do print moderno 3.x
# Print('Seja bem-vindo(a) %s' % nome)
# exemplo de print 'mais atual'
print(f'Seja bem-vindo(a) {nome.strip().title()}')
# print('Qual sua idade? ')
# idade = input()
idade = int(input('Qual sua idade ?'))
# processamento
# Saída de dados
# Exemplo de print 'antigo' 2.x
# print('A {0} tem {1} anos' .format(nome, idade))
# print('A %s tem %s anos' % (nome.title().strip(), idade.strip()))
# Forma atual 3.8
print(f'A(o) {nome.title().strip()} tem {idade}')
# int(idade)=> cast
"""
Cast é a converção de um tipo de dado para outro
"""
print(f'A(o) {nome.title().strip()} nasceu em {2020 - idade}')
|
# -*- coding: utf-8 -*-
"""
Docoratorns com diferentes assinaturas
- Passar varios parametros de um funcão decorada
- A assinatura de uma função é representada por seu retorno e nome e parametro de entrada.
"""
# # Relembrando
# def gritar(funcao):
# def aumentar(nome):
# return funcao(nome).upper()
# return aumentar
#
#
# @gritar
# def saudacao(nome):
# return f'Olá, eu sou o {nome}'
#
#
# @gritar
# def ordenar(principal, acompanhamento):
# return f'eu gostaria de {principal}, aompanhado de {acompanhamento}'
#
#
# print(ordenar('picanha', 'batata frita'))
# refatorando com decorator patter
def gritar(funcao):
def aumentar(*args, **kwargs):
return funcao(*args, **kwargs).upper()
return aumentar
@gritar
def ordenar(prato, acompanhamento):
return f'quero {prato}, com {acompanhamento}'
print(ordenar('Picanha', 'batata'))
@gritar
def lol():
return 'lol'
print(lol())
# vale lembrar que podemos usar padroes nomeados
print(ordenar(acompanhamento='ssalada', prato='Cheio'))
# decorator com argumentos
|
from tkinter import *
tela = Tk()
tela.title('009')
lbl1 = Label(tela, text='Este é o Label 1')
lbl2 = Label(tela, text='Este é o label 2')
botao = Button(tela, text='Este é o botão')
# pack
lbl1.pack()
botao.pack()
lbl2.pack()
tela.mainloop()
|
"""
Min e max
max - retorna o maior valor em um iterável
min - retorna o menor valor em um iteravel
"""
#
# # exemplo
# lista = [0, 8, 9, 41]
# print(max(lista))
#
# # ordena pela chave
# dicio = {'a': 5, 'b': 3}
# print(max(dicio))
# print(max(dicio.values()))
# # programa que receba dois valores
# v1, v2 = 3, 7
# print(max(v1, v2)) # retorna o valor maior
#
# print(max('a', 'abc', 'g'))
# print(max('b', 'z', 'g'))
# # print(max(1, 'v')) # Valores não compatíveis
# # exemplo
# lista = [0, 8, 9, 41]
# print(min(lista))
#
# # ordena pela chave
# dicio = {'a': 5, 'b': 3}
# print(min(dicio))
# print(min(dicio.values()))
#
# # programa que receba dois valores
# v1, v2 = 3, 7
# print(min(v1, v2)) # retorna o valor maior
#
# print(min('a', 'abc', 'g'))
# print(min('b', 'z', 'g'))
# # print(max(1, 'v')) # Valores não compatíveis
# print(min(-1, 0, 1))
# OUTROS EXEMPLOS
nomes = ['marcelo', 'adriana', 'giseli', 'pedro lemos ', 'ana', 'zarrit']
print(max(nomes)) # adriana
print(min(nomes)) # zarrit
print(max(nomes, key=lambda nome: len(nome))) # pedro lemos
print(min(nomes, key=lambda nome: len(nome))) # ana
musicas = [
{'titulo': 'Jesus chorou', 'tocou': 3},
{'titulo': 'Cana braba', 'tocou': 2},
{'titulo': 'Giz', 'tocou': 4}
]
print(max(musicas, key=lambda musica: musica['tocou']))
print(min(musicas, key=lambda musica: musica['tocou']))
# Desafio
print(max(musicas, key=lambda musica: musica['tocou'])['titulo']) # exibir apenas o nome da musica
print(min(musicas, key=lambda musica: musica['tocou'])['titulo'])
|
# # definindo funções
# def minha_funcao():
# print('Essa é minha função')
# minha_funcao()
#
# # Utilizando parâmetros
# def adicionar(a, b):
# print(a + b)
# adicionar(10, 20)
# # função lambda:
# saudar = lambda nome: 'Olá ' + nome
# print(saudar('Erickson'))
#
# adicionar = lambda a, b: a + b
# subtrair = lambda a, b: a - b
# dividir = lambda a, b: a / b
# multiplicar = lambda a, b: a * b
#
# print(abs(subtrair(10, 15)))
# print(adicionar(10, 15))
|
"""
Try - except
tratar erros que podem ocorrer, previnindo assim que o programa pare de funcionar.
"""
# # SyntaxError
# try:
# geek()
# except:
# print('ops')
# # como tratar esse erro
# try:
# geek() # NameError
# except NameError:
# print('Não foi encontrado o nome pedido')
# try:
# len(5) # TypeError
# except TypeError:
# print('ops')
# # Detalhes especificos de erro
# try:
# len(5)
# except TypeError as err:
# print(f'O seguinte erro aconteceu: {err}')
# # podemos efetuar diversos tratamentos de erros
# try:
# print('4'[5])
# except TypeError as tr:
# print('Erro', tr)
# except NameError as Ne:
# print('Erro', Ne)
# except IndexError as s:
# print('Aconteceu outro erro', s)
# Retornando algo com tratamento de erro
def pega_valor(dicionario, chave):
try:
return dicionario[chave]
except KeyError:
print('Essa chave não existe')
return None
dic = {'nome': 'geek'}
print(pega_valor(dic, 'nome'))
|
from source.data import char_span_to_token_span
import unittest
class SpanTest(unittest.TestCase):
def test_from_beginning(self):
passage = "The College of Arts and Letters was established as the university's first college in 1842 with" \
" the first degrees given in 1849. The university's first academic curriculum was modeled after" \
" the Jesuit Ratio Studiorum from Saint Louis University. Today the college, housed in " \
"O'Shaughnessy Hall, includes 20 departments in the areas of fine arts, humanities, and social" \
" sciences, and awards Bachelor of Arts (B.A.) degrees in 33 majors, making it the largest of the" \
" university's colleges. There are around 2,500 undergraduates and 750 graduates enrolled in the" \
" college."
start = [0]
end = [31]
self.assertEqual([1, 6], char_span_to_token_span(start, end, passage))
def test_in_the_middle(self):
passage = "The College of Science was established at the university in 1865 by president Father Patrick " \
"Dillon. Dillon's scientific courses were six years of work, including higher-level mathematics" \
" courses. Today the college, housed in the newly built Jordan Hall of Science, includes over" \
" 1,200 undergraduates in six departments of study – biology, chemistry, mathematics, physics," \
" pre-professional studies, and applied and computational mathematics and statistics (ACMS) – " \
"each awarding Bachelor of Science (B.S.) degrees. According to university statistics, its science" \
" pre-professional program has one of the highest acceptance rates to medical school of any" \
" university in the United States."
start = [78]
end = [99]
self.assertEqual([14, 16], char_span_to_token_span(start, end, passage))
|
frase = input("Escriba la frase que quiere saber cuantas vocales y consonantes tiene?\n")
n_consonantes = 0
n_vocales = 0
vocales = ["a","e","i","o","u"]
for letra in frase:
if letra in vocales:
n_vocales +=1
else:
n_consonantes +=1
print("La frase tiene {} consonantes y {} vocales".format(n_consonantes,n_vocales))
|
import numpy as np
import itertools
"""
Use Floyd-Warshall to compute shortest distances between all states to compute optimal reward in expectation
"""
if __name__ == '__main__':
board = ['##########',
'# #',
'# #',
'# # #',
'# ## #',
'# ## #',
'# # #',
'# #',
'# #',
'##########']
arr = np.array([list(row) for row in board])
free_spaces = list(map(tuple, np.argwhere(arr != '#')))
dist = {(x, y) : np.inf for x in free_spaces for y in free_spaces}
for (u, v) in dist.keys():
d = abs(u[0] - v[0]) + abs(u[1] - v[1])
if d == 0:
dist[(u, v)] = 0
elif d == 1:
dist[(u, v)] = 1
for k in free_spaces:
for i in free_spaces:
for j in free_spaces:
if dist[(i, j)] > dist[(i, k)] + dist[(k, j)]:
dist[(i, j)] = dist[(i, k)] + dist[(k, j)]
reward = []
count = 0
N = 2
for points in itertools.combinations(free_spaces, N):
distances = [dist[(points[0], points[i])] for i in range(1, N)]
d = np.min(distances)
if d > 0:
reward.append(1 + -0.1 * (d-1))
print(reward)
print(np.mean(reward))
print(np.std(reward))
# for i in range(1):
#
# env = CollectEnv(goal_condition=lambda x: x.colour == 'purple' and x.shape == 'square')
# env.reset()
# env.render()
# for _ in range(10000):
# obs, reward, done, _ = env.step(env.action_space.sample())
# env.render()
# if done:
# env.reset()
# 1 let dist be a |V| × |V| array of minimum distances initialized to ∞ (infinity)
# 2 for each edge (u,v)
# 3 dist[u][v] ← w(u,v) // the weight of the edge (u,v)
# 4 for each vertex v
# 5 dist[v][v] ← 0
# 6 for k from 1 to |V|
# 7 for i from 1 to |V|
# 8 for j from 1 to |V|
# 9 if dist[i][j] > dist[i][k] + dist[k][j]
# 10 dist[i][j] ← dist[i][k] + dist[k][j]
# 11 end if
|
def recursive_sum():
num_input = int(input("Escribe el número a sumar:"))
if (num_input == 0):
return 0
else:
return (int(num_input)) + int(recursive_sum())
def main():
print("La suma es: {}".format(str((recursive_sum()))))
if __name__ == '__main__':
main()
|
"""
"abacabad" c
"abacabaabacaba" _
"abcdefghijklmnopqrstuvwxyziflskecznslkjfabe" d
"bcccccccccccccyb" y
"""
def exist(repet_in_text, letter_in_text):
nonExist = True
for cont in range(len(repet_in_text)):
if repet_in_text[cont] == 1:
nonExist = False
break
else:
continue
if nonExist == False:
return letter_in_text[cont]
else:
return '_'
def first_not_repeating_char(char_sequence):
if char_sequence == 'exit':
return 'exit'
letter_in_text = list()
repet_in_text = list()
for letter in char_sequence:
if letter != ' ':
repet = 0
try:
letter_in_text.index(letter)
except ValueError:
letter_in_text.append(letter)
for verifyLetter in char_sequence:
if verifyLetter == letter:
repet += 1
repet_in_text.append(repet)
##print(letter_in_text)
##print(repet_in_text)
return exist(repet_in_text, letter_in_text)
def main():
char_sequence = str(input('Escribe una secuencia de caracteres: '))
result = first_not_repeating_char(char_sequence)
if result == '_':
print('Todos los caracteres se repiten.')
elif result == 'exit':
return 'exit'
else:
print('El primer caracter no repetido es: {}'.format(result))
if __name__ == '__main__':
while True:
exit = main()
if exit == 'exit':
break
else: continue
|
name = str(input('¿Cual es tu Nombre?: '))
print('Hola, ' + name + '!')
print('Ejemplo de Funcion.')
def suma(dato1, dato2):
return dato1 + dato2
print('Suma: '+ str(suma(2,3)))
|
class Student(object):
def __init__(self,name,value):
self.name = name
self.value = value
bar = Student('s',3)
print(bar.name)
print(bar.value)
|
import threading
global_dict = {}
def std_thread():
std = '1212'
# 把std放到全局变量global_dict中:
global_dict[threading.current_thread()] = std
print(len(global_dict),std,threading.current_thread())
do_task_1()
do_task_2()
def do_task_1():
# 不传入std,而是根据当前线程查找:
std = global_dict[threading.current_thread()]
print(len(global_dict),std,threading.current_thread())
def do_task_2():
# 任何函数都可以查找出当前线程的std变量:
std = global_dict[threading.current_thread()]
print(len(global_dict),std,threading.current_thread())
# std_thread()
local_school = threading.local()
def process_thread(name):
local_school.student= name
# 记住这里不能用process_thread的名称,会导致thread无法识别参数个数
process_thread1()
def process_thread1():
std = local_school.student
print('Hello, %s (in %s)' % (std, threading.current_thread().name))
t1 = threading.Thread(target=process_thread, args=('Alice',), name='Thread-A')
t2 = threading.Thread(target=process_thread, args=('Bob',), name='Thread-B')
# t1.start()
# t2.start()
# t1.join()
# t2.join()
from multiprocessing import Pool
if __name__ == '__main__' :
pool = Pool(4)
for i in range(100):
pool.apply_async(process_thread,args=('Alice',))
pool.apply_async(process_thread,args=('Bob',))
pool.close()
pool.join()
# t1.start()
# t2.start()
# t1.join()
# t2.join() |
import time,threading
def loop():
n = 0
while n<5:
n = n + 1
print('thread %s >>> %s' % (threading.current_thread().name, n))
time.sleep(0.1)
print('thread %s ended.' % threading.current_thread().name)
print('thread %s is running...' % threading.current_thread().name)
t =threading.Thread(target=loop,name='lt')
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)
'''
lock
'''
balance = 0
lock = threading.Lock()
def run_thread(n):
for i in range(100000):
# 先要获取锁:
lock.acquire()
try:
# 放心地改吧:
change_it(n)
finally:
# 改完了一定要释放锁:
lock.release()
import multiprocessing
print('cpu:' , multiprocessing.cpu_count())
'''
因为Python的线程虽然是真正的线程,但解释器执行代码时,有一个GIL锁:Global Interpreter Lock,任何Python线程执行前,必须先获得GIL锁,然后,每执行100条字节码,解释器就自动释放GIL锁,让别的线程有机会执行。这个GIL全局锁实际上把所有线程的执行代码都给上了锁,所以,多线程在Python中只能交替执行,即使100个线程跑在100核CPU上,也只能用到1个核。
GIL是Python解释器设计的历史遗留问题,通常我们用的解释器是官方实现的CPython,要真正利用多核,除非重写一个不带GIL的解释器。
所以,在Python中,可以使用多线程,但不要指望能有效利用多核。如果一定要通过多线程利用多核,那只能通过C扩展来实现,不过这样就失去了Python简单易用的特点。
不过,也不用过于担心,Python虽然不能利用多线程实现多核任务,但可以通过多进程实现多核任务。多个Python进程有各自独立的GIL锁,互不影响
''' |
#!/usr/bin/python3
# My method to determine the type of a variable
# uses different hashes to store values.
# e.g. all numbers go to %numbers
# all strings go to %strings
# all arrays go to %arrays
# all dicts go to %dicts
# the code below is a problem for me, because
# it will place "a" into the numbers hash.
# when it is reassigned to an array, it will
# also be put in the arrays hash.
# therefore my code will not know how to tell whether the
# variable "a" is a number or an array.
a = 5
a = ['test', 'script', 'five']
print(a)
# my translations -> print($@a)
# required -> print(@a)
|
#!/usr/bin/python3
# tests user input -> sys.stdin.readline()
# tests arrays, range with 1 arg, range with variable
# single line if statement, append(), continue
# array indexing
import sys
print("Enter a number between 100 and 200")
user_num = int(sys.stdin.readline())
i = 0
even_arr = []
for i in range(user_num):
if i % 2 == 0: even_arr.append(i); i += 1
if i % 2 != 0: i += 1; continue
print("The length of even_arr is ", len(even_arr))
for i in range(user_num/2):
print(even_arr[i], " is even")
|
class price():
def __init__(self, goods):
self.goods=goods
def printPrice(self):
if self.goods=='hamburger':
print('2$')
elif self.goods=='coca':
print('1$')
goods1=price('hamburger')
goods1.printPrice()
|
import numpy as np
import matplotlib.pyplot as plt
'''
How might we solve a set of linear equations?
This is the simplest case: two relations and two
unknowns.
3x0 + x1 = 9
x0 + 2x1 = 8
Or in another form, we are solving for x where:
Ax = b
| 3 1 |
A = | 1 2 |
| 9 |
b = | 8 |
'''
if __name__ == '__main__':
A = np.array([
[3, 1],
[1, 2],
])
b = np.array([9, 8])
x = np.linalg.solve(A, b)
# Note that @ is the matrix multiplication operator
print(f'Solution: {x}\n\n'
'Ax - b = \n\n'
f'{A} {x} - {b} = \n\n'
f'{A @ x} - {b} = \n\n'
f'{A @ x - b}\n')
'''
We just directly solved this set of linear equations
because we were fortunate enough to have the same number
of equations as we had unknowns (aka our matrix was square).
If we are not so fortunate however, we will have to use an
approximation, like so.
Let us solve the following set of equations:
x0 + 2x1 + x2 = 4
x0 + x1 + 2x2 = 3
2x0 + x1 + x2 = 5
x0 + x1 + x2 = 4
Or alternately,
Ax = b where
|1 2 1|
|1 1 2|
|2 1 1|
A = |1 1 1|
| 4 |
| 3 |
| 5 |
and b = | 4 |
'''
A = np.array([
[1, 2, 1],
[1, 1, 2],
[2, 1, 1],
[1, 1, 1],
])
b = np.array([
4,
3,
5,
4,
])
'''
This is the 'magic' function that will do all our dirty
work for us.
We don't expect the result of Ax - b to equal zero exactly,
as this is a least-squares approximation at the solution.
'''
x, residuals, rank, s = np.linalg.lstsq(A, b, rcond=None)
print(f'Solution: {x}\n\n'
'Ax - b = \n\n'
f'{A} {x} - {b} = \n\n'
f'{A @ x} - {b} = \n\n'
f'{A @ x - b}\n')
'''
Try to regress over the following relationship:
Ax = b where
| 0 1.1 |
| 1 0 |
A = | 0 -0.2 |
| 1.1 |
| -1.1 |
and b = | -.2 |
'''
'''
When you are ready, uncomment these lines and
compute the least squares yourself.
A = []
b = []
if not np.allclose(A @ x - b, [ 0, 0, 0 ]):
print('Nope! Your solution is not close enough.')
exit(1)
else:
print(f'Solution: {x}\n\n'
'Ax - b = \n\n'
f'{A} {x} - {b} = \n\n'
f'{A @ x} - {b} = \n\n'
f'{A @ x - b}')
'''
|
import fractions
import collections
# Resource : http://www.nku.edu/~christensen/section%206%20multiplicative%20ciphers.pdf
def findModInverse(a, m):
#if gcd(a, m) != 1:
# return None # no mod inverse exists if a & m aren't relatively prime
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m
while v3 != 0:
q = u3 // v3 # // is the integer division operator
v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
return u1 % m
plaintext=raw_input("Enter Plain Text\t")
key=input("Enter key\t")
#check if multiplicative inverse exists
gcd=fractions.gcd(key, 26)
if gcd == 1 :
plaintext = plaintext.replace(' ', '')
ciphertext=""
for char in plaintext:
char= chr( ( ( ( ord(char) -97 ) *key)%26)+97)
ciphertext=""+ciphertext+""+char+""
print "Cipher Text : "+ciphertext
#find multiplicative inverse of key
modinv=findModInverse(key,26)
plaintext=""
for char in ciphertext:
char= chr( ( ( ( ord(char) -97 ) *modinv)%26)+97)
plaintext=""+plaintext+""+char+""
print "\nPlain Text: "+plaintext
elif gcd!=1 :
print "The multiplicative cipher for "+str(key)+" does not exist. Try another key."
'''
# rhea @ rhea-Lenovo in ~/Documents/gittest/Cryptography-and-System-Security on git:master x [23:49:11]
$ python multiplicativecipher.py
Enter Plain Text y
Enter key 3
Cipher Text : u
Plain Text: y
# rhea @ rhea-Lenovo in ~/Documents/gittest/Cryptography-and-System-Security on git:master x [23:51:36]
$ python multiplicativecipher.py
Enter Plain Text rhea
Enter key 3
Cipher Text : zvma
Plain Text: rhea
# rhea @ rhea-Lenovo in ~/Documents/gittest/Cryptography-and-System-Security on git:master x [23:51:51]
$ python multiplicativecipher.py
Enter Plain Text zvma
Enter key 9
Cipher Text : rhea
Plain Text: zvma
'''
|
def main():
"Main function to test timestwo generated code"
from timestwoPython import timestwo
# Call initialize function to set up any necessary state
print("Calling initialize")
timestwo.timestwo_initialize()
m = 2
n = 3
numel = m*n
# Input data
input = timestwo.doubleArray(numel)
for i in range(0,numel):
input[i] = i
print("Initial data")
print_array(input, numel)
# Result data
result = timestwo.doubleArray(numel)
# Call entry-point
timestwo.timestwo(input.cast(), result.cast())
# Gather returned data
print_array(result, numel)
# Call terminate function to perform any necessary clean up
print("Calling terminate")
timestwo.timestwo_terminate()
def print_array(d, n):
"Print out values in a doubleArray"
if n == 0:
print("Empty array")
return
for i in range(0,n-1):
print("{0:g},".format(d[i]))
print("{0:g},".format(d[n-1]))
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
'''
Find the non-duplicate number:
Given a list of numbers, where every number shows up twice except for one number, find that one number.
'''
def single_number(nums):
result = 0
for n in nums:
result ^= n
return result
def main():
nums = [4, 3, 2, 4, 1, 3, 2] # result should be 2
print(sum(nums))
result = single_number(nums)
print(result)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
import sys
def read_matrix(N):
matrix = []
for _ in range(N):
matrix.append([int(num) for num in sys.stdin.readline().split()])
return matrix
def rotate_matrix(matrix, N):
final = ''
for i in range(N):
for row in reversed(matrix):
final += str(row[i]) + ' '
final = final.strip() + '\n'
print(final)
def main():
for line in sys.stdin:
N = int(line)
if N == 0:
break
matrix = read_matrix(N)
rotate_matrix(matrix, N)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
'''
Merge List Of Number Into Ranges:
Given a sorted list of numbers, return a list of strings that represent all of the consecutive numbers.
'''
def find_ranges(nums):
start = nums[0]
end = nums[0]
ranges = []
for i in range(len(nums)):
if nums[i] == end+1 or nums[i] == end:
end = nums[i]
else:
ranges.append(str(start) + '->' + str(end))
start = nums[i]
end = nums[i]
ranges.append(str(start) + '->' + str(end))
print(ranges)
def main():
nums = [0, 1, 2, 5, 7, 8, 9, 9, 10, 11, 15]
find_ranges(nums)
if __name__ == '__main__':
main()
|
#!/usr/bin/python3
# -*- encoding: utf-8 -*-
'''
@File : Algorithm.py
@Time : 2020/03/31 14:09:45
@Author : Boxt
@Version : 1.0
@Desc : common stack operations
@Desc_zh : 常见的栈操作
'''
'''
数制转换
表达式求值
'''
from typing import List
'''
顺序栈,使用数组实现
'''
class SequenceStack:
def __init__(self, n: int):
if n <= 0:
raise "栈的大小不能小于1"
self.stackArr = [-1] * n # 栈
self.length = n # 栈的规定大小
self.top = -1 # 栈顶指针
# 入栈操作
def push(self, data) -> bool:
if self.top == self.length - 1:
return False
self.top += 1
self.stackArr[self.top] = data
return True
# 出栈操作
def pop(self) -> int:
if self.top < 0:
return None
data = self.stackArr[self.top]
self.top -= 1
return data
def isEmpty(self) -> bool:
if self.top < 0:
return True
else:
return False
def getTop(self) -> int:
if self.top < 0:
return None
return self.stackArr[self.top]
def getDataStr(self) -> str:
dataStr = ''
index = self.top + 1
while index:
index -= 1
dataStr += str(self.stackArr[index])
return dataStr
'''
链式栈,使用链表实现
'''
class Node:
def __init__(self, data: int, _next = None):
self.data: int = data
self.next: Node = _next
class LinkedStack:
def __init__(self, n: int):
if n <= 0:
raise "栈的大小不能小于1"
self.length = n # 栈的规定大小
self.count = 0 # 栈的实际长度
self.top = None # 栈顶指针
def push(self, data) -> bool:
if self.count == self.length:
return False
node = Node(data, self.top)
self.top = node
self.count += 1
return True
def pop(self) -> int:
if self.count == 0:
return None
data = self.top.data
self.top = self.top.next
self.count -= 1
return data
def isEmpty(self) -> bool:
if self.count == 0:
return True
else:
return False
def getTop(self) -> int:
if self.count == 0:
return None
return self.top.data
def getDataStr(self) -> str:
dataStr = ''
node = self.top
while node:
dataStr += str(node.data) + ''
node = node.next
return dataStr
def printStr(self) -> str:
printStr = ''
node = self.top
while node:
printStr += str(node.data) + ' -> '
node = node.next
printStr += 'End'
return printStr
'''
数制转换
表达式求值
'''
class StackSolutions:
'''
十进制与其他进制间的转换
@param number 十进制数字
@param number 转换的进制
'''
def decimalBinaryConverter(self, number: int, binarySystem: int) -> str:
stack = SequenceStack(100)
# stack = LinkedStack(100)
if number < binarySystem:
return self.convertNumber(number)
while number > 0:
stack.push(self.convertNumber(number % binarySystem))
number = int(number / binarySystem)
return stack.getDataStr()
'''
转换进制中的特殊字符
字符A 的 ascii 码为65,对应十进制的 10,所以用十进制数字 + 55 就是特殊字符的 ascii 码
'''
def convertNumber(self, number: int) -> str:
if number < 10:
return str(number)
else:
return chr(number + 55)
'''
表达式求值,leetcode 150
'''
def evalRPN(self, tokens: List[str]) -> int:
# stack = SequenceStack(50)
stack = LinkedStack(50)
for x in tokens:
if x not in '+-*/':
stack.push(int(x))
else:
num2 = stack.pop()
num1 = stack.pop()
stack.push(self.getResult(num1, num2, x))
return stack.pop()
'''
升级版表达式求值
输入的不是数组,而是直接的表达式字符串,不考虑表达式不成立、空格、存在负数的情况
题目分析:
1. 运算的优先级:括号内的子表达式 > 乘除 > 加减,在括号里的子表达式遵循的也是 乘除 > 加减,所以在实际的实现中,其实是 乘除 > 括号内部 > 加减
2. 数字字符串需要转换成数字
3. 做减法时,改为加一个负数
代码实现:
1. 使用两个栈,一个用来存放数字(数字栈),一个用来存放运算符和括号(运算栈)
2. 字符为左括号时,不进行任何操作,直接推入运算栈中
3. 字符为右括号时,计算出与它对应的左括号(运算栈持续出栈操作后遇到的第一个左括号)组成的表达式的值,推入数字栈中
4. 字符为运算符时,如果是乘除的话,计算表达式,如果是减号的话,改为加一个负数
'''
# 10*(6/((9+3)*11))+17+5-6 = 16
# ((2+1)*3) = 9
# 4+(13/5) = 6
# 2*3*6-4 = 32
# 4+2*3*6-4 = 36
# (12+33*8)*10 = 2796
# 4+6/2/3 = 5
# 4+2*3*6-4+(12+33*8)*10 = 4076
# 3+4-5+8 = 10
# 1+2-1/1/1/1/1+100 = 102
# 1+1-1-1-1-1 = -2
# 10/(2+3) = 2
def evalRPNHard(self, exp: str) -> str:
# numStack = SequenceStack(50)
# expStack = SequenceStack(50)
numStack = LinkedStack(50) # 存放数字
expStack = LinkedStack(50) # 存放运算符和括号
priority = { # 运算符的优先级
'+': 1, '-': 1,
'*': 2, '/': 2,
}
numStr = ''
for x in exp:
if x == '(':
expStack.push(x)
elif x == ')':
numStr = self.pushNumByStr(numStack, numStr)
numStack.push(self.getInnerResult(priority, numStack, expStack))
elif x not in '+-*/':
numStr += x
else:
numStr = self.pushNumByStr(numStack, numStr)
higherResult = self.getHigherPriorityResult(priority, numStack, expStack, x)
if higherResult:
numStack.push(higherResult)
if x == '-':
numStr = self.pushNumByStr(numStack, numStr)
numStr += x
x = '+'
expStack.push(x)
self.pushNumByStr(numStack, numStr)
return self.getSamePriorityResult(numStack, expStack)
'''
数字字符串转换为数字,并推入数字栈中
'''
def pushNumByStr(self, numStack: LinkedStack, numStr: str):
if numStr:
numStack.push(int(numStr))
numStr = ''
return numStr
'''
计算括号内子表达式的值
'''
def getInnerResult(self, priority, numStack: LinkedStack, expStack: LinkedStack) -> int:
exp = expStack.pop()
result = numStack.pop()
while exp and exp != '(':
num = numStack.pop()
result = self.getResult(num, result, exp)
exp = expStack.pop()
return result
'''
计算高优先级表达式的值
'''
def getHigherPriorityResult(self, priority, numStack: LinkedStack, expStack: LinkedStack, x: str) -> int:
e = expStack.getTop()
result = None
if not e:
return result
result = numStack.pop()
while priority.get(e, 0) > 1:
num = numStack.pop()
result = self.getResult(num, result, e)
expStack.pop()
e = expStack.getTop()
return result
'''
计算相同优先级表达式的值
'''
def getSamePriorityResult(self, numStack: LinkedStack, expStack: LinkedStack) -> int:
result = numStack.pop()
while not numStack.isEmpty():
n = numStack.pop()
e = expStack.pop()
result = self.getResult(n, result, e)
return result
'''
计算操作
'''
def getResult(self, num1: int, num2: int, exp: str) -> int:
if exp == '-':
return num1 - num2
elif exp == '*':
return num1 * num2
elif exp == '/':
return int(num1 / num2)
else:
return num1 + num2
|
"""
GPS (Gopher Population Simulator)
A secret population of 1000 gophers lives near the library. Every year, a random number of gophers is
born, between 10% of the current population, and 20%. (e.g. 15% of the gophers might give birth,
increasing the population by 150). Also each year, a random number of gophers die, between 5% and
25% (e.g. 8% of the gophers might die, reducing the population by 80).
"""
from random import randrange
from time import sleep
def main():
gopher_population = 1000
print("Welcome to Gopher Population Simulator!\nStarting population {}".format(gopher_population))
amount_of_years = valid_years()
for year in range(amount_of_years):
print("YEAR {}\n***************".format(year + 1))
gopher_population = gopher_population_modifier(gopher_population)
sleep(1)
if gopher_population <= 0:
print("All the gophers have died :(")
break
print("Thanks for watching the gophers :)")
def gopher_population_modifier(current_population):
""" Function modifies and returns the gopher population and prints the changes."""
births = int(current_population * (randrange(10, 21) / 100))
deaths = int(current_population * (randrange(5, 26) / 100))
new_population = current_population + births - deaths
print("{} gophers were born :) {} gophers died :(\nTotal gopher population : {}\n".format
(births, deaths, new_population))
return new_population
def valid_years():
""" Function checks to see if years are an INT and within the range of 1 to 60."""
years_spent_watching = 0
while years_spent_watching <= 0 or years_spent_watching > 60:
try:
years_spent_watching = int(input("How many years do you want to watch the gophers for? : "))
if years_spent_watching > 60:
print("Please enter less than 60 years, you don't want to waste your life watching gophers do you?")
elif years_spent_watching <= 0:
print("Please enter a number larger than 0 so you can actually watch the gophers.")
except ValueError:
print(ValueError)
print("Invalid input, please enter a number of years.")
return years_spent_watching
main()
|
class Guitar:
"""Creates a Guitar object"""
def __init__(self, name, year, price):
self.name = str(name)
self.year = int(year)
self.price = float(price)
def __str__(self):
string_format = "{} manufactured in {} - Price ${:.2f}".format(self.name, self.year, self.price)
return string_format
def __lt__(self, other):
return self.year < other.year
def class_testing():
pass
if __name__ == "__main__":
class_testing()
|
"""
A modification of the score.py file that uses a function to return the appropriate value (string) for main() to print.
"""
def main():
score = float(input("Enter score: "))
assessed_grade = score_sorter(score)
print(assessed_grade)
def score_sorter(user_score):
""" This function sorts out an integer score value into a print statement. """
if user_score < 0 or user_score > 100:
return "Invalid score"
elif user_score >= 90:
return "Excellent"
elif user_score >= 50:
return "Passable"
else:
return "Bad"
main()
|
"""This is a class that creates guitar objects."""
VINTAGE_THRESHOLD = 50
CURRENT_YEAR = 2017
class Guitar:
def __init__(self, name="", year=0, price=0):
self.name = name
self.year = year
self.price = price
def __str__(self):
string_format = "{} ({}) : ${:.2f}".format(self.name, self.year, self.price)
return string_format
def get_age(self):
return CURRENT_YEAR - self.year
def is_vintage(self):
if CURRENT_YEAR - self.year > VINTAGE_THRESHOLD:
return True
else:
return False
|
check = True
while check:
name = input()
for i in name:
if i.isdigit() and len(name)>8:
check = False
|
from typing import List, Tuple
import pandas as pd
def load_data(path_real: str,
path_fake: str,
real_sep: str = ',',
fake_sep: str = ',',
drop_columns: List = None) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Load data from a real and synthetic data csv. This function makes sure that the loaded data has the same columns
with the same data types.
:param path_real: string path to csv with real data
:param path_fake: string path to csv with real data
:param real_sep: separator of the real csv
:param fake_sep: separator of the fake csv
:param drop_columns: names of columns to drop.
:return: Tuple with DataFrame containing the real data and DataFrame containing the synthetic data.
"""
real = pd.read_csv(path_real, sep=real_sep, low_memory=False)
fake = pd.read_csv(path_fake, sep=fake_sep, low_memory=False)
if set(fake.columns.tolist()).issubset(set(real.columns.tolist())):
real = real[fake.columns]
elif drop_columns is not None:
real = real.drop(drop_columns, axis=1)
try:
fake = fake.drop(drop_columns, axis=1)
except:
print(f'Some of {drop_columns} were not found on fake.index.')
assert len(fake.columns.tolist()) == len(real.columns.tolist()), \
f'Real and fake do not have same nr of columns: {len(fake.columns)} and {len(real.columns)}'
fake.columns = real.columns
else:
fake.columns = real.columns
for col in fake.columns:
fake[col] = fake[col].astype(real[col].dtype)
return real, fake
|
# prints a graph that when 5-colored can be used to paint the faces of a
# dodecahedron in 5 colored triangles each so that triangles that share a
# pentagon edge have the same color, but no two triangles on the same pentagon
# do.
N = 30
E = N * 8 / 2
adj = [[0 for i in range(N)] for j in range(N)]
def face(a, b, c, d, e):
adj[a][b] = adj[b][a] = 1
adj[a][c] = adj[c][a] = 1
adj[a][d] = adj[d][a] = 1
adj[a][e] = adj[e][a] = 1
adj[b][c] = adj[c][b] = 1
adj[b][d] = adj[d][b] = 1
adj[b][e] = adj[e][b] = 1
adj[c][d] = adj[d][c] = 1
adj[c][e] = adj[e][c] = 1
adj[d][e] = adj[e][d] = 1
face(0, 1, 2, 3, 4)
face(0, 5, 9, 14, 15)
face(5, 4, 6, 17, 16)
face(6, 3, 7, 19, 18)
face(7, 2, 8 ,11, 10)
face(9, 1, 8, 12, 13)
face(13, 14, 23, 27, 22)
face(23, 28, 24, 16, 15)
face(24, 29, 20, 17, 18)
face(21, 25, 20, 19, 10)
face(21, 26, 22, 12, 11)
face(25, 26, 27, 28, 29)
#for l in adj:
#print sum(l) # should be 8
#print l
from math import *
print 'graph dodecahedron {'
# 0 - 4
for i in range(5):
y = -50 * cos(i * 2 * pi / 5)
x = -50 * sin(i * 2 * pi / 5)
print ' %d [pos="%f,%f"];' % (i, x, y)
# 5 - 9
for i in range(5):
y = 100 * cos(i * 2 * pi / 5 + 6*pi/5)
x = -100 * sin(i * 2 * pi / 5 + 6*pi/5)
print ' %d [pos="%f,%f"];' % (i + 5, x, y)
# 10 - 19
for i in range(10):
y = 150 * cos(i * 2 * pi / 10 + pi/10)
x = -150 * sin(i * 2 * pi / 10 + pi/10)
print ' %d [pos="%f,%f"];' % (i + 10, x, y)
# 20 - 24
for i in range(5):
y = 255 * cos(i * 2 * pi / 5 - 2*pi/10)
x = -255 * sin(i * 2 * pi / 5 - 2*pi/10)
print ' %d [pos="%f,%f"];' % (i + 20, x, y)
# 25 - 29
for i in range(5):
y = -350 * cos(i * 2 * pi / 5 + 10*pi/10)
x = 350 * sin(i * 2 * pi / 5 + 10*pi/10)
print ' %d [pos="%f,%f"];' % (i + 25, x, y)
for i in range(N):
for j in range(i + 1, N):
if adj[i][j] and not (i >= 25 and j >= 25):
print ' %d -- %d;' % (i, j)
print '}'
|
# coding: utf-8
# In[2]:
d={'a':1,'b':2,'c':3}
for key in d:
print(key)
# In[5]:
for ch in 'ABC':
print(ch)
# In[1]:
#判断是否可迭代
from collections import Iterable
print(isinstance('abc',Iterable))
print(isinstance([1,2,3],Iterable))
print(isinstance(123,Iterable))
# In[8]:
for i,value in enumerate(['A','B','C']):
print(i,value)
print(enumerate(['A','B','C']))
#enumerate是枚举,列举的意思
#如果对于一个列表,既要遍历索引又要遍历元素时,首先可以这样写
list1 = ["这", "是", "一个", "测试"]
for i in range (len(list1)):
print(i ,list1[i])
print('\n')
#但这样很麻烦,所以可以用enumrate这样写
for i,value in enumerate(list1):
print(i,value)
print('\n')
#enumerate还可以接受第二个参数,用于指定初始索引
for i,value in enumerate(list1,1):
print(i,value)
print('\n')
# In[9]:
#在for循环里,同时引用两个变量
for x,y in [(1,1),(2,2),(3,3)]:
print(x,y)
# In[ ]:
#end
|
# coding: utf-8
# In[3]:
'''
如果要让内部属性不被外部访问,可以把属性的名称前加上
两个下划线__,在Python中,实例的变量名如果以__开头,
就变成了一个私有变量(private),只有内部可以访问,外
部不能访问,
'''
class student(object):
def __init__(self,name,score):
self.__name=name
self.__score=score
def print_score(self):
print('%s: %s' %(self.__name,self.__score))
'''
改完后,对于外部代码来说,没什么变动,但是已经无法从外部
访问实例变量.__name和实例变量.__score了:只能通过类内的方法
才可以调用这些私有变量
'''
bart = student('Bart Simpson', 98)
bart.print_score()
print(bart.__name)
# In[4]:
'''
如果外部想要获取name和score怎么办,
给student类添加get_name和get_score
外部想要修改怎么办,set_score
需要注意的是,在Python中,变量名类似__xxx__的,
也就是以双下划线开头,并且以双下划线结尾的,是特殊变量,
特殊变量是可以直接访问的,不是private变量,所以,不能用
__name__、__score__这样的变量名。
有些时候,你会看到以一个下划线开头的实例变量名,比如_name
,这样的实例变量外部是可以访问的,但是,按照约定俗成的规定,
当你看到这样的变量时,意思就是,“虽然我可以被访问,但是,
请把我视为私有变量,不要随意访问”。
双下划线开头的实例变量是不是一定不能从外部访问呢?其实也不是。
不能直接访问__name是因为Python解释器对外把__name变量改成了_Student__name,
所以,仍然可以通过_Student__name来访问__name变量:
'''
print(bart._student__name)#好神奇
#但是强烈建议你不要这么干,因为不同版本的Python解释器可能会把__name改成不同的变量名。
# In[5]:
#所以如果外界对实例化对象设置私有变量的值,因为上面说了
#私有变量会被改名为 _student__name这样,所以如果使用
#bart.__name='New Name',则表示在该对象内新建一个变量
#不影响本来的__name
bart.__name='New name'
bart.print_score()
#out[]: Bart Simpson: 98
# In[ ]:
|
import heapq
import math
import random
def bubble_sort(arr):
swap = True
count = 0
for i in range(len(arr) - 1): # only to n-2 because inner loop will
# cause last element to be largest after first pass
swap = False;
for j in range(
len(arr) - i - 1): # Wont check already updated elements
count += 1
if arr[j] > arr[j + 1]:
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
swap = True
if not swap:
print(count)
return
print(count)
return
def insertion_sort(arr: list):
for j in range(1, len(arr)):
insert = arr[j]
i = j - 1
while i >= 0 and insert < arr[i]: # stable, right to left
arr[i + 1] = arr[i]
i -= 1
arr[i + 1] = insert
def quick_sort(arr, left, right):
if left >= right:
return
p = partition(arr, left, right)
quick_sort(arr, left, p - 1)
quick_sort(arr, p + 1, right)
def heap_sort(arr):
n = len(arr)
heapify(arr)
for i in range(len(arr)-1, 0, -1):
arr[0], arr[i] = arr[i], arr[0]
sift_down(arr, 0, i)
def heapify(arr: list) -> None: # In place, linear time max-heap function
"""
A linear time, in place function for creating a max-heap
:param arr: Array to be turned into a max-heap
"""
for i in range(len(arr) - 1, -1, -1):
sift_down(arr, i, len(arr))
def sift_down(arr: list, node: int, n) -> None:
"""
A log(h) time function to be used on an array node to heapify a subtree.
Works bottom-up, as in parents smaller than children will swap,
and iteratively continues.
:param arr: Array to be sifted through
:param node: Current parent node index of interest
:param n: Size of array/tree
"""
index = node
if index >= n or index*2 + 1 >= n :
return
has_left_child = True
left_child = arr[index * 2 + 1]
has_right_child = True if index * 2 + 2 < n else False
if has_right_child:
right_child = arr[index * 2 + 2]
else:
right_child = None
while has_left_child and arr[index] < arr[index * 2 + 1] or (
has_right_child and arr[index] < arr[index * 2 + 2]):
if has_left_child and has_right_child:
max_child_index = 2 * index + 1 if left_child >= right_child \
else 2 * index + 2
else:
max_child_index = 2 * index + 1
arr[max_child_index], arr[index] = arr[index], arr[max_child_index]
index = max_child_index
if index*2 + 1 >= n:
return
else:
left_child = arr[index*2 + 1]
has_right_child = True if index * 2 + 2 < n else False
if has_right_child:
right_child = arr[index * 2 + 2]
def partition(arr, left, right):
pivot = arr[left]
i, j = left + 1, right
while True: # consider even or odd length lists
while i <= j and arr[i] <= pivot:
i += 1
while i <= j and arr[j] >= pivot:
j -= 1
if i <= j:
arr[j], arr[i] = arr[i], arr[j]
else:
break
arr[left], arr[j] = arr[j], arr[left] # swap pivot in
return j
def digit_ordering(arr, max):
num_digits = math.ceil(math.log(max, 10))
digits_organized = [[] for i in range(10)]
for i in range(num_digits):
for j in range(len(arr)):
digit = int((arr[j] // math.pow(10, i))) % 10
digits_organized[digit].append(arr[j])
arr[:] = [leaves for tree in digits_organized for leaves in tree]
for sublist in digits_organized:
sublist.clear()
test = [elem for sublist in digits_organized for elem in sublist]
return digits_organized
if __name__ == '__main__':
arr = [3, 11, 15, 2, 12, 9]
arr2 = [3, 5, 9, 12, 20, 46]
rand_arr = [random.randint(0, 820) for i in range(175)]
rand_arr2 = [random.randint(0, 820) for i in range(175)]
heap_sort(arr)
print(arr)
heap_sort(rand_arr)
print(rand_arr)
# # print("The array contents are: %s", arr)
#
# x = digit_ordering(rand_arr, 820)
# # print(x)
#
# quick_sort(arr, 0, len(arr) - 1)
# # print("The array contents are: %s", arr)
# print(rand_arr2)
# heapq._heapify_max(rand_arr2)
# print(rand_arr2.pop())
# print(rand_arr2)
# heap_sort(rand_arr2)
# print("Also, the array: ", rand_arr2)
#
# insertion_sort(arr)
|
# Going along a list backwards
my_list = ['alpha', 'beta', 'gamma']
# Method 1
for x in my_list[::-1]:
print(x)
# Method 2
for y in reversed(my_list):
print(y)
|
# Generating and printing
# Fibonacci numbers
# below 100
a, b = 0, 1
while a < 100:
print(a)
a, b = b, a + b
# Notice how nice is
# multiple assignment |
# Imagine you have a loop over a list
data = [1, 3, 5, 7, 9]
for i in range(len(data)):
# but you want to use indices
print(data[i])
# Question: how many times does Python
# call "len(data)"?
# And how many times "range"? |
# Ways to create a tuple
t1 = 10, 20, 30
t2 = (10, 20, 30)
t3 = 10, # single element in a tuple
t4 = (10,)
t5 = tuple([10, 20, 30])
print(type(t1))
print(type(t2))
print(type(t3))
print(type(t4))
print(type(t5))
|
# Calculator that parses operations
ops = { # operations
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
}
def calc(x, y, op): # op = operator
return ops[op](x, y)
print(calc(3, 4, '+')) # 7
print(calc(3, 4, '-')) # -1
print(calc(3, 4, '*')) # 12
print(calc(3, 4, '/')) # 0.75
|
# How many bits does your integer
# need in memory?
i = 34
print(i.bit_length())
i = 340
print(i.bit_length())
i = 34238459238539284329572395832
print(i.bit_length())
|
# Iterating over a dictionary is...
data = {
"France": "Paris",
"Germany": "Berlin",
"Italy": "Rome"
}
for x in data:
# for x in data.keys(): # the same
print(x)
# what is x?
# these are the keys |
# Reading from a JSON file
# Let us improve this program a bit
import json
data = []
with open('capitals.json') as f:
data = json.load(f)
# Here, the file is still open
# Now the file is closed
for x in data:
print(
x["country"], '—',
x["capital"]
)
|
# Reading the last line from a file
import os
with open('lines.txt') as f:
# Go to the last character
last = f.seek(0, os.SEEK_END)
while last: # while last != 0
last = last - 1
f.seek(last)
if f.read(1) == "\n":
# Found the first newline
# character from the
# end of file
print(f.readline())
# Read the rest from
# that position
break |
# Use "pass" to do nothing :-)
x = 0
while x < 8:
x += 1
if x == 4:
pass
# you need a block
# here, so if you have
# nothing to do,
# type "pass"
print(x)
|
# Creating custom iterators
class C:
def __iter__(self):
self.n = 0
return self
def __next__(self):
# Let's stop when n = 3
if self.n == 3:
raise StopIteration
self.n += 1
return self.n
c = C()
i = iter(c) # get an iterator
for _ in range(5):
try: # exception has to be caught
print(next(i))
except:
break |
# Convert a list of tuples
# to a list of lists
data = [
(3, 4), (7, 8), (100, 200)
]
# Using list comprehension
data2 = [
# "a" was a tuple here
list(a) for a in data
]
print(data2) |
# Let's see another paradigm
# you can use with conditional
# statements
for i in range(1, 5):
# is i odd or even?
# oe = 'odd' if i % 2 else 'even'
print('odd') if i % 2 else print('even')
# print(f'{i} is {oe}')
|
# Deleting a variable
x = 42
print(x)
# Now delete it
del(x)
print(x) # will not be able to print |
# Find the minimum and maximum
# values WITHOUT using the "min"
# and "max" functions
data = [3, 4, 77, 1, 34, 7]
min_val = data[0]
max_val = data[0]
# normally do this:
# print(min(data))
# print(max(data))
for x in data:
if x < min_val:
min_val = x
if x > max_val:
max_val = x
print(min_val)
print(max_val) |
# The "for" loop can have an
# "else" clause
for i in range(5):
print(i)
if i == 3:
break
else:
print('done') # printed after
# the end of the loop
# but only if the loop finished
# successfully |
# Find the first repeating element
# in a list, print it and quit
data = [3, 5, 7, 5, 9, 11]
# 5 is the answer
# "Slow" method first
for x in data:
if data.count(x) > 1:
print(x)
break
|
# How to push data to a list
# and how to pop it back
data = []
for i in range(5):
data.append(i * i)
# fill with some data
while(len(data)):
# while list is not empty
value = data.pop() # take from
# back
print(value)
# Printed in reverse order |
# Print ASCII values of all
# characters in a given
# string
str = 'Hello'
ascii = [ord(s) for s in str]
# ord() converts a character to
# its ASCII position number
print(ascii) |
# Raw strings in Python
# Regular string:
print('Hello, \nWorld!')
# "Raw" string
# prefixed with "r"
print(r'Hello, \nWorld!')
|
# Iterating over dictionary pairs
# (both keys and values)
capitals = {
'France': 'Paris',
'Italy': 'Rome',
}
for country, city in capitals.items():
# country = key
# city = value
print('The capital of ' + \
country + ' is ' + city + '.')
|
# What is the colour of a pixel?
from PIL import Image
img = Image.open('bird.png')
pixels = img.load()
clr = pixels[10, 10] # coords
# access as an matrix
print(clr)
# Also see the types:
print(type(pixels))
print(type(clr)) |
# How to print both
# indices and values
# of a list?
# Here is a list:
data = ['red', 'green', 'blue']
# Let us use a built-in function
# "enumerate"
for index, value in enumerate(data):
print('index =', index)
print('value =', value)
|
# Defining custom behaviour for
# the "len" function
class Phrase:
# our class keeps a phrase
def __init__(self, text):
# save it in an object
self.text = text
# Let "len" return the number
# of words in the phrase
def __len__(self):
# Count spaces
return 1 + self.text.count(' ')
# Use the class:
phrase = Phrase("Hello World")
print(len(phrase)) # 2
|
word_a = 'hello'
word_b = 'world'
# Sets of letters in the words;
# each letter appears only once
in_a = set(word_a)
in_b = set(word_b)
# Difference between the two sets
common = in_a.intersection(in_b)
# Also works for this task:
# common = in_b.intersection(in_a)
# Print common letters
print(common) # {'l', 'o'}
|
# Need a ternary operator?
# Use conditional expression
for i in range(1, 5):
# is i odd or even?
oe = 'odd' if i % 2 else 'even'
print(f'{i} is {oe}')
|
# Differences in the return type
# of "input()"
item = raw_input("Enter something: ")
print(type(item))
|
# reversed() vs .reverse()
a = ['alpha', 'beta', 'gamma']
b = reversed(a)
print(a) # original a
c = a.reverse()
print(a) # original a is broken
|
# NumPy operates with N-dimensional
# data
import numpy
data = numpy.array(
[
[1, 3, 5, 7],
[2, 4, 6, 8] # Two axes
]
)
print(data.shape) # 2 by 4
print(data.ndim) # 2 dimensions
print(data.size) # 8 elements
print(type(data)) # its class |
# Swapping the content
# of two variables
left = 'knife'
right = 'fork'
print(f'Before: {left}, {right}')
left, right = right, left
print(f'After: {left}, {right}') |
# You can open more than one file
# within a single "with":
# Open a.txt for reading,
# Open b.txt for writing ('w')
with \
open('a.txt') as a, \
open('b.txt', 'w') as b:
# For each line in a.txt
for line in a:
# copy it to b.txt
b.write(line)
|
# Split a string into numbers
# and words
import re # regular expressions
s = "3 bananas, 15 carrots, 10 apples"
nums = re.findall(r'(\d+)', s)
words = re.findall(r'([a-zA-Z]+)', s)
print(nums)
print(words) |
# Digits in the Unicode space
import re
count=0
for i in range(32, 10_000):
ch = chr(i) # character with
# the Unicode code i
if re.match('\d', ch):
# if re.match('\d', ch, re.ASCII):
# if it is a digit
print(ch, end='')
count+=1
print('')
print(count)
# How many digits will be printed? |
# Remove duplicates from a list
# and make sure the order is saved
data = [10, 12, 10, 33, 2, 2, 5, 2]
result = []
values = set()
for i in data:
if i not in values:
values.add(i)
result.append(i)
print(result)
|
# Quick sort algorithm
data = [4, 7, 1, 4, 8, 9, 3, 2, 5, 6]
def quicksort(data):
if len(data) <= 1:
return data
pivot = data[0]
left = []
right = []
for x in data[1:]:
if x < pivot:
left.append(x)
else:
right.append(x)
return quicksort(left) + \
[pivot] + quicksort(right)
data = quicksort(data)
print(data)
|
# Reading gzipped files
import gzip
# A built-in module
# Open the file
with gzip.open('info.txt.gz') as f:
# Read a byte literal
str = f.read()
# Convert to UTF-8 to print
print(str.decode('utf-8'))
|
# Test if all the numbers in a list
# are positive
data = [1, 2, 4, 7, 10]
if all(x > 0 for x in data):
print('All positive ints')
else:
print('No')
|
# Find the first repeating element
# in a list, print it and quit
data = [3, 5, 7, 5, 9, 11]
# 5 is the answer
# Faster method (for big data lists)
seen = set()
for x in data:
if x in seen:
print(x)
break
seen.add(x)
|
str = input('Type your phrase: ')
str = str.replace('a', 'A')
print(str)
|
# Splitting data into
# odd and even numbers
data = [
45, 56, 67, 23, 57, 78, 67, 454
]
odd = []
even = []
for d in data:
if d % 2:
odd.append(d)
else:
even.append(d)
print(f'Odd numbers: {odd}')
print(f'Even numbers: {even}') |
# Extracting and Sorting User with Line Number
file_name = 'password.txt' # File Location passing as variable
fp = open(file_name, 'r')
list_of_users = [] # Empty List defining to store the items
for line in fp:
user_info = line.split(':')
list_of_users.append(user_info[0]) # Appending to empty list
fp.close()
#print(list_of_users)
list_of_users.sort()
for item in list_of_users:
print(item )
print()
print(enumerate(list_of_users))
print()
# Iterate List item for its index, value
for item1, item2 in enumerate(list_of_users, 1):
print(item1, '->', item2) |
items = [2.2, 'pam', 'allen', 3.3, 'pip', 1.9, 'cpan', 3.4]
# By Index "pop" the element in list "Index"
#POPS the last element by Default
value = items.pop()
print(value)
print(items)
print()
# Delete By Value, By default it will remove the first occurence of the value
items = [2.2, 'pam', 'pam', 3.3, 'pip', 1.9, 'pam', 3.4]
item = 'pam'
items.remove(item)
print(items)
# Deleting the all the required value in List "use While Condition"
items1 = [2.2, 'pam', 'pam', 3.3, 'pip', 1.9, 'pam', 3.4]
ite = 'pam'
print(items1.count(ite)) # To Find the Count of the Element in Array
while ite in items1:
items1.remove(ite)
print()
print(items1)
# Deleting Only First Occurance of 'pam'. Functions are not available only Work Around
items2 = [2.2, 'pam', 'pam', 3.3, 'pip', 1.9, 'pam', 3.4]
it = 'pam'
first_occurance_pam = items2.index(it) # It will index the value
temp = items2[first_occurance_pam+1:] # It will slice the list and store in Variable
print(temp)
print()
# Below it will remove the value from the sliced
while items2 in temp:
temp.remove(it)
# It will concatenate the string
print(items2[:first_occurance_pam + 1] + temp) |
# RegExp Matching. It is case Sensitive and it will match only once in a line. It Match for Sub-Sting eg: Sunflower it match with Sun
import re
s = 'The python and the perl scripting'
pattern = 'P.+N' #
patterns = 'P.+?N' # Non-Greedy, Least occurenace to match and print
m = re.search(pattern, s)
print(m)
print()
n = re.search(patterns, s, re.I) # re.I to ignore Case sensitive
print(n)
if n:
print("match :", n.group())
before = s[:n.start()] # Print Before the Match content
after = s[n.end():] #Print content after the match content
print("before : |{}|".format(before))
print("after: |{}|".format(after))
else:
print('Failed to Match') |
# If Else Conditional
n = 4
result = n ** 2 if n > 5 else n ** 3
print(result)
# Membership Operator
s = 'This ia a python training'
print('ia' in s)
print('a p' in s)
print('bb' not in s)
print('bb' in s) |
import matplotlib.pyplot as plt
import numpy as np
# Deinerer en funksjon
def f(x):
return -x**2 + 25
x_verdier = []
y_verdier = []
for x in range(-5,6):
x_verdier.append(x)
y_verdier.append(f(x))
print("x-verdier: ", x_verdier)
print("y-verdier: ", y_verdier)
plt.plot(x_verdier, y_verdier)
plt.grid()
plt.show() |
def run():
dic={}
for i in range(1,101):
pow=i**3
if i%3!=0:
dic[i]=i**3
print(dic)
if __name__=='__main__':
run() |
import random
from decimal import *
instances=[0,0,0,0,0,0,0,0,0,0,0,0,0]
n=1
r=40
def drawCard():
return random.randint(2,14)
def printing(n,rand,r):
getcontext().prec=4
if 104-n==0 and r==0:
print(str(rand) + " " + str(r) + "/" + str(104-n) + "," + "0")
return
if rand < 11:
print(str(rand) + " " + str(r) + "/" + str(104-n) + "," + str(Decimal(r*100)/Decimal(104-n)))
if rand == 11:
print("Jack,"+ str(r) + "/" + str(104-n) + "," + str(Decimal(r*100)/Decimal(104-n)))
if rand == 12:
print("Queen,"+ str(r) + "/" + str(104-n) + "," + str(Decimal(r*100)/Decimal(104-n)))
if rand == 13:
print("King,"+ str(r) + "/" + str(104-n) + "," + str(Decimal(r*100)/Decimal(104-n)))
if rand == 14:
print("Ace,"+ str(r) + "/" + str(104-n) + "," + str(Decimal(r*100)/Decimal(104-n)))
def checkInstance(rand):
global instances
if instances[rand-2] == 8:
return False
else:
instances[rand-2] += 1
return True
def checkImportant(rand):
global r
if r == 0:
return False
elif rand > 9:
r-=1
print("Card,Fraction,Percentage")
while n < 105:
rand = drawCard()
check = checkInstance(rand)
if check == False:
continue
else:
checkImportant(rand)
printing(n,rand,r)
n += 1
|
class Car:
""" Objectice is to create a Car class which contains the owner's name, miles to drive and fuel required for driving.
Initally, the car has no fuel therefore it needs to be refilled.
Once refilled, the car can drive upto the required miles.
In case, there is not enough fuel to complete the miles, an indication will appear saying how much more is needed to be refilled.
The car can also refill from another car in case of an emergency if there is no petrol pump.
"""
def __init__(self, owner_name):
self.owner_name = owner_name
self.miles = 0
self.fuel = 0
def drive(self, miles):
fuel_req = miles * 3
if self.fuel == 0:
print(self.owner_name, "your fuel is", self.fuel, "Please refill.")
elif self.fuel < fuel_req:
print(self.owner_name, "you do not have enough fuel, you require", (fuel_req - self.fuel), "more for driving.")
else:
self.miles += miles
self.fuel -= fuel_req
print(self.owner_name, "you have driven", self.miles, "miles. The fuel is now", self.fuel)
def refill(self, fuel):
self.fuel += fuel
print(self.owner_name, "you have refilled", fuel, "and your current fuel is", self.fuel)
def transfer_from(self, another_car, fuel):
self.fuel += fuel
print(self.owner_name, "you have refilled", fuel, "and your current fuel is", self.fuel)
another_car.transfer_to(fuel)
def transfer_to(self, fuel):
self.fuel -= fuel
print(self.owner_name, "your fuel is now", self.fuel)
car_1 = Car('Stephen')
car_1.drive(10) # Stephen your fuel is 0 Please refill.
car_1.refill(20) # Stephen you have refilled 20 and your current fuel is 20
car_1.drive(10) # Stephen you do not have enough fuel, you require 10 more for driving.
car_1.refill(10) # Stephen you have refilled 10 and your current fuel is 30
car_1.drive(10) # You have driven 10 miles. The fuel is now 0
car_2 = Car('Jude')
car_2.refill(50) # Jude you have refilled 50 and your current fuel is 50
car_1.transfer_from(car_2, 10)
# Stephen you have refilled 10 and your current fuel is 10
# Jude your fuel is now 40 |
'''
display_sensor_true.py
Additional changes in the main need to done
'''
import pygame
from pygame import font
import random
from pathlib import Path
def _content(weight: float) -> list:
'''input: scale reading (weight)
returns a list of text that is written in the text bubble'''
CO2_val = weight * 0.3968316
display_list = [
[' ', ' ', ' ', 'Thank you for composting!',
'You just composted ' + str(weight) + ' ounces!'],
[' ', ' ', ' ', 'Thank you for composting!', 'You just helped avoid ' +
str(CO2_val) + ' ounces of carbon-equivalent emissions! '],
[' ', ' ', ' ', 'Thank you for composting!', ' Food waste is the single largest part of waste.', ' Keeping it out of landfills is important!']]
index = random.choice([0, 1, 2])
return display_list[index]
def drawText(surface, text_list: list, color, rect, font_height: int, aa=False, bkg=None):
# Wraps text and draws it inside the rect.
y = rect.top
# padding ratios have been calculated based on border and image dimensions.
pad_x = (0.1 * rect.width)
pad_y = (0.1 * rect.height)
pad_y_bottom = (0.24 * rect.height)
font = pygame.font.Font(None, font_height)
for text in text_list:
while text:
i = 1
# determine if the row of text will be outside our area
if (y + font_height + (2 * pad_y) + pad_y_bottom) > rect.bottom:
print("Could not fit in all the text. Please reduce font")
return
# determine maximum width of line
while font.size(text[:i])[0] < (rect.width - pad_x * 2) and i < len(text):
i += 1
# if we've wrapped the text, then adjust the wrap to the last word
if i < len(text):
text_to_find = " "
i = text.rfind(text_to_find, 0, i)
# render the line and blit it to the surface
if bkg:
image = font.render(text[:(i)], 1, color, bkg)
image.set_colorkey(bkg)
else:
image = font.render(text[:i], aa, color)
surface.blit(image, (rect.left + pad_x, y + pad_y))
y += font_height
# remove the text we just blitted
text = text[i:]
def scale_text_bubble(width, iwidth, height, iheight)->'scale':
# Scales the image to best fit. Assumed 1/5 of the screen as pad_x and pad_y
scale_x = ((3 / 5) * width) / iwidth
scale_y = ((3 / 5) * height) / iheight
scale = min(scale_x, scale_y)
if scale < 1:
scale = 1
return scale
def draw_text_bubble(screen, width, height)-> []:
# draws a text bubble with sufficient x and y padding. This function returns a list containing the surface, x_pad val and y_pad val.
text_bubble = pygame.image.load(str(Path('./assets/img/text_bubbles_transparent/white_crop_bubble.png')))
iwidth, iheight = text_bubble.get_size()
scale = scale_text_bubble(width, iwidth, height, iheight)
text_bubble = pygame.transform.scale(
text_bubble, (int(scale * iwidth), int(scale * iheight)))
swidth, sheight = text_bubble.get_size()
pad_x = (width - swidth) / 2
pad_y = (1 / 2) * (height - (sheight))
screen.blit(text_bubble, (pad_x, pad_y))
pygame.display.update()
return [text_bubble, pad_x, pad_y]
if __name__ == '__main__':
# To be added: if sensor_boolean= True:
pygame.init()
'''hardcoded values:
weight (for now) is set to 10.55
font_height will be adjusted to best fit the text in the bubble
'''
font_height = 30
weight = 10.55
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
width, height = screen.get_size()
ret_list = draw_text_bubble(screen, width, height)
text_bubble = ret_list[0]
x = ret_list[1]
y = ret_list[2]
rect = text_bubble.get_rect().move(x, y)
text_list = _content(weight)
drawText(screen, text_list, (128, 128, 128),
rect, font_height, aa=False, bkg=None)
pygame.display.update()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
break
pygame.quit()
|
# "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list)
# together with a format string, which contains normal text together with "argument specifiers"
# special symbols like "%s" and "%d"
name = "John"
print("Hello, %s!" % name)
# To use two or more argument specifiers, use a tuple (parentheses)
age = 23
print("%s is %d years old." % (name, age))
# Any object which is not a string can be formatted using the %s operator
# the string which returns from the "repr" method of that object is formatted as the string
mylist = [1,2,3]
print("A list: %s" % mylist)
# %s - String (or any object with a string representation, like numbers)
# %d - Integers
# %f - Floating point numbers
# %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot
# %x/%X - Integers in hex representation (lowercase/uppercase) |
"""
Some of the classes will include
Spot- This class represents one block of the 8*8 grid and another optional piece.
Piece- This class is the basic building block of the system, every piece will be placed on a spot.
From class piece, we can also create other class children which include, King, Queen, Knight and Bishop.
These are the abtract operations in the game.
Board- The class board is the 8*8 of the boxes containing all the active chess pieces
Player- Player class represents the participants playing the game and are the ones making the game complete.
Move- This class represents the game moves containing the starting and ending spots.
This class will also help to keep track of the player who made the move.
"""
# -*- coding: utf-8 -*-
"""
Module containing the basic class Piece, as well as a children class for each type of pieces in the chess game.
"""
# TODO: If your system does not correctly display the unicode characters of the chess game,
# set this constant (global variable) to False
USE_UNICODE = True
class Piece:
"""
A basic class representing a piece of the chess game. It is this class which is inherited below to provide
one class per type of piece (Pawn, Rook, etc.).
Attributes:
color (str): The color of the piece, either 'white' or 'black'.
can_jump (bool): Whether or not the piece can "jump" over other pieces on a chessboard.
Args:
color (str): The color with which to create the piece.
can_jump (bool): The value with which the attribute can_jump must be initialized.
"""
def __init__(self, color, can_jump):
# Validation if the received color is valid.
assert color in ('white', 'black')
# Creation of the attributes with the received values.
self.color = color
self.can_jump = can_jump
def is_white(self):
"""
Returns whether or not the piece is white.
Returns:
bool: True if the piece is white, and False else.
"""
return self.color == 'white'
def is_black(self):
"""
Returns whether or not the piece is black.
Returns:
bool: True if the piece is black, and False else.
"""
return self.color == 'black'
def can_move_to(self, source_position, target_position):
"""
Checks whether, according to the rules of chess, the piece can move from one position to another.
A position is a two-character string.
The first character is a letter between a and h, representing the column of the chessboard.
The second character is a number between 1 and 8, representing the row of the chessboard.
Args:
source_position (str): The source position, following the above format. For example, 'a8', 'f3', etc.
target_position (str): The target position, following the above format. For example, 'b6', 'h1', etc.
Warning:
Since we are in the basic class and not in one of the children's classes, we don't know
(yet) how this piece moves. This method is thus to be redefined in each of the
children's classes.
Warning:
As the Piece class is independent of the chessboard (and therefore we don't know if a piece is "in the
path"), we must ignore the content of the chessboard: we concentrate only on the rules of movement
of the pieces.
Returns:
bool: True if the move is valid following the rules of the piece, and False otherwise.
"""
# An exception is thrown (more on this later) indicating that this code has not been implemented. Do not touch
# to this method: reimplement it in children's classes!
raise NotImplementedError
def can_make_a_takeover_to(self, source_position, target_position):
"""
Checks whether, according to the rules of chess, the piece can "eat" (make a takeover) an enemy piece.
For most pieces the rule is the same, so the method can_move_to is called.
If this is not the case for a certain piece, we can simply redefine this method to program
the rule.
Args:
source_position (str): The source position, following the above format. For example, 'a8', 'f3', etc.
target_position (str): The target position, following the above format. For example, 'b6', 'h1', etc.
Returns:
bool: True if the takover is valid following the rules of the piece, and False otherwise.
"""
return self.can_move_to(source_position, target_position)
class Pawn(Piece):
def __init__(self, color):
super().__init__(color, False)
def can_move_to(self, source_position, target_position):
source_column, target_column = ord(source_position[0]), ord(target_position[0])
source_row, target_row = int(source_position[1]), int(target_position[1])
# A pawn moves on the same column.
if target_column != source_column:
return False
"""
If the pawn has never moved, it may move two squares. Otherwise, only one square.
Note that this is the only place where we refer to the size of the chessboard.
To make our classes of pieces truly independent of this size, we could
for example add an attribute n_deplacements, which will be incremented if the piece
moves.
"""
difference = source_row - target_row
if self.is_white():
if source_row == 2:
return difference in (-1, -2)
else:
return difference == -1
else:
if source_row == 7:
return difference in (1, 2)
else:
return difference == 1
def can_make_a_takeover_to(self, source_position, target_position):
source_column, target_position = ord(source_position[0]), ord(target_position[0])
source_row, target_row = int(source_position[1]), int(target_position[1])
# Le pion fait une prise en diagonale, d'une case seulement, et la direction dépend
# de sa couleur.
if target_position not in (source_column - 1, source_column + 1):
return False
if self.is_white():
return target_row == source_row + 1
else:
return target_row == source_row - 1
def __repr__(self):
"""
Redefines how a pawn is displayed on the screen. We use the constant USE_UNICODE
to determine how to display the pawn.
Returns:
str: The string representing the pawn.
"""
if self.is_white():
if USE_UNICODE:
return '\u2659'
else:
return 'PB'
else:
if USE_UNICODE:
return '\u265f'
else:
return 'PN'
class Rook(Piece):
def __init__(self, color):
super().__init__(color, False)
def can_move_to(self, source_position, target_position):
source_column, target_column = source_position[0], target_position[0]
source_row, target_row = source_position[1], target_position[1]
# A rook moves on the same row or line, regardless of direction
if target_column != source_column and source_row != target_row:
return False
# On the other hand, it cannot stay there.
if source_column == target_column and source_row == target_row:
return False
return True
def __repr__(self):
if self.is_white():
if USE_UNICODE:
return '\u2656'
else:
return 'TB'
else:
if USE_UNICODE:
return '\u265c'
else:
return 'TN'
class Knight(Piece):
def __init__(self, color):
super().__init__(color, True)
def can_move_to(self, source_position, target_position):
source_column, target_column = ord(source_position[0]), ord(target_position[0])
source_row, target_row = int(source_position[1]), int(target_position[1])
# Un cavalier se déplace en "L", alors l'une de ses coordonnées soit varier de 1, et l'autre de 2.
column_distance = abs(source_position - target_position)
row_distance = abs(source_row - target_row)
if column_distance == 1 and row_distance == 2:
return True
if column_distance == 2 and row_distance == 1:
return True
return False
def __repr__(self):
if self.is_white():
if USE_UNICODE:
return '\u2658'
else:
return 'CB'
else:
if USE_UNICODE:
return '\u265e'
else:
return 'CN'
class Bishop(Piece):
def __init__(self, color):
super().__init__(color, False)
def can_move_to(self, source_position, target_position):
# A bishop moves diagonally, i.e. the distance between rows and columns must be the same.
source_column, target_column = ord(source_position[0]), ord(target_position[0])
source_row, target_row = int(source_position[1]), int(target_position[1])
if abs(source_column - target_column) != abs(source_row - target_row):
return False
# On the other hand, he can't do a sur-place.
if source_column == target_column and source_row == target_row:
return False
return True
def __repr__(self):
if self.is_white():
if USE_UNICODE:
return '\u2657'
else:
return 'FB'
else:
if USE_UNICODE:
return '\u265d'
else:
return 'FN'
class King(Piece):
def __init__(self, color):
super().__init__(color, False)
def can_move_to(self, source_position, target_position):
#A king can move one square, on a line, row or column.
source_column, target_column = ord(source_position[0]), ord(target_position[0])
source_row, target_row = int(source_position[1]), int(target_position[1])
column_distance = abs(source_column - target_column)
row_distance = abs(source_row - target_row)
if row_distance != 1 and column_distance != 1:
return False
return True
def __repr__(self):
if self.is_white():
if USE_UNICODE:
return '\u2654'
else:
return 'RB'
else:
if USE_UNICODE:
return '\u265a'
else:
return 'RN'
class Queen(Piece):
def __init__(self, color):
super().__init__(color, False)
def can_move_to(self, source_position, target_position):
# A move for a queen is valid if she moves in a row, column or diagonal.
# Note that we use the methods directly from a class, passing as first
# argument the current object (self). It would have been "cleaner" to create new functions
# common to Tower, Bishop and Queen classes to avoid making these calls from the class.
return Rook.can_move_to(self, source_position, target_position) or \
Rook.can_move_to(self, source_position, target_position)
def __repr__(self):
if self.is_white():
if USE_UNICODE:
return '\u2655'
else:
return 'DB'
else:
if USE_UNICODE:
return '\u265b'
else:
return 'DN'
|
"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
"""
import itertools
def get_fibonacci_generator():
# Normally, fibonacci sequences start with 1, 1, 2, 3, 5, etc.
# This omits the first "1" but that's okay since 1 is odd.
first_previous_value = 0
second_previous_value = 1
for _ in itertools.count():
first_previous_value, second_previous_value = second_previous_value, first_previous_value + second_previous_value
yield second_previous_value
def get_even_fibonacci_sum(maximum):
generator = get_fibonacci_generator()
fibonacci_sum = 0
for _ in itertools.count():
fibonacci = next(generator)
if fibonacci > maximum:
break
if fibonacci % 2 == 1:
continue
fibonacci_sum += fibonacci
return fibonacci_sum
answer = get_even_fibonacci_sum(4 * 10 ** 6)
|
# Variables
"""
In python we no need to declare the variables explicitly , they are declared automatically when we assign
values to them
"""
i=10
j=10.23
k="This is string in double quotes"
l='This is string in single quotes'
m="""This is string in triple quotes"""
print('',i,'\n',j,'\n',k,'\n ',l,'\n',m) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.