text stringlengths 37 1.41M |
|---|
# 변수명 규칙
# - 문자, 숫자, (_) 가능. 단, 숫자로 시작할 수 없음
# - 대/소문자 구별.
# - 예약어 사용 불가능
#########################
## 수치형: int,Long,float, complex ##
#########################
a = 123456789
print(a)# 123456789
print(type(a)) #<class 'int'>
## 연산자(+,-,*,/,//,%)
a = 3 +4
print(a)
b = 7 - 10
print(b)
c = 7 * -3
print(c)
d = 30 // 7
print(d)
e = 22 / 7
print(e)
f = 22 // 7
print(f)
g = 22 % 7
print(g)
# 진수변환
# 16진수 -> 10진수
print(0x3039) #12345
# 10진수 -> 16진수
print(hex(12345)) #0x3039
print(type(hex(12345))) #<class 'str'>
# 10진수 -> 2진수
print(bin(0))
print(bin(8))
print(bin(16))
print(bin(255))
'''
0b0
0b1000
0b10000
0b11111111
'''
print(type(bin(255))) # <class 'str'> 자료형이 문자열
# 2진수 -> 10 진수
print(0b0) # 0
print(0b11111111) # 255
# 10 진수 -> 8진수 변환
print(oct(8)) # 0o10
print(oct(12)) # 0o14
print(oct(254)) # 0o376
# 변수 (실수)
h = 3.14
print(h)
print(type(h))
# 연산자
b = 3.3 + 4.2
print(b)
c = 10.0 + 30.8
print(c)
d = 10.1 * 30.4
print(d)
e = 22.5 /7.6
print(e)
print(type(e)) #<class 'float'>
f = 22.5 // 7.6 # 결과값 : 실수 , 몫 반환연산자
print(f) # 2.0
g = 22.5 % 7.6 # 결과값 : 실수, 나머지 반환연산자
print(g) # 7.300000000000001
# 복소수(complex Number)
a = 2 + 3j
print(a)
print(type(a)) #<class 'complex'>
print(a.real) # 2.0
print(a.imag) # 3.0
print(a.conjugate()) # 켤레복소수
# 복소수의 사칙연산
a = (1+2j)+(3+4j)
print(a) #(4+6j)
a = (1+2j)*(3+4j)
print(a) #(-5+10j)
a = (1+2j)/(3+4j)
print(a) #(0.44+0.08j)
# math 모듈을 이용한 계산
import math
print(math.pi) # 원주율
print(math.e) # 자연상수
print(abs(10)) # 절대값 계싼 함수(내장함수)
print(abs(-10))
print(round(1.2)) # 반올림
print(round(1.5))
print(math.trunc(1.4)) # 버림함수
print(math.pow(3,3)) # 3**3 과 동일
print(3**3) # 3^3 = 27
print(math.sqrt(81)) # 제곱근연산
print(math.log(4,2))
|
# 한 함수안에 여러개의 ruturn 배치 가능
def my_arg1(arg):
if arg < 0 :
return arg * -1
else:
return arg
# 주의 필요
def my_arg2(arg):
if arg < 0:
return arg * -1
else:
return
result = my_arg2(-1)
print(result)
result = my_arg2(0)
print(result) # return을 실행하지 못하고 함수가 종료되면
# 함수는 호출자에게 None을 반환
def ogamdo (num):
for i in range(1, num+1):
print('제 {0}의 아해'.format(i))
if i == 5 :
return #2. 데이터 없이 함수종료의 의미로 사용
ogamdo(3)
print()
ogamdo(5)
print()
ogamdo(8)
print()
def print_someting(*args):
for s in args:
print(s)
print_someting(1,2,3,4,5)
# 3. 반환 경과 없고, 함수 중간에
# 종료 시킬 일도 없을 때
# return문 생략 가능 |
def hello():
return "hello world"
def factorize(value):
powers = []
for i in range(2, value):
while value % i == 0:
powers.append(str(i))
value /= i
return '*'.join(powers)
def is_prime(value):
import math
for i in range(2, int(math.sqrt(value))):
if value % i == 0:
return "1"
return "0"
|
n = int(input('Enter any value: '))
i = 2
nn = 1
while i <= n:
i *= 2
nn += 1
print(nn - 1, i // 2)
|
a = int(input("Students in Class 1: ")) # Class 1
b = int(input("Students in Class 2: ")) # Class 2
c = int(input("Students in Class 3: ")) # Class 3
print("Need to buy desks:", a // 2 + b // 2 + c // 2 + a % 2 + b % 2 + c % 2)
|
class Stack():
def __init__(self):
self.items = []
def is_Empty(self):
'''判空'''
return self.items == []
def push(self,item):
'''入栈'''
self.items.append(item)
def pop(self):
'''出栈'''
return self.items.pop()
def peek(self):
'''返回栈顶元素'''
return self.items[len(self.items)-1]
def size(self):
'''返回大小'''
return len(self.items)
if __name__ == '__main__':
s = Stack()
s.push('hello')
s.push('world')
s.push('python')
print(s.size())
print(s.peek())
s.pop()
s.pop()
s.pop()
|
#Program that searches for a tweet matching
#the term given and prints out the username and their tweet
from twython import TwythonStreamer
from auth import (
consumer_key,
consumer_secret,
access_token,
access_token_secret)
#on_success code runs when a matching tweet is found
class myStreamer(TwythonStreamer):
def on_success(self, data):
if 'text' in data:
username = data['user']['screen_name']
tweet = data['text']
#prints out the username followed by the tweet text
#print("@{}: {}".format(username, tweet))
print(data['text']) #just gives the tweet text
#instance of myStreamer
stream = myStreamer(
consumer_key,
consumer_secret,
access_token,
access_token_secret)
#status filter to track a particular term
stream.statuses.filter(track = 'Nairobi')
|
alphabet = [ letter for letter in range(ord('a'), ord('z') + 1) ]
def transform(letter, key):
ord_letter = ord(letter)
first_letter = alphabet[0]
if (ord_letter in alphabet):
transleted = ( (ord_letter + self.key - first_letter) % len(alphabet) )+first_letter
return chr(transleted)
else:
return letter
def cipher(text, key):
return "".join([transform(letter,key) for letter in text ])
def decipher(text, key):
return "".join([transform(letter,-key) for letter in text ])
message = "hello world!"
key = 10
ciphered = ((cipher(message,key)))
deciphered = (decipher(ciphered, key))
deciphered = (decipher(ciphered, key))
print( 'Исходный текст: {}'.format(message))
print(('После шифрования: {}').format(ciphered))
print(('После дешифрования: {}').format(deciphered))
def D_message (message ,key):
print (('Используем ключ: {}').format(key))
print( 'Исходный текст: {}'.format(message))
print(('После шифрования: {}').format(ciphered))
print(('После дешифрования: {}').format(deciphered))
D_message('hello world!', 10)
print('-'*30)
D_message('very good!', 12)
|
print("W h a t s y o u r n a m e??", end=' ')
name = input()
print("H o w o l d a r e y o u ??", end=' ')
age = int(input())
print("W h a t s y o u r h e i g h t ??", end=' ')
height = int(input())
print("W h a t s y o u r w e i g h t ??", end=' ')
weight = int(input())
print(f"S o , y o u r n a m e i s {name} , y o u a r e {age} y e a r s o l d , y o u h a v e {height} c m a n d y o u w e i g h t e d {weight} k g")
|
from sys import argv
"""
script, first, second, third = argv
print("My first script is: " + script)
print("My first variable is: " + first)
print("My second variable is: " + second)
print("My third variable is: " + third)
"""
"""
script, first, second = argv
print("My first script is: " + script)
print("My first variable is: " + first)
print("My second variable is: " + second)
"""
"""
script, first, second, third = argv
print("My first script is: " + script)
print("My first variable is: " + first)
print("My second variable is: " + second)
print("My third variable is: " + third)
"""
script, first, second, third = input(argv)
print("My first script is: " + script)
print("My first variable is: " + first)
print("My second variable is: " + second)
print("My third variable is: " + third)
|
# поключаем из модуля sys компонент для получения значений из входящей строки
from sys import argv
# получаем первым значением название нашей программи, вторым - название файла для чтения
script, filename = argv
# открываем файл для чтения
txt = open(filename, "r")
# Выводим строку с названием файла
print(f"Inside the file: {filename}")
# получаем содержимое файла на вывод
print(txt.read())
txt.close()
# Следующие четыре строки абсолютно идентичны, так как мы выводим содержимое указанного второго файла
print("Enter the file name once more: ")
file_again = input("> ")
txt_again = open(file_again)
print(txt_again.read())
txt_again.close()
|
from tkinter import *
class Application:
def __init__(self, master=None):
self.widget1 = Frame(master)
self.widget1.pack()
self.msg = Label(self.widget1, text="Primeiro widget")
self.msg["font"] = ("Calibri", "9", "italic")
self.msg.pack ()
self.sair = Button(self.widget1)
self.sair["text"] = "Clique aqui"
self.sair["font"] = ("Calibri", "9")
self.sair["width"] = 10
self.sair["command"] = self.mudarTexto
self.sair.pack ()
def mudarTexto(self):
if self.msg["text"] == "Primeiro widget":
self.msg["text"] = "O botão recebeu um clique"
else:
self.msg["text"] = "Primeiro widget"
root = Tk()
Application(root)
root.mainloop() |
lista = []
totalValores = 20
for i in range(totalValores):
lista.append(int(input(f"Entre com o numero {i} :-> ")))
semRepetidos = set(lista)
print("=================================================")
print(lista)
print(semRepetidos)
print("=================================================")
print("EOP ") |
from functools import reduce
def somar (x, y ):
return x + y
lista = [1,3,5,7,9 , 11, 13 ]
soma = reduce (somar , lista)
print(soma) |
velMS = float(input("Entre com a Velocidade em M/S :-> "))
velKMH = velMS * 3.6
print(f"E a velocidade em M/S é :-> {velKMH:.2f}")
|
import math
valorA = int(input("entre com Valor A :-> "))
valorB = int(input("entre com Valor B :-> "))
valorC = int(input("entre com Valor C :-> "))
delta = (valorB ** 2) - (4 * valorA * valorB)
if delta < 0:
print("Não existe raiz para os valores selecionados ")
else:
if delta == 0:
print("Existe apenas uma unica raiz ")
raiz1 = (-1 * valorB) / (2 * valorA)
print(raiz1)
else:
print("existem duas raizes ")
raiz1 = ((-1 * valorB) + math.sqrt(delta)) / (2 * valorA)
raiz2 = ((-1 * valorB) - math.sqrt(delta)) / (2 * valorA)
print(raiz1)
print(raiz2)
|
lista = []
totalNotas = 10
qtdNeg = 0
somaPositivo = 0
for i in range(totalNotas):
lista.append(int(input(f"Entre com o numero {i} :-> ")))
for num in lista:
if num > 0:
somaPositivo += num
elif num <= 0 :
qtdNeg += 1
print("=================================================")
print(lista)
print(f"SOma dos positivos :-> {somaPositivo}")
print(f"Quantidade Neghativos :-> {qtdNeg}")
print("=================================================")
print("EOP ") |
"""
Média Aritmética Ponderada
A média aritmética ponderada é calculada multiplicando cada valor do conjunto de dados pelo seu peso.
Depois, encontra-se a soma desses valores que será dividida pela soma dos pesos.
"""
def calculaMedia (nota1, nota2, nota3, metodo):
media = 0
if metodo.upper() == 'A':
media = (nota1+nota2+nota3)/3
elif metodo.upper() == 'P':
media = ((nota1*5) + (nota2*3) + (nota3*2))/(5+3+2)
return media
valor1 = int(input("Entre com o 1º nota :-> "))
valor2 = int(input("Entre com o 2º nota :-> "))
valor3 = int(input("Entre com o 3º nota :-> "))
tipo = input("Entre com o tipo de calculo A/P :-> ")
result = calculaMedia(valor1, valor2,valor3, tipo)
print(f'E a media calculada é :-> {result}') |
numero = quadrado = cubo = raiz = 0
while True:
numero = int(input("Entre com o 1 numero :-> "))
if numero <= 0:
break
quadrado = numero ** 2
cubo = numero ** 3
raiz = numero ** (1 / 2)
print(f"Quadrado :-> {quadrado}")
print(f"Cubo :-> {cubo}")
print(f"raix :-> {raiz}")
print("=================================================")
print("Final de O programas")
|
"""
criando a sua propria versão de Lupe
====================================================================================================================
for num in [1,2,3,4,5,6]:
print(num)
for letra in 'Geek University':
print(letra)
====================================================================================================================
"""
def meu_for (iteravel):
it = iter(iteravel)
while True:
try:
print(next(it))
except StopIteration:
break
numeros = [0,0,1,2,3,4,5,6,7,8,9]
meu_for('Apalpa a minha naba adiposa caso possa')
meu_for(numeros) |
def e_primo(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
final = inicio = soma = 0
while inicio <= 0: inicio = int(input("Entre com o 1 numero :-> "))
while final <= inicio: final = int(input("Entre com o 2 numero :-> "))
counter = 0
while inicio <= final:
if e_primo(inicio):
counter += 1
soma += inicio
print(f'Primo? {inicio}')
inicio += 1
print(f'A quantidade de primos é de {counter} ')
print(f'A soma dos {counter} primos no intervalo é {soma}') |
peso = float(input("Entre com o PESO da pessoa :-> "))
altura = float(input("Entre com a altura da pessoa :-> "))
imc = peso / (altura**2)
mensagem = ""
if imc <= 18.5:
mensagem = "Abaixo de O Peso "
elif 18.6 <= imc <= 24.9 :
mensagem = "Saudável"
elif 25 <= imc <= 29.9:
mensagem = "Peso em Excesso"
elif 30 <= imc <= 34.9:
mensagem = "Obesidade Grau I"
elif 35 <= imc <= 39.9:
mensagem = "Obesidade Grau II (Severa) "
elif imc >= 40:
mensagem = "Obesidade Grau III (Mórbida) "
print(f"E o calculo de IMC para os dados informados é de {imc:.1f} e o sujeito é classificado com '{mensagem}'") |
contador = 1
valor1 = int(input("Entre com o 1 numero :-> "))
while contador <= valor1:
if valor1%contador == 0:
print(f" E o numero {valor1} é divisivel por {contador}")
contador += 1 |
"""
Módulo Collections - Named Tuple
* São tuplas diferenciadas onde eespecificamos um nome para a mesma e também parametros
====================================================================================================================
review
tupla = (1,2,3)
print(tupla)
print(tupla[0])
====================================================================================================================
https://docs.python.org/3/library/collections.html#collections.namedtuple
====================================================================================================================
"""
from collections import namedtuple
# Apos o import tem que definir o nome e para-metros
# Forma 1 declaração de NT
cachorro = namedtuple('cachorro', 'idade raca nome')
#forma2
cachorro = namedtuple('cachorro', 'idade, raca, nome')
#forma3
cachorro = namedtuple('cachorro', ['idade', 'raca', 'nome'])
ray = cachorro(idade=2, raca='Chow-Chow', nome='Ray')
print(ray)
print("**********************")
#acessando os dados forma 1
print(ray[0])
print(ray[1])
print(ray[2])
print("**********************")
#acessando os dados forma 1
print(ray.idade)
print(ray.raca)
print(ray.nome)
print("**********************")
print(ray.index('Chow-Chow'))
print(ray.count('Chow-Chow')) |
import random
matrizUm = []
matrizDois = []
matrizTres = []
linhaAtualUm = []
linhaAtualDois = []
linhaAtualTres = []
linhas = 4
colunas = 4
print("=================================================")
print(f'Preenche todos os valores para a matriz A e Matriz B [{linhas},{colunas}]')
for i in range(linhas):
for j in range(colunas):
# valor = int(input(f'Entre com elemento [{i}][{j}] :=-> '))
valorUm = random.randint(0,1000)
print(f'Entre com elemento [{i}][{j}] para a Matriz "A" :=-> {valorUm}')
linhaAtualUm.append(valorUm)
valorDois = random.randint(0,1000)
print(f'Entre com elemento [{i}][{j}] para a Matriz "B" :=-> {valorDois}')
linhaAtualDois.append(valorDois)
if valorUm > valorDois:
maior = valorUm
else:
maior = valorDois
linhaAtualTres.append(maior)
matrizUm.append(linhaAtualUm)
matrizDois.append(linhaAtualDois)
matrizTres.append(linhaAtualTres)
linhaAtualUm = []
linhaAtualDois = []
linhaAtualTres = []
print("=================================================")
print('Matrix "A"' )
for linha in matrizUm :
print(linha)
print("=================================================")
print('Matrix "B" ')
for linha in matrizDois :
print(linha)
print("=================================================")
print('Matrix "C" ')
for linha in matrizTres :
print(linha)
|
lista = []
totalValores = 8
valorX = 0
valorY = 0
for i in range(totalValores):
lista.append(int(input(f"Entre com o numero {i} :-> ")))
print("=================================================")
print(lista)
print("=================================================")
valorX = int(input(f"Entre com a Posicao X :-> "))
valorY = int(input(f"Entre com a Posicao Y :-> "))
print("=================================================")
print(f"O Valor encontrado na posicao X é {lista[valorX]} ")
print(f"e o valor na posicao Y é {lista[valorY]}")
print(f"E a soma dos valores é {lista[valorX] + lista[valorY] } ")
print("=================================================") |
"""
Crie uma classe Agenda que pode armazenar 10 pessoas e seja capaz de realizar as seguintes operações:
* void armazenaPessoa(String nome, int idade, float altura); (OK)
* void removePessoa(String nome); (OK)
* int buscaPessoa(String nome); // informa em que posição da agenda está a pessoa (OK)
* void imprimeAgenda(); // imprime os dados de todas as pessoas da agenda (OK)
* void imprimePessoa(int index); // imprime os dados da pessoa que está na posição "i" da agenda. (OK)
"""
class Agenda:
cont = 0
banco = []
def __init__(self, nome, idade, altura):
self.__banco = Agenda.banco
self.__cont = Agenda.cont + 1
self.__nome = nome
self.__idade = idade
self.__altura = altura
Agenda.cont = self.__cont
self.__posicao = 0
def armazena_pessoa(self):
user = 'pessoa ' + str(self.__cont)
pessoa = {user: (self.__nome, self.__idade, self.__altura)}
self.__banco.append(pessoa)
return self.__banco
def remover_pessoa(self, nome):
""" Separa os dicionários da lista(banco) e acessa os valores, onde estão contido as tuplas. Então,
por via índice, o nome da pessoa é localizado"""
self.__banco = Agenda.banco
indice = 0
for dicionario in self.__banco:
if list(dicionario.values())[0][0] == nome:
break
else:
indice += 1
self.__banco.pop(indice) # Removendo a pessoa
self.__banco = Agenda.banco
print(f'{nome} foi removido')
def buscar_pessoa(self, nome):
self.__banco = Agenda.banco
indice = 0
compara = 0
for dicionario in self.__banco:
if list(dicionario.values())[0][0] == nome:
compara += 1
print(f'A Pessoa Está localizada no índice {indice}')
break
else:
indice += 1
if compara != 1:
print('Pessoa não encontrada.')
def imprime_agenda(self):
self.__banco = Agenda.banco
for dicionario in self.__banco:
print(f'nome: {list(dicionario.values())[0][0]}')
print(f'idade: {list(dicionario.values())[0][1]}')
print(f'altura: {list(dicionario.values())[0][2]}\n')
def posicao_pessoa(self, indice):
self.__banco = Agenda.banco
self.__posicao = self.__banco[indice]
nome = list(self.__posicao.values())[0][0]
idade = list(self.__posicao.values())[0][1]
altura = list(self.__posicao.values())[0][2]
print(f'Nome: {nome}\nIdade: {idade}\nAltura: {altura}')
pessoa_1 = Agenda('Luis Gustavo', 21, 1.74)
pessoa_2 = Agenda('Jhenifer Noha', 23, 1.72)
pessoa_3 = Agenda('Larissa Vicente', 42, 1.82)
pessoa_4 = Agenda('Alan Taring', 48, 1.78)
pessoa_5 = Agenda('Cláudia Mendes', 19, 1.59)
pessoa_6 = Agenda('Alice Matos', 28, 1.75)
pessoa_7 = Agenda('Sérgio Vicente', 57, 1.73)
pessoa_8 = Agenda('Alan Silva', 21, 1.92)
pessoa_9 = Agenda('Eulayla Monteiro', 19, 1.70)
pessoa_10 = Agenda('João Pedro', 21, 1.73)
Agenda.armazena_pessoa(pessoa_1)
Agenda.armazena_pessoa(pessoa_2)
Agenda.armazena_pessoa(pessoa_3)
Agenda.armazena_pessoa(pessoa_4)
Agenda.armazena_pessoa(pessoa_5)
Agenda.armazena_pessoa(pessoa_6)
Agenda.armazena_pessoa(pessoa_7)
Agenda.armazena_pessoa(pessoa_8)
Agenda.armazena_pessoa(pessoa_9)
Agenda.armazena_pessoa(pessoa_10)
print(Agenda.banco, '\n')
# Remover Pessoa:
nome_remover = input('Digite o nome da pessoa a ser removida: ')
try:
Agenda.remover_pessoa(pessoa_10, nome_remover)
print(Agenda.banco)
except IndexError:
print('A pessoa não encontra-se no banco de dados.')
# Buscar a posição da agenda da pessoas:
nome_busca = input('Digite o nome da pessoa a ser encontrada: ')
Agenda.buscar_pessoa(pessoa_10, nome_busca)
# Mostrar os dados das Pessoas:
Agenda.imprime_agenda(pessoa_10)
# Imprime os dados da pessoa que está na posição "i" da agenda
Agenda.posicao_pessoa(pessoa_10, 5) |
totalNumeros = 10
vetorInicial = []
print("**********************")
for i in range(totalNumeros):
vetorInicial.append(int(input(f"Entre com o numero {i} inteiro para o Vetor :-> ")))
print("=================================================")
print("Vetor Inicial ")
print("=================================================")
vetorInicial.sort()
for j in vetorInicial:
print(j)
|
tempCelcius = float(input("Entre com a Temperatura em ºc :-> "))
tempKelvim = tempCelcius + 273.15
print(f"E a temperatura éem Kelvim é :-> {tempKelvim:.2f}") |
baseMaior = float(input("entre com a base Maior:-> "))
baseMenor = float(input("entre com a Base Menor :-> "))
altura = float(input("entre com a Altura :-> "))
if baseMenor > 0 and baseMaior > 0 and altura > 0:
area = ((baseMenor + baseMaior)* altura)/2
print("E o valor da área do Trapezio :-> " + str(area)) |
velKMH = float(input("Entre com a Velocidade em KM/H :-> "))
velMilhas = velKMH / 1.6
print(f"E a velocidade em Milhas/hora :-> {velMilhas:.2f}")
|
# -*- coding: cp1252 -*-
nomeArquivo = input(f'Entre com o nome de O Arquivo :-> ')
try:
with open(nomeArquivo, 'r') as arquivo:
linhas = arquivo.read()
novo = linhas.replace('a', '*').replace('A', '*').replace('a', '*').replace('E', '*').replace('e', '*').replace(
'I', '*').replace('i', '*').replace('O', '*').replace('o', '*').replace('U', '*').replace('u', '*')
try:
saidaArquivo = nomeArquivo + '.novo.txt'
with open(saidaArquivo, 'w') as saida:
saida.writelines(novo)
except FileNotFoundError:
print('Arquivo no achado')
except FileNotFoundError:
print('Arquivo no achado')
|
resist1 = resist2 = resistencia = 0
while True:
resist1 = int(input("Entre com o valor do Resistor 1 :-> "))
resist2 = int(input("Entre com o valor do Resistor 2 :-> "))
if resist1==0 or resist2 ==0:
break
resistencia =(resist1*resist2) / (resist1 + resist2)
print(f"E o valor da resistencia é de :-> {resistencia:.2f}")
print("=================================================")
print("Final de O programa s")
|
vetorUm = []
vetorDois = []
vetorIntersec = []
totalNumeros = 6
for n in range(totalNumeros):
print("**********************")
numero = 0
while numero <= 0: numero = int(
input(f"Entre com o numero {n + 1} inteiro e maior que Zero para o Vetor 01 :-> "))
vetorUm.append(numero)
numero = 0
while numero <= 0: numero = int(
input(f"Entre com o numero {n + 1} inteiro e maior que Zero para o Vetor 02 :-> "))
vetorDois.append(numero)
# Aqui, pra usar a funcionalidade SET, tem que converter a lista em COnjunto
conjUm = set(vetorUm)
conjDois = set(vetorDois)
conjIntersect = conjUm.intersection(conjDois)
print("=================================================")
print("E os numeros que se repetem nos dois vetores são ")
print(conjIntersect) |
totalNumeros = 15
matrizFinal = []
linhaAtual = []
linhas = 4
colunas = 4
contaMaio10 = 0
print("**********************")
for i in range(linhas):
for j in range(colunas):
valor = int(input(f'Entre com elemento [{i}][{j}] :=-> '))
linhaAtual.append(valor)
if valor > 10 :
contaMaio10 += 1
matrizFinal.append(linhaAtual)
linhaAtual = []
# linhaAtual.clear() o clear nesse caso provoca erro, acho que ele "mata" a linha
print("**********************")
print(matrizFinal)
print (matrizFinal[2][2])
print("=================================================")
# pegadinha do malanro pra imprimir a matriz
for row in matrizFinal:
print(' '.join([str(elem) for elem in row]))
print("=================================================")
print("**********************")
print(f'Tota de numeros > 10 :-> {contaMaio10}') |
import random
matrizFinal = []
linhaAtual = []
linhas = 4
colunas = 4
maior = 0
posXmaior = 0
posYmaior = 0
print("**********************")
for i in range(linhas):
for j in range(colunas):
# valor = int(input(f'Entre com elemento [{i}][{j}] :=-> '))
valor = random.randint(0,1000)
print(f'Entre com elemento [{i}][{j}] :=-> {valor}')
linhaAtual.append(valor)
matrizFinal.append(linhaAtual)
linhaAtual = []
print("=================================================")
for linha in matrizFinal:
print(linha)
maior = int(input(f'Entre com um numero pra eu localizar nessa bagaça ai :-> '))
encontrou = False
for k in matrizFinal:
if maior in k:
posYmaior = k.index(maior)
encontrou = True
break
posXmaior += 1
if encontrou:
print(f'E a posicao [X,Y] do Maior é [{posXmaior},{posYmaior}]')
else:
print('Nao encontrei ')
print("=================================================")
|
"""
44 - Leia um número positivo do usuário, então, calcule e imprima a sequência Fibonacci até o primeiro número superior
ao número lido.
Exemplo: se o usuário informou o número 30, a sequência a ser impressa será: 0 1 1 2 3 5 8 13 21 34
"""
soma = 0
num_atual = 0
num_anterior = 1
sequencia = [0, 1]
numero = int(input('Digite um número para cálculo da sequência de Fibonacci: '))
while numero < 0:
print('Você deve digitar um número positivo!')
numero = int(input('Digite um número para cálculo da sequência de Fibonacci: '))
while True:
soma = num_atual + num_anterior
num_anterior = max(sequencia)
sequencia.append(soma)
if max(sequencia) > numero:
break
else:
num_atual = soma
print(sequencia)
print("=================================================")
print("Final de O programas")
|
base = int(input("Entre com a Base :-> "))
loga = int(input("Entre com o LOgaritmando :-> "))
if base > 1 and loga > 0:
novo=loga
log1=0
while novo != 1:
novo = novo / base
log1 = log1 + 1
print (f"o LOG de {loga} na base {base} é :-> {log1} ")
else:
print("A base tem quie ser maior que 1 e o Lgaritimando maior que 0 ") |
"""
funções com parametro de entrada
* Funções que recebem dados para ser processados dentro da mesma
* Funções podem ter N parametros de entarda. podemos receber tantos parametros quanto necessários, separados por " , "
Se a gente pensar em qualquer programa, geralmente temos
entrada -> processamento -> saida
Nos casos de funções :
- Funções sem entrada
- Funções sem saidas
- Possuem entrada mas não possuem saida
- Possuem saida mas não tem entrada
- Possuem entrada e saida
====================================================================================================================
# Refatorando uma função:
def quadrado_de_seth():
return 7 * 7
def quadrado(numero):
# return numero * numero
return numero ** 2
print(quadrado(7))
print(quadrado(2))
print(quadrado(5))
====================================================================================================================
# exemplo 2
def cantar_parabens(aniversariante ):
print('parabéns proce')
print('É rola é rola é rola')
print(f'morre diabo {aniversariante}')
cantar_parabens('MarKYS')
====================================================================================================================
def soma(a, b):
return a + b
def multimplica(num1, num2):
return num1 * num2
def outa(num1, b, msg):
return (num1 + b) * msg
# Obs se for informado um numero errado de parametro ou argumentos, teremos TypeError
====================================================================================================================
# NOmeando Parametros
def nome_completo (nome, sobrenome):
return f'Seu nome completo é {nome} {sobrenome}'
print(nome_completo('Negao', 'do Zap'))
# A diferenca entre parametros e Argumentos
# parametros sao variaveis na definicao de uma função
# Argumentos são dados passados durante a execução de uma função
# A ordem dos parametros importa
#Argumentos Nomeados -> KeyWordArguments
#Caso utilizamos nomes dos parametros nos argumentos para informalos, podemos utilizar qualquer ordem:
print(nome_completo(nome='Scalet', sobrenome='Johansenn'))
print(nome_completo(sobrenome='Grey', nome='Sasha'))
====================================================================================================================
"""
# Erro comum na utilização do return
def soma_impares(numeros):
total = 0
for num in numeros:
if num % 2 != 0:
total += num
return total
lista = [1, 2, 3, 4, 5, 6, 7, 8]
print(soma_impares(lista))
|
custoFabrica = float(input("Entre com o custo de Fabrica do Veiculo :-> "))
distribuidor = 0
impostos = 0
if custoFabrica <= 12000:
distribuidor = 5
impostos = 0
elif 12001 <= custoFabrica <= 25000:
distribuidor = 10
impostos = 15
elif custoFabrica > 25000:
distribuidor = 15
impostos = 20
valorFinal = custoFabrica + ((custoFabrica*distribuidor)/100) +((custoFabrica*impostos)/100)
print(f"E o valor final é :-> {valorFinal:.2f}")
|
class Elevador:
pessoas = 0
andar_atual = 0
def __init__(self, andares, capacidade):
self.__andares = andares
self.__capacidade = capacidade
def entra(self):
if Elevador.pessoas < self.__capacidade:
Elevador.pessoas += 1
return f'Entrou uma pessoa no elevador.\nHá agora {Elevador.pessoas} pessoas no elevador'
else:
return 'ELEVADOR LOTADO!!'
@classmethod
def sai(cls):
if cls.pessoas > 0:
cls.pessoas -= 1
return f'Saiu uma pessoa no elevador.\nHá agora {cls.pessoas} pessoas no elevador'
else:
return 'ELEVADOR VAZIO!!'
def sobe(self):
if Elevador.andar_atual < self.__andares:
Elevador.andar_atual += 1
return f'O elevador subiu um andar.\nAgora o elevador está no andar nº {Elevador.andar_atual}'
else:
return 'ESTAMOS NO ÚLTIMO ANDAR'
@classmethod
def desce(cls):
if cls.andar_atual > 0:
cls.andar_atual -= 1
return f'O elevador desceu um andar.\nAgora o elevador está no andar nº {cls.andar_atual}'
else:
return 'ESTAMOS NO TÉRREO'
elevador = Elevador(20, 6) |
vetor1 = []
vetor2 = []
vetor3 = []
for n in range(1, 11):
n1 = int(input(f'Informe o valor {n} do primeiro vetor: '))
vetor1.append(n1)
# posição par do vetor 3
vetor3.append(n1)
n2 = int(input(f'Informe o valor {n} do primeiro vetor: '))
vetor2.append(n2)
# Posição ímpar do vetor 3
vetor3.append(n2)
print(vetor3) |
lista = []
listaPar = []
totalValores = 10
totalPares = 0
for i in range(totalValores):
lista.append(int(input(f"Entre com o numero {i} :-> ")))
if lista[i] %2 == 0 :
listaPar.append(lista[i])
totalPares += 1
print("=================================================")
print(f"A quantidade de numeros pares é {totalPares}")
print(listaPar) |
"""
Progamação Orientada à Objetas - POO
- Classes: nada mais são do que modelos dos objetos do mundo real sendo representados computacoinalmentes
Imagine que vc queira criar um sistyema automatizado para controle de lampadas de um ambiente
classes podem contar:
- Atributos -> representam as caracteristicas do Objeto.OU seja, pelos atributos conseguimos representar
computacionalmente os estados de um objeto. No caso da lampada, possivelmente iriamos querer saber se a
lampada é 110 ou 220, a sua cor, qual a luminosidade, , etc ..
- Métodos -> representam os comportamentos dos objetos, ou seja as ações que esse Objeto pode realizar
no seu Sistema. no caso da Lampada por exempo, um cmportamento comum que muito provavelmte iriamos querer
representar no nosso sistema é o de LIgar/Desligar a mnesma
Em python para definir uma classe utilizamos a palavra reservada " class "
OBS.: Utilizamos a palavra " pass " em python quando temos um bloco de código que ainda não está implementado.
OBS.: QUando nomeamos nossas classes em Python utilizamos por convençao o nome com inicial em Maiusculo. Se o nome for
composto, utiliza as Iniciais de ambas as palavras em Maiusculo, todas Juntas
Dica Geek: em Computação não utilzamos Acentuação , caracteres especiais, espaços ou similares para nomes de classes,
atributos, metodos, arquivos, diretórios, etc ...
OBS: quando estamos planejando um Software e definimos quais classes teremos que ter no sistema, chamamos estes objetos
que serão mapeeados para classes de " entidades "
====================================================================================================================
====================================================================================================================
====================================================================================================================
====================================================================================================================
====================================================================================================================
"""
print('-=-|-=-|-=-|-=-|-=-|-=-|-=-|-=-|-=-|-=-|-=-|-=-|-=-|-=-|-=-')
class Lampada:
pass
class ContaCorrente:
pass
class Produto:
pass
class Usuario:
pass
lamp = Lampada()
print(type(lamp))
|
numBase = 0
counter = 0
atual = 0
proximo = 1
temp = 0
while numBase <= 0: numBase = int(input("Entre com o 1 numero :-> "))
while True :
print(atual)
temp = atual + proximo
atual = proximo
proximo = temp
counter += 1
if atual > numBase:
break
print("=================================================")
print("Final de O programas") |
def validarHora(hora):
horaSeparada = hora.split(":")
if 0 <= int(horaSeparada[0]) < 24 and 0 <= int(horaSeparada[0]) < 60:
return True
else:
return False
Entrada = input("Entre com a hora de entrada no formado HH24:MM :-> ")
Saida = input("Entre com a hora de saida no formado HH24:MM :-> ")
tempoAbsoluto = 0
totalFull = 0
valorAPagar = 0
if validarHora(Entrada) and validarHora(Saida):
tempoEntrada = int(Entrada.split(':')[0]) * 60 + int(Entrada.split(':')[1])
tempoSaida = int(Saida.split(':')[0]) * 60 + int(Saida.split(':')[1])
print(f"{tempoEntrada} - {tempoSaida}")
if Saida <= Entrada:
tempoAbsoluto = (1440 - tempoEntrada) + tempoSaida
else:
tempoAbsoluto = tempoSaida - tempoEntrada
totalHoras = int(tempoAbsoluto / 60)
totalMinutos = int(tempoAbsoluto % 60)
totalFull = totalHoras
if totalMinutos >= 1: totalFull = totalHoras + 1
print(f"Tempo total em minutos :-> {tempoAbsoluto}")
if totalFull == 1:
valorAPagar == 1.00
elif totalFull == 2:
valorAPagar = 2.00
elif totalFull == 3:
valorAPagar = 2 + 1.4
elif totalFull == 4:
valorAPagar = 2 + 2.8
elif totalFull >= 5:
valorAPagar = totalFull * 2
print(f"Total de horas : {totalFull} ; Valor a se pagar : {valorAPagar:.2f}")
else:
print("Alguma das horas estão erradas. Verificar !")
|
tempFhr = float(input("Entre com a Temperatura em ºf :-> "))
tempCelcius = 5 * ( ( tempFhr -32 )/9 )
print(f"E a temperatura éem Celcius é :-> {tempCelcius:.2f}") |
def triangulo_vertical(altura=6):
cont_espaco = 0
base = 2 * altura + 1
# Como sabemos que o triângulo sempre aumentará em 2, o número de
# asteriscos da linha seguinte, defini o incremento do for
# no valor 2
for i in range(1, base, 2):
# Fórmula para determinar a quantidade de espaços
# inseridos em cada linha, que será o valor altura
# menos o valor atual de cont_espaco
espacamento = altura - cont_espaco
# Imprimindo os espaços, mas sem avançar a linha
print(' ' * espacamento, end='')
# Imprimindo os asteriscos da linha atual
print('*' * i)
# Incrementando o cont_espaço para a próxima linha
# ter menos espaços
cont_espaco += 1
print(triangulo_vertical())
|
class Solution:
def __init__(self):
self.count = 0
'''
这个问题转换成一个一位数组,查看 p + q == x + y or p - q == x - y
In this problem, whenever a location (x, y) is occupied, any other locations
(p, q ) where p + q == x + y or p - q == x - y would be invalid. We can use
this information to keep track of the indicators (xy_dif and xy_sum ) of the
invalid positions and then call DFS recursively with valid positions only.
'''
def solveNQueens(self, n):
def DFS(queens, xy_dif, xy_sum):
p = len(queens)
if p == n:
self.count += 1
return None
for q in range(n):
if q not in queens and p - q not in xy_dif and p + q not in xy_sum:
DFS(queens + [q], xy_dif + [p - q], xy_sum + [p + q])
result = []
DFS([], [], [])
return self.count
sol = Solution()
sol.solveNQueens(5)
|
class QuickSelect:
def __init__(self, A):
self.A = A
def quickSelect(self, start, end, k):
'''
QuickSelect的核心是partition方法
每次partition之后,要判断pivot的位置
'''
i, j = start, end
while True:
pivot = self.partition(i, j)
if pivot == k - 1:
return self.A[pivot]
elif pivot > k - 1:
j = pivot - 1
else:
i = pivot + 1
return -1
def swap(self, i, j):
temp = self.A[i]
self.A[i] = self.A[j]
self.A[j] = temp
def partition(self, start, end):
i, j, pivot = start, start, end
while j < pivot:
if self.A[j] >= self.A[pivot]:
j += 1
else:
self.swap(i, j)
i += 1
j += 1
return i
l = [7,2,4,5,9,1,3,6,10,8]
qs = QuickSelect(l)
print qs.quickSelect(0, len(l) - 1, 4)
|
class Node:
def __init__(self, number):
self.edges = []
self.number = number
class Edge:
def __init__(self, node, cost):
self.node = node
self.cost = cost
class Test:
def getShortestCostNode(self, root):
'''
stack: 用来保存节点的边
visited: 用来保存该节点是否visited
retMap: 包含从root到所有的叶节点的cost map
costs:记录从root到所有非叶节点的cost值
'''
import sys
if not root or not root.edges:
return
stack, visited, retMap, costs = [], {}, {}, {}
count, minValue, ret = 0, -sys.maxint, None
for edge in root.edges:
stack.append(edge)
costs[edge.node] = edge.cost
while stack:
edge = stack.pop()
node = edge.node
if node in visited:
continue
count = costs[node]
visited[node] = True
if node.edges:
for edge1 in node.edges:
if edge1.node not in visited:
stack.append(edge1)
costs[edge1.node] = count + edge1.cost
else:
retMap[node] = count
return sorted(retMap.values())[0]
root = Node(0)
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node6 = Node(6)
edge1 = Edge(node1, 2)
edge2 = Edge(node2, 3)
edge3 = Edge(node3, 1)
edge4 = Edge(node4, 4)
edge5 = Edge(node5, 6)
edge6 = Edge(node6, 2)
root.edges = [edge1, edge2]
node1.edges = [edge3, edge5]
node2.edges = [edge4]
node4.edges = [edge6]
test = Test()
test.getShortestCostNode(root)
import Queue as Q
q = Q.PriorityQueue()
q.put((-10,'ten'))
q.put((-1,'one'))
q.put((-5,'five'))
print q.qsize()
while not q.empty():
print q.get(),
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
这里注意[1,1,2,2]这种情况
"""
if not head or not head.next:
return head
allHead = ListNode(-1)
allHead.next = head
pre, cur = allHead, head
while cur:
while cur.next and cur.val == cur.next.val:
cur = cur.next
if pre.next == cur: # 没有重复的
pre = pre.next
else: # 有重复的,直接跳过
pre.next = cur.next
cur = cur.next # 最后把当前的设置为next
return allHead.next
head = ListNode(1)
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(2)
head.next = node1
node1.next = node2
node2.next = node3
sol = Solution()
sol.deleteDuplicates(head)
|
class MovingAverage:
def __init__(self, size):
import Queue
self.size = size
self.q = Queue.Queue()
self.sum = 0
def next(self, val):
if self.q.qsize() < self.size:
self.q.put(val)
self.sum += val
return (self.sum * 1.0) / self.q.qsize()
else:
self.sum -= self.q.get()
self.q.put(val)
self.sum += val
return (self.sum * 1.0) / self.q.qsize()
sol = MovingAverage(3)
print sol.next(1)
print sol.next(3)
print sol.next(2)
print sol.next(3)
print sol.next(4)
|
class Solution:
def threeSumSmaller(self, nums, target):
'''
解题思路和3SUM一样,也是先对整个数组排序,然后一个外层循环确定第一个数,然后里面使用头尾指针left和right进行夹逼,
得到三个数的和。如果这个和大于或者等于目标数,说明我们选的三个数有点大了,就把尾指针right向前一位(因为是排序的数组,
所以向前肯定会变小)。如果这个和小于目标数,那就有right - left个有效的结果。为什么呢?因为假设我们此时固定好外层的那个数,
还有头指针left指向的数不变,那把尾指针向左移0位一直到左移到left之前一位,这些组合都是小于目标数的。
'''
if not nums:
return 0
nums.sort()
i, j = 1, len(nums) - 1
res = 0
while i < j:
while i < j:
val = nums[i - 1] + nums[i] + nums[j]
if val >= target:
j -= 1
else:
res += j - i
break
i += 1
return res
sol = Solution()
print sol.threeSumSmaller([-2, 0, 1, 3], 2)
|
// Recursion Solution
class Solution:
def isMatch(self, s, p):
if not p:
return not s
if p[-1] == '*':
if s and (s[-1] == p[-2] or p[-2] == '.'):
return self.isMatch(s, p[:-2]) or self.isMatch(s[:-1], p)
else:
return self.isMatch(s, p[:-2])
else:
if s and (s[-1] == p[-1] or p[-1] == '.'):
return self.isMatch(s[:-1], p[:-1])
else:
return False
|
#!/usr/bin/env python3
"""
Parses the HTML Response from the Twitter Search page
"""
from sys import stderr
from pyquery import PyQuery
class TweetParser:
"""
Parses the HTML Response from the Twitter Search page
"""
@staticmethod
def create_dict(tweet):
"""
Formats a PyQuery parsed tweet into a Twitter API like dict
"""
return {
'created_at': int(tweet("small.time span.js-short-timestamp").attr("data-time")),
'id': tweet.attr("data-tweet-id"),
'lang': tweet("div.js-tweet-text-container p").attr("lang"),
'text': tweet("p.js-tweet-text").text(),
'user': {
'id': tweet("div.stream-item-header a").attr("data-user-id"),
'screen_name': tweet("span:first.username.u-dir b").text()
},
}
@staticmethod
def parse(html=None):
"""
Parses the HTML response from Twitter into a list of tweets
:param html: String of HTML data
"""
final_tweets = []
try:
tweets_parsed = PyQuery(html['items_html'])('div.js-stream-tweet')
has_tweets = len(tweets_parsed) > 0
if not has_tweets:
return final_tweets
except Exception as exception:
print('Failed to parse HTML', file=stderr)
print(exception)
return final_tweets
for tweet in tweets_parsed:
tweet_pyquery = PyQuery(tweet)
tweet_dict = TweetParser.create_dict(tweet_pyquery)
final_tweets.append(tweet_dict)
return final_tweets
|
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 17 19:03:06 2018
@author: GEAR
"""
# python stack 实现
class Stack():
#初始化栈为空列表
def __init__(self):
self.__items = []
#判断栈是否为空,返回布尔值
def is_empty(self):
return self.__items == []
#返回栈顶元素
def peek(self):
return self.__items[-1]
#返回栈的大小
def size(self):
return len(self.__items)
#新元素入栈
def push(self, item):
self.__items.append(item)
#栈顶元素出栈
def pop(self):
return self.__items.pop()
if __name__ == '__main__':
#创建一个空栈对象
myStack = Stack()
myStack.push(1)
myStack.push(2)
myStack.push(3)
myStack.pop()
print(myStack.size())
print(myStack.peek())
print(myStack.is_empty())
|
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 17 19:47:20 2018
@author: GEAR
"""
from Queue import *
def hotPotato(namelist, num):
simqueue = Queue() #创建空队列
for name in namelist:
simqueue.enqueue(name) #将参数全部入队列
while simqueue.size() > 1:
for i in range(num):
#假设队首的人拿着东西,先将其出队再入队尾,
simqueue.enqueue(simqueue.dequeue())
simqueue.dequeue() # 在经过num次循环后将队首的元素删除
return simqueue.dequeue()
print(hotPotato(['A','B','C','D'], 1))
|
str=""
found=0
while True:
i=input("enter a friends name: ")
str+=i+" "
c=input("have more friends? ")
if(c=="no"):
break
l=str.split()
s=input("search which friend? ")
for f in range(len(l)):
if(l[f]==s):
print("friend found at",f)
found=1
break
if(found==0):
print("not a friend")
|
cont=1
num=0
false=0
while cont==1 :
str=input("Enter a number: ")
try:
num=int(str)
except:
false=1
if num>0 and false==0:
print("Number entered is:",num)
elif false==1:
print("not a number")
cont=int(input("do you want to continue: "))
false=0
print("Program done")
|
l=list()
while True:
i=input("Enter a number: ")
if(i=="done"):
break
try:
l.append(float(i))
except:
print("wrong input")
print("Average:",sum(l)/len(l))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if not p or not q:
return p == q
return p.val == q.val and \
self.isSameTree(p.left, q.left) and \
self.isSameTree(p.right, q.right)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
if n == 0:
return []
return self.helper(1, n)
def helper(self, min: int, max: int) -> List[TreeNode]:
ans = []
if min > max:
ans.append(None)
return ans
for i in range(min, max + 1):
leftTree = self.helper(min, i - 1)
rightTree = self.helper(i + 1, max)
for left in leftTree:
for right in rightTree:
root = TreeNode(i)
root.left = left
root.right = right
ans.append(root)
return ans
|
transdict={'G':'C','C':'G','T':'A','A':'U'}
dna=list(raw_input("Enter the strand value : "))
#checks if the value is in list or not and if not then prints x
for node in dna:
if node.upper() in transdict:
print transdict.get(node.upper())
else:
print 'X' |
alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def count():
strings = raw_input()
length = len(strings)
chars = 0
for i in alpha:
if(strings.count(i)%2 != 0):
chars += 1
if((chars == 0) and (length%2 == 0)):
print "YES"
if(chars == 1):
if(length%2 == 1):
print "YES"
else:
print "NO"
if(chars > 1):
print "NO"
count()
|
import sys
def substringafter(string, after, offset=0):
if (after.lower() in string.lower()):
return string[string.lower().index(after.lower()) + len(after) + offset:]
return string
def substringbefore(string, before, offset=0):
if (before.lower() in string.lower()):
return string[:string.lower().index(before.lower()) + offset]
return string
def rsubstringafter(string, after, offset=0):
if (after.lower() in string.lower()):
return string[string.lower().rindex(after.lower()) + len(after) + offset:]
return string
def rsubstringbefore(string, before, offset=0):
if (before.lower() in string.lower()):
return string[:string.lower().rindex(before.lower()) + offset]
return string
|
def half(entStr):
evens = ""
odds = ""
if len(entStr) % 2 ==0:
for i in range(len(entStr)/2-1, -1,-1):
evens = entStr[i] + evens
print evens
if not (len(entStr) % 2 ==0):
for i in range((len(entStr)-1)/2,-1, -1):
odds = entStr[i] + odds
print odds |
# this funciton takes two argument
# one is the picture path used to upload picture to drop on the canvas
# another one is the path used to save the final picture
import random
def turtleImage(pictPath,savePath):
# 1. create an image with random drawing
# 2. use the random drawing image as the background
canvas = makeEmptyPicture(1280,960)
bgTurtle = makeTurtle(canvas)
# call the randomDrawing function to draw a random background
randomDrawing(bgTurtle)
# 3. drop 4 tutles
ta = makeTurtle(canvas)
tb = makeTurtle(canvas)
tc = makeTurtle(canvas)
td = makeTurtle(canvas)
# move them to 4 corners without pen mark
turtleToCorner(ta,0,0)
turtleToCorner(tb,1280,0)
turtleToCorner(tc,1280,960)
turtleToCorner(td,0,960)
# 4. turtles chase toward each other and draw linse
# till all converge in the center
for i in range(0,600):
chaseTurtle(ta,tb)
chaseTurtle(tb,tc)
chaseTurtle(tc,td)
chaseTurtle(td,ta)
# 5. another turtle drops 4 small images in a square
my_pict = makePicture(pictPath)
dropTurtle = makeTurtle(canvas)
# use the turtleToCorner funciton to move the turtle
# the square is 720*720 while the canvas is 1280*960
# 280=(1280-720)/2,120=(960-720)/2
turtleToCorner(dropTurtle,280,120)
dropTurtle.turnRight()
# 6. call the dropPicture function to drop 4 images in a square without covering the center
dropPicture(dropTurtle,my_pict)
# show the canvas
show(canvas)
# 7. write the image to disk
writePictureTo(canvas,savePath)
# 1st sub-function to draw a random background
def randomDrawing(turtle):
turtle.setPenColor(green)
for i in range(0,2000):
turtle.forward(int(100*random.random()))
turtle.turn(int(100*random.random()))
# 2nd sub-function to move 4 turtles to 4 corners
def turtleToCorner(turtle,x,y):
# leave no pen marks
turtle.penUp()
turtle.moveTo(x,y)
turtle.penDown()
# 3rd sub-function to make turtles to chase after each other
def chaseTurtle(t1,t2):
t1.turnToFace(t2)
# set the pen width as 10 pix
t1.setPenWidth(10)
t1.forward(4)
# 4th sub-function to drop pictures in a square 720*720
def dropPicture(turtle,pict):
# leave no pen marks
turtle.penUp()
for i in range(0,4):
turtle.forward(480)
turtle.drop(pict)
turtle.forward(240)
turtle.turnRight() |
# this program is to create a pink flower using turtles of 3 subclasses
def patternTurtle(filename):
# what makeWorld makes isn't pictures therefore cann't be written to disk
# use makeEmptyPicture here for saving later
world = makeEmptyPicture(1000,1000)
# first turtle draws green leaves, belongs to the greenTurtle subclass
outT = greenTurtle(world)
outT.drawLeaf()
# second turtle draws pink petals,belongs to the pinkTurtle subclass
middleT = pinkTurtle(world)
middleT.drawFlower()
# third turtle draws the center of the flower,belongs to the redTurtle subclass
centerT= redTurtle(world)
centerT.drawHeart()
explore(world)
# set the media path to save the file with a given name
setMediaPath("C:/Temp/")
writePictureTo(world,getMediaPath(filename))
# draw triangles 20 times, used as the center of the flower
class redTurtle(Turtle):
def drawHeart(self):
for i in range(0,20):
self.turn(18)
for i in range(0,3):
self.setPenWidth(3)
self.setPenColor(red)
self.setBodyColor(red)
self.forward(25)
self.turn(120)
# draw hexagons 10 times, used as the petals
class pinkTurtle(Turtle):
def drawFlower(self):
for i in range(0,10):
self.turn(36)
for i in range(0,6):
self.setPenWidth(5)
self.setPenColor(pink)
self.setBodyColor(pink)
self.forward(100)
self.turn(60)
# draw squares 5 times, used as the leaves
class greenTurtle(Turtle):
def drawLeaf(self):
for i in range(0,5):
self.turn(72)
for i in range(0,4):
self.setPenWidth(3)
self.setPenColor(green)
self.setBodyColor(green)
self.forward(200)
self.turn(90) |
filename = 'my_checkbook_plus.txt'
#Check if file exists
import os.path
from os import path
if not path.exists(filename):
with open(filename, 'w') as f:
f.write(f'0 , {transaction_time} , starting balance')
# Timestamp function
from datetime import datetime
def transaction_time():
dateTimeObj = datetime.now()
timeStr = dateTimeObj.strftime('%Y-%m-%d')
return print(f' , {timeStr}')
# Menu functions
def menu_choice():
choice = input('What would you like to do?\n\n\
1) view current balance\n\
2) record a debit (withdraw)\n\
3) record a credit (deposit)\n\
4) view all historical transactions\n\
5) view all transactions for a single day\n\
6) view all transactions in a category\n\
7) exit\n')
while choice not in ['1', '2', '3', '4', '5', '6', '7']:
print(f'Invalid choice: {choice}')
choice = input('What would you like to do?\n\n\
1) view current balance\n\
2) record a debit (withdraw)\n\
3) record a credit (deposit)\n\
4) view all historical transactions\n\
5) view all transactions for a single day\n\
6) view all transactions in a category\n\
7) exit\n')
else:
return choice
def debit_category_choice():
choice = input('Please select a category for this withdrawal: \n\
a = work expense \n\
b = school expense \n\
c = household expense \n\
d = other\n')
while choice not in ['a', 'b', 'c', 'd']:
print('Invalid selection. Please try again.')
choice = input('Please select a category for this withdrawal: \n\
a = work expense \n\
b = school expense \n\
c = household expense \n\
d = other expense\n')
else:
return choice
def credit_category_choice():
choice = input('Please select a category for this deposit: \n\
a = paycheck \n\
b = gift \n\
c = tax returns \n\
d = other income\n')
while choice not in ['a', 'b', 'c', 'd']:
print('Invalid selection. Please try again.')
choice = input('Please select a category for this deposit: \n\
a = paycheck \n\
b = gift \n\
c = tax returns \n\
d = other\n')
else:
return choice
# clean list of transactions
def get_cleaned_transactions():
with open(filename) as f:
lines = f.read().split('\n')
all_list = []
for line in lines:
all_list.append(line.split(' , '))
return all_list
# balance function
def balance():
all_list = get_cleaned_transactions()
total = 0
balance = []
for sublist in all_list:
balance.append(sublist[0])
for b in balance:
total += float(b)
return round(total, 2)
# debit function
def debit(debit_prompt):
debit_prompt = float(debit_prompt)
with open(filename, 'a') as f:
if debit_prompt > balance():
return print('balance is too low for this debit')
else:
debit_category = debit_category_choice()
while debit_category not in ['a', 'b', 'c', 'd']:
print('Invalid selection. Please try again.')
debit_category_choice()
if debit_category == 'a':
f.write('\n' + f'-{debit_prompt} , {transaction_time()} , work expense')
return print(f'Withdrew ${debit_prompt}, new balance is ${round(balance(), 2)}.')
elif debit_category == 'b':
f.write('\n' + f'-{debit_prompt} , {transaction_time()} , school expense')
return print(f'Withdrew ${debit_prompt}, new balance is ${round(balance(), 2)}.')
elif debit_category == 'c':
f.write('\n' + f'-{debit_prompt} , {transaction_time()} , household expense')
return print(f'Withdrew ${debit_prompt}, new balance is ${round(balance(), 2)}.')
elif debit_category == 'd':
f.write('\n' + f'-{debit_prompt} , {transaction_time()} , other expense')
return print(f'Withdrew ${debit_prompt}, new balance is ${round(balance(), 2)}.')
else:
return print('Something went wrong!')
# credit function
def credit(credit_prompt):
with open(filename, 'a') as f:
credit_category = credit_category_choice()
while credit_category not in ['a', 'b', 'c', 'd']:
print('Invalid selection. Please try again.')
credit_category_choice()
if credit_category == 'a':
f.write('\n' + f'{float(credit_prompt)} , {transaction_time()} , paycheck')
return print(f'Deposited ${float(credit_prompt)}, new balance is ${round(balance(), 2)}.')
elif credit_category == 'b':
f.write('\n' + f'{float(credit_prompt)} , {transaction_time()} , gift')
return print(f'Deposited ${float(credit_prompt)}, new balance is ${round(balance(), 2)}.')
elif credit_category == 'c':
f.write('\n' + f'{float(credit_prompt)} , {transaction_time()} , tax returns')
return print(f'Deposited ${float(credit_prompt)}, new balance is ${round(balance(), 2)}.')
elif credit_category == 'd':
f.write('\n' + f'{float(credit_prompt)} , {transaction_time()} , other')
return print(f'Deposited ${float(credit_prompt)}, new balance is ${round(balance(), 2)}.')
else:
return print('Something went wrong!')
# All transactions to date function
def all_transactions():
with open(filename) as f:
transactions = f.readlines()
for i, line in enumerate(transactions, 1):
print(f'{i}. ', line)
# allow viewer to see all transactions from a given day
def trans_by_day(day_prompt):
all_list = get_cleaned_transactions()
date_list = []
for line in all_list:
if line[1] == day_prompt:
date_list.append(line)
for x, y in enumerate(date_list, 1):
print(x, y)
# show all transactions in a category
def get_categories():
cat_choice = input('What category would you like to select?\n\
a = work expense \n\
b = school expense \n\
c = household expense \n\
d = other expense\n\
e = paycheck \n\
f = gift \n\
g = tax returns \n\
h = other income\n')
while cat_choice not in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']:
print('Invalid selection. Please try again.')
cat_choice = input('What category would you like to select?\n\
a = work expense \n\
b = school expense \n\
c = household expense \n\
d = other expense\n\
e = paycheck \n\
f = gift \n\
g = tax returns \n\
h = other income\n')
if cat_choice == 'a':
category = 'work expense'
elif cat_choice == 'b':
category = 'school expense'
elif cat_choice == 'c':
category = 'household expense'
elif cat_choice == 'd':
category = 'other expense'
elif cat_choice == 'e':
category = 'paycheck'
elif cat_choice == 'f':
category = 'gift'
elif cat_choice == 'g':
category = 'tax returns'
elif cat_choice == 'b':
category = 'other income'
else:
print('Something went wrong!')
all_list = get_cleaned_transactions()
cat_list = []
for line in all_list:
if line[2] == category:
cat_list.append(line)
for x, y in enumerate(cat_list, 1):
print(x, y)
return print(f'Showing all transactions in category: {category}')
# checkbook app
print()
print('~~~ Welcome to your terminal checkbook! ~~~')
print()
menu_variable = True
while menu_variable == True:
userchoice = menu_choice()
print()
while userchoice not in ['1', '2', '3', '4', '5', '6', '7']:
print(f'Invalid choice: {userchoice}')
userchoice = menu_choice()
# 1: view current balance
if userchoice == '1':
print(f'Your choice?: {userchoice}')
print()
print(f'Your current balance is ${round(balance(), 2)}.')
print()
userchoice = menu_choice()
# 2: debit
elif userchoice == '2':
print(f'Your choice?: {userchoice}')
print()
debit_prompt = input('How much is the debit? ')
debit(debit_prompt)
print()
userchoice = menu_choice()
# 3: credit
elif userchoice == '3':
print(f'Your choice?: {userchoice}')
print()
credit_prompt = input('How much is the credit? ')
credit(credit_prompt)
print()
userchoice = menu_choice()
# 4: All transactions in file
elif userchoice == '4':
print(f'Your choice?: {userchoice}')
print()
print(all_transactions())
userchoice = menu_choice()
# 5: transactions on a given day
elif userchoice == '5':
print(f'Your choice?: {userchoice}')
print()
day_prompt = input('Please enter a day in this format: yyyy-mm-dd\n')
print(trans_by_day(day_prompt))
userchoice = menu_choice()
# 6: view all transactions in a category
elif userchoice == '6':
print(f'Your choice?: {userchoice}')
print()
get_categories()
userchoice = menu_choice()
elif userchoice == '7':
menu_variable = False
else:
print('Something went wrong!')
break
# 7: exit
print(f'Your choice?: {userchoice}')
print()
print('Thanks, have a great day!')
|
kata = input("masukan kata ")
panjang=len(kata)
satu = round(1/3 * panjang)
dua = round(2/3 * panjang)
print("panjang : ",panjang)
for k in range(0,satu):
print(kata[k],end='')
print(",",end='')
for k in range(satu,dua):
print(kata[k],end='')
print(",",end='')
for k in range(dua,panjang):
print(kata[k],end='')
print("")
for k in range(0,satu):
print(kata[k],end='')
for k in range(satu,dua):
print(kata[k],end='')
print(",",end='')
for k in range(dua,panjang):
print(kata[k],end='')
|
def conversor(tipo_moneda, valor_dolar):
quetzalez = input("¿Cuántos " + tipo_moneda + " tienes?: ")
quetzalez = float(quetzalez)
dolares = quetzalez / valor_dolar
dolares = round(dolares, 2)
dolares = str(dolares)
print("Tienes $ " + dolares + " dolares")
menu = """
Bienvenido al conversor de monedas 😜
1 - Quetzales
2 - Pesos Argentinos
3 - Pesos Mexicanos
Elige una opción"""
opcion = input(menu)
if opcion == '1':
conversor("quetzalez", 7.83)
elif opcion == '2':
conversor("pesos argentinos", 65)
elif opcion == '3':
conversor("pesos mexicanos", 24)
else:
print("Favor colocar una opción válida")
|
num1=int(input("enter value for num1"))
num2=int(input("enter value for num2"))
num1+=1
num2*=2
print(num1,",",num2)
|
start = 2
end = 20
for i in range(start, end):
for j in range(2, i):
if (i % j == 0):
break
else:
print(i)
|
lst=[1,2,3,4]
element=int(input("enter element"))
lst.sort()
low=0
upp=len(lst)-1#3
while(low<upp):#0<3,1<3
total=lst[low]+lst[upp]#5,6
if(total==element):#6==6
print("pairs=",lst[low],lst[upp])#2,4
break
elif(total>element):
upp=upp-1
elif(total<element):#5<6
low=low+1 #1
|
#binary search
# lst=[1.2,3,4,5,6]
# ele=int(input("enter element"))
# task=[i for i in lst if i==ele]
# print(task)
|
f=open("cat","r")
lst=[]
for lines in f:
line=lines.rstrip("\n")
words=line.split(" ")
for word in words:
for char in word:
lst.append(char)
print(lst)
|
class Parent:
def m1(self):
print("inside parent")
class Child(Parent):
def m2(self):
print("inside child")
class subChild(Child):
def m3(self):
print("inside subchild")
sb=subChild()
sb.m3()
sb.m2()
sb.m1()
sb2=Child()
#sb2.m3()//error
sb2.m2()
sb2.m1()
p=Parent()
# p.m3() //error
# p.m2() //error
p.m1()
|
import re
mob=input("enter mob no")
#rule="[0-9]{10}"
#rule="\d{10}"
rule='(91)?\d{10}'
match=re.fullmatch(rule,mob)
if(match==None):
print("invalid")
else:
print("valid") |
num1=int(input("enter value for num1"))
flg=0
for i in range(2,num1):
if(num1%i==0):
flg=1
break
else:
flg=0
if(flg>0):
print("not prime")
else:
print("prime")
|
import datetime
class Bank:
def createAccount(self,acno,personname,bname,balance):
self.acno=acno
self.person_name=personname
self.bank_name=bname
self.balance=balance
def deposit(self,amount):
self.balance+=amount
print("your",self.bank_name,"has been credited with",amount,"aval balance",self.balance)
def withdraw(self,amount):
if(amount>self.balance):
print("insufficient balance in your account")
else:
self.balance-=amount
print("your",self.bank_name,"has been debited with",amount,"on",datetime.date.today(),"aval balance",self.balance)
def balenq(self):
print("your account balance",self.balance)
obj=Bank()
#obj.createAccount(1001,"dinu","sbk",5000)
#obj.withdraw(10000)
#obj.createAccount(1002,"dinu","sbk",50000)
# obj.withdraw(10000)
#obj.createAccount(1002,"dinu","sbk",50000)
#obj.deposit(10000)
obj.createAccount(1002,"dinu","sbk",50000)
obj.balenq() |
lst=[10,11,12,13,14,15,16,17]
search=int(input("serach element"))
flg=0
for item in lst:
if(item==search):
flg=1
break
else:
flg=0
if(flg>0):
print("element found")
else:
print("element not found")
# or
#
#
# piu=[2,4,5,8,10,1,3,5,7,9]
# search=int(input("search element"))
# count=0
# for item in piu:
# if(item==search):
# count=count+1
# break
# else:
# count=0
#
# if(count>0):
# print("element is found")
# else:
# print("element is not found")
|
class Student:
def __init__(self,rol,name,course,total):
self.rol=rol
self.name=name
self.course=course
self.total=total
def printStudent(self):
print("rol no=",self.rol)
print("name=",self.name)
print("course=",self.course)
print("total=",self.total)
def __str__(self):
return self.name # for indicating object by name instead of refernce adds
f=open("student","r")
lst=[]
for lines in f:
data=lines.rstrip("\n").split(",")
print(data)
id=data[0]
name=data[1]
course=data[2]
total=int(data[3])
obj=Student(id,name,course,total)
lst.append(obj)
# print all student name who have total>450
for obj in lst:
#print(obj)
if obj.total>450:
print(obj)
# print highest total
total=[]
for obj in lst:
total.append(obj.total)
maximum=max(total)
for obj in lst:
if obj.total==maximum:
print(obj)
|
lst=[1,2,2,2,4,4]
num=int(input("enter number"))
count=0
for item in lst:
if(item==num):
count+=1
print(count) |
# plot throughput
import numpy as np
import matplotlib.pyplot as plt
plt.rcdefaults()
n = 3
throughput = (9.73, 5.69, 3.10)
hop = ('1', '2', '3')
y_pos = np.arange(len(hop))
width = 0.35
fig, ax = plt.subplots()
rects = ax.bar(y_pos, throughput)
ax.set_ylabel('End-to-end tihroughput (Mbits/sec)')
ax.set_xlabel('Number of hop')
def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
'%d' % float(height),
ha='center', va='bottom')
autolabel(rects)
plt.show()
|
import datetime
import calendar
def findDay(date):
born = datetime.datetime.strptime(date, '%d %m %Y').weekday()
return (calendar.day_name[born])
date = input("Enter your date: ")
print(findDay(date)) |
'''
Algorithms - Practical No.: 1 - Rod Cuttting Problem
Jaisal Shah - 002 - MSc. C.S.
Date: 08/09/2021
'''
def rodCutting(rodLength, cutPrices):
matrix = [[0 for i in range(rodLength + 1)]
for j in range(rodLength + 1)]
for i in range(1, rodLength + 1):
for j in range(1, rodLength + 1):
if i == j:
matrix[i][j] = max(matrix[i-1][j], matrix[i][j] + cutPrices[i])
elif i > j:
matrix[i][j] = matrix[i-1][j]
else:
matrix[i][j] = max(matrix[i-1][j], matrix[i]
[j-i] + cutPrices[i])
print("Matrix Calculations: ")
for i in range(1, len(matrix)):
print(matrix[i][1:])
print()
return matrix[rodLength][rodLength]
rodLength = int(input("Size of Rod: "))
cutPrices = {}
for i in range(1, rodLength + 1):
cutPrices[i] = int(input(f"Price for cut of size {i}: "))
print("The best cost that can be achieved is ",
rodCutting(rodLength, cutPrices))
|
import read_file
#calculate variance
def calc_variance(series):
return sum([(item-series.mean())**2 for item in series])/len(series)
#caculating covariance
def calc_covariance(x,y):
x_mean=x.mean()
y_mean=y.mean()
return sum([(item1-x_mean)*(item2-y_mean) for item1,item2 in zip(x,y)])/len(x)
#caculating correlation values
def calc_correlation(x,y):
covariance=calc_covariance(x,y)
x_st_deviation=calc_variance(x)**(1/2)
y_st_deviation=calc_variance(y)**(1/2)
return covariance/(x_st_deviation*y_st_deviation)
#get dataframe from read.py
movie_reviews=read_file.movie_reviews
#--------------part one--------------
#Recall calc_variance,so we can get variance and standart deviation.
#variance reveals how data cluster or spread aroud mean value.
rt_var=calc_variance(movie_reviews['RT_user_norm'])
rt_stdev=rt_var**(1/2)
mc_var=calc_variance(movie_reviews['Metacritic_user_nom'])
mc_stdev=mc_var**(1/2)
fg_var=calc_variance(movie_reviews['Fandango_Ratingvalue'])
fg_stdev=fg_var**(1/2)
id_var=calc_variance(movie_reviews['IMDB_norm'])
id_stdev=id_var**(1/2)
print("Rotten Tomatoes (variance):", rt_var)
print("Metacritic (variance):", mc_var)
print("Fandango (variance):", fg_var)
print("IMDB (variance):", id_var)
print("\n")
print("Rotten Tomatoes (standard deviation):", rt_stdev)
print("Metacritic (standard deviation):", mc_stdev)
print("Fandango (standard deviation):", fg_stdev)
print("IMDB (standard deviation):", id_stdev)
print("\n")
#----------------part two---------------
#Call the calc_variance method to get the covariance.
rt_fg_covar=calc_covariance(movie_reviews['RT_user_norm'],movie_reviews['Fandango_Ratingvalue'])
mc_fg_covar=calc_covariance(movie_reviews['Metacritic_user_nom'],movie_reviews['Fandango_Ratingvalue'])
id_fg_covar=calc_covariance(movie_reviews['IMDB_norm'],movie_reviews['Fandango_Ratingvalue'])
#Call the calc_correlation method to get the correlation values.
rt_fg_corr=calc_correlation(movie_reviews["RT_user_norm"], movie_reviews["Fandango_Ratingvalue"])
mc_fg_corr=calc_correlation(movie_reviews["Metacritic_user_nom"], movie_reviews["Fandango_Ratingvalue"])
id_fg_corr=calc_correlation(movie_reviews["IMDB_norm"], movie_reviews["Fandango_Ratingvalue"])
print("Correlation between Rotten Tomatoes and Fandango", rt_fg_corr)
print("Correlation between Metacritic and Fandango", mc_fg_corr)
print("Correlation between IMDB and Fandango", id_fg_corr)
|
"""
intervaltree: A mutable, self-balancing interval tree for Python 2 and 3.
Queries may be by point, by range overlap, or by range envelopment.
Interval class
Copyright 2013-2014 Chaim-Leib Halbert
Modifications copyright 2014 Konstantin Tretyakov
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from numbers import Number
from collections import namedtuple
class Interval(namedtuple('IntervalBase', ['begin', 'end', 'data'])):
__slots__ = () # Saves memory, avoiding the need to create __dict__ for each interval
def __new__(cls, begin, end, data=None):
return super(Interval, cls).__new__(cls, begin, end, data)
def overlaps(self, begin, end=None):
if end is not None:
return (
(begin <= self.begin < end) or
(begin < self.end <= end) or
(self.begin <= begin < self.end) or
(self.begin < end <= self.end)
)
elif isinstance(begin, Number):
return self.contains_point(begin)
else: # duck-typed interval
return self.overlaps(begin.begin, begin.end)
def contains_point(self, p):
return self.begin <= p < self.end
def range_matches(self, other):
return (
self.begin == other.begin and
self.end == other.end
)
def contains_interval(self, other):
return (
self.begin <= other.begin and
self.end >= other.end
)
def distance_to(self, other):
"""
Returns the size of the gap between intervals, or 0
if they touch or overlap.
"""
if self.overlaps(other):
return 0
elif self.begin < other.begin:
return other.begin - self.end
else:
return self.begin - other.end
def is_null(self):
"""
Returns True if nothing is contained in this interval, i.e. end <= begin.
"""
return self.begin >= self.end
def length(self):
if self.is_null():
return 0
return self.end - self.begin
def __hash__(self):
return hash((self.begin, self.end))
def __eq__(self, other):
return (
self.begin == other.begin and
self.end == other.end and
self.data == other.data
)
def __cmp__(self, other):
s = self[0:2]
o = other[0:2]
if s != o:
return -1 if s < o else 1
try:
if self.data == other.data:
return 0
return -1 if self.data < other.data else 1
except TypeError:
s = type(self.data).__name__
o = type(other.data).__name__
if s == o:
return 0
return -1 if s < o else 1
def __lt__(self, other):
return self.__cmp__(other) < 0
def __gt__(self, other):
return self.__cmp__(other) > 0
def _get_fields(self):
"""Used by str, unicode, repr and __reduce__.
Returns only the fields necessary to reconstruct the Interval.
"""
if self.data is not None:
return self.begin, self.end, self.data
else:
return self.begin, self.end
def __repr__(self):
if isinstance(self.begin, Number):
s_begin = str(self.begin)
s_end = str(self.end)
else:
s_begin = repr(self.begin)
s_end = repr(self.end)
if self.data is None:
return "Interval({0}, {1})".format(s_begin, s_end)
else:
return "Interval({0}, {1}, {2})".format(s_begin, s_end, repr(self.data))
__str__ = __repr__
def copy(self):
return Interval(self.begin, self.end, self.data)
def __reduce__(self):
"""
For pickle-ing.
"""
return Interval, self._get_fields()
|
import json
import csv
def parse_tweets(number_of_lines, file_name):
print("Calculating reply relations...")
network = {} # This is a dictionary where all reply relations between users will be stored.
def insert_user(id_str, screen_name=None): # A function which ...
if id_str not in network: # ... inserts a user into the dictionary if he/she doesn't exist or ...
network[id_str] = {"screen_name": screen_name, # The screen name of the user
"n_tweets": 0,
"n_replies_from": 0, # The number of times other users replied to this user
"n_replies_to": 0, # The number of times this user replied to other users
"replies_from": {}, # The dictionary of users who replied to this user
"replies_to": {} # The dictionary of users who this user replied to
}
else: # ... increments the number of tweets by the user if the user already exists.
network[id_str]["n_tweets"] += 1
with open("tweets.json") as json_file, \
open("errors.csv", "w+") as errors_file: # Open the original JSON file and open an errors file for writing down errors
errors_writer = csv.writer(errors_file)
errors_writer.writerow(["line_number", "original_string", "error"]) # Write the headers into errors.csv file
count = 1 # This variable will be used to track progress
for line in json_file:
if count >= number_of_lines: #parse only the first 10000 lines
break
try:
line = line.strip()
d = json.loads(line) # Parse the line and store the reference to it in variable d.
except: # If an error happened while parsing the line ...
errors_writer.writerow([str(count), line, "Error parsing the line"]) # ... write it down to errors.csv.
else:
if "id_str" not in d: # If d doesn't have id_str field, it is not a valid tweet object. So ...
errors_writer.writerow([str(count), line, "Not a tweet"]) #... write it to the errors.csv file.
else: # If there are no errors, ...
insert_user(d["user"]["id_str"], d["user"]["screen_name"]) # ... pass "id_str" to insert_user function.
if d["in_reply_to_user_id_str"] is not None: # If the tweet is a reply ...
insert_user(d["in_reply_to_user_id_str"]) # ... pass "in_reply_to_user_id_str" to insert_user function.
if d["in_reply_to_user_id_str"] not in network[d["user"]["id_str"]]["replies_to"]:
# If the user has not replied to "in_reply_to_user_id_str", create a new entry.
network[d["user"]["id_str"]]["replies_to"][d["in_reply_to_user_id_str"]] = 1
else:
# If the user has already replied to "in_reply_to_user_id_str" increment the replies count.
network[d["user"]["id_str"]]["replies_to"][d["in_reply_to_user_id_str"]] += 1
# Increment the total number of times the user has replied
network[d["user"]["id_str"]]["n_replies_to"] += 1
# If "in_reply_to_user_id_str" has not received replies from the user, create a new entry, ...
if d["user"]["id_str"] not in network[d["in_reply_to_user_id_str"]]["replies_from"]:
network[d["in_reply_to_user_id_str"]]["replies_from"][d["user"]["id_str"]] = 1
else:
# ... else increment the count
network[d["in_reply_to_user_id_str"]]["replies_from"][d["user"]["id_str"]] += 1
# Increment the total number of times "in_reply_to_user_id_str" has ...
# ... received replies from other users
network[d["in_reply_to_user_id_str"]]["n_replies_from"] += 1
if count % 100000 == 0: # Print a message every 100k lines
print(count, "lines parsed.")
count += 1
print()
print("Generating output...")
# Now create a dictionary following this structure: https://bl.ocks.org/mbostock/2675ff61ea5e063ede2b5d63c08020c7#miserables.json
graph = {"nodes": [], "links": []}
for user_id in network:
graph["nodes"].append({"id": user_id,
"screen_name": network[user_id]["screen_name"],
"n_replies_from": network[user_id]["n_replies_from"]})
for responder in network[user_id]["replies_from"]:
value = network[user_id]["replies_from"][responder]
del network[responder]["replies_to"][user_id]
if responder in network[user_id]["replies_to"]:
value += network[user_id]["replies_to"][responder]
del network[responder]["replies_from"][user_id]
graph["links"].append({"source": user_id, "target": responder, "value": value})
print()
print("Writing output to file...")
# Finally store the output in graph.json file
with open(file_name, "w+") as graph_file:
json.dump(graph, graph_file)
print("Done.")
|
# modules are built-in codes from python standard library
# import the random and string Modules
import random
import string
# Utilize the string module's custom method: ".ascii_letters"
print(string.ascii_letters)
# Utilize the random module's custom method randint
for x in range(10):
print(random.randint(1, 10))
|
# Nice shortcuts:
# Ctrl + R = Replace
# Ctrl + F = Find
# Ctrl + D = Duplicate line
# Ctrl + / = Comment block of lines
# Statistics Training
# You can find this on: HackerRank -> Challenges (Tutorials) -> 10 Days of Statistics
# This is: Day 2 - Basic Probability
print("---------- Task 1 ----------")
# In a single toss of 2 fair (evenly-weighted) six-sided dice, find the probability that their sum will be at most 9.
# Answer: 5 / 6
# Statistics Training
# You can find this on: HackerRank -> Challenges (Tutorials) -> 10 Days of Statistics
# This is: Day 2 - More Dice
print("---------- Task 2 ----------")
# In a single toss of 2 fair (evenly-weighted) six-sided dice, find the probability that the values rolled by each die will be different and the two dice have a sum of 6.
# Answer: 1 / 9
# Statistics Training
# You can find this on: HackerRank -> Challenges (Tutorials) -> 10 Days of Statistics
# This is: Day 2 - Compound Event Probability
print("---------- Task 3 ----------")
# There are 3 urns labeled X, Y, and Z.\
# Urn X contains 4 red balls and 3 black balls.
# Urn Y contains 5 red balls and 4 black balls.
# Urn Z contains 4 red balls and 4 black balls.
# One ball is drawn from each of the urns. What is the probability that, of the balls drawn, are red and is black?
# Answer: 17 / 42
|
"""
Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.
"""
# Complete the plusMinus function below.
def plusMinus(arr):
pos = neg = zer = 0
tot = len(arr)
for i in range(0, tot):
if arr[i] > 0:
pos += 1
elif arr[i] < 0:
neg += 1
else:
zer += 1
if tot > 0:
pos = pos / tot
neg = neg / tot
zer = zer / tot
print("%8.6f"% (pos))
print("%8.6f"% (neg))
print("%8.6f"% (zer))
|
"""
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example, arr[1,3,5,7,9]. Our minimum sum is 1+3+5+7=16 and our maximum sum is 3+5+7+9=24.
We would print :
> 16 24
"""
# Complete the miniMaxSum function below.
def miniMaxSum(arr):
minimo = maximo = 0
arr.sort()
# option 1
minimo = sum(arr[0:4])
maximo = sum(arr[-4:])
# option 2
#for i in range(0,len(arr)-1):
# minimo += arr[i]
#for j in range(len(arr)-1, 0, -1):
# maximo += arr[j]
# output
print(minimo, maximo)
|
# c05ex12.py
# Future value with formatted table.
def main():
print("This program calculates the future value of an investment.")
print()
principal = float(input("Enter the initial principal: "))
apr = float(input("Enter the annualized interest rate: "))
years = int(input("Enter the number of years: "))
print("Year Value")
print("--------------")
for i in range(years+1):
print("{0:3} ${1:7.2f}".format(i, principal))
principal = principal * (1 + apr)
main()
|
# c08ex04.py
# Syracuse sequence
# Note: Let me know if you find a starting value that doesn't go to 1 :-).
def main():
print("This program outputs a Syracuse sequence\n")
n = int(input("Enter the initial value (an int >= 1): "))
while n != 1:
print(n, end=' ')
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
print(1)
if __name__ == '__main__':
main()
|
from graphics import *
def main():
win = GraphWin()
win.setCoords(-5,-5, 5,5)
# draw the contour of the face
face = Oval(Point(-5,-5), Point(5,5))
face.setOutline("black")
face.setFill("beige")
face.draw(win)
# draw the ears
rightEar = Polygon(Point(4,3), Point(3.5,3.5), Point(4,4.25))
rightEar.draw(win)
leftEar = Polygon(Point(-4,3), Point(-3.5,3.5), Point(-4,4.25))
leftEar.draw(win)
leftEar.setFill("grey")
rightEar.setFill("grey")
# draw the eyes
leftEye = Oval(Point(-3,3), Point(-1.5,2))
leftEye.draw(win)
rightEye = leftEye.clone()
rightEye.move(4,0)
rightEye.draw(win)
rightEye.setFill("blue")
leftEye.setFill("blue")
# draw the nose
nose = Polygon(Point(-0.75,2), Point(-0.3,1), Point(0.25,2))
nose.draw(win)
nose.setFill("grey")
# draw the mouth
mouth = Oval(Point(-3,-2), Point(3,-1))
mouth.draw(win)
mouth.setFill("red")
# close after mouse click
win.getMouse()
win.close()
main()
|
# c03ex04.py
# Calculate distance to a lightning strike
def main():
print("This program calculates the distance from a lightning strike.")
print()
seconds = int(input("Enter number of seconds between flash and crash: "))
feet = 1100 * seconds
miles = feet / 5280.0
print()
print("The lightning is approximately", round(miles,1), "miles away.")
main()
|
# c06ex11.py
# Square each value in a list
def squareEach(nums):
for i in range(len(nums)):
nums[i] = nums[i]**2
def test():
nums = list(range(10))
squareEach(nums)
print(nums)
test()
|
# average6.py
def main():
fileName = input("What file are the numbers in? ")
infile = open(FileName, "r")
total = 0.0
n = 0
line = infile.readline().strip()
while line != "":
total = total + float(line)
n = n + 1
line = infile.readline().strip()
print("\nThe average is", total / n)
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.