blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
bf16f46f94cad68da94c323d0d506b450e0cefc0 | patiregina89/Exercicios-Logistica_Algoritimos | /Questionario.py | 1,945 | 4.0625 | 4 | print("*"*12,"FACULDADE CESUSC","*"*12)
print("CURSO: ANÁLISE E DESENV. DE SISTEMAS")
print("Discipl.: Lógica Computacional e Algorítimos")
print("Turma: ADS11")
print("Nome: Patricia Regina Rodrigues")
print("Exercício:Questionário")
print(("*"*42))
'''
3) Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa
cadastrada, o programa perguntar se o usuário quer ou não continuar. No final
mostre:
a. a) Quantas pessoas tem mais de 18 anos.
b. b) Quantos homens foram cadastrados.
c. c) Quantas mulheres tem menos de 20 anos.
'''
qtd_pessoa_18 = 0
qtd_homem = 0
qtd_mulher = 0
while True:
idade = int(input("Informe a idade: "))
sexo = ' '
while sexo not in 'MF':
sexo = str(input("Informe o sexo [M/F]: "))
if idade >= 18:
qtd_pessoa_18 += 1
if sexo == 'M':
qtd_homem += 1
if sexo == 'F' and idade < 20:
qtd_mulher += 1
resp = ' '
while resp not in 'SN':
resp = str(input("Quer continuar [S/N]? "))
if resp == 'N':
break
print("Finalizado!")
print("A quantidade de pessoas, maior de 18 anos, cadastradas é: %d"%qtd_pessoa_18)
print("A quantidde de homens cadatsrados é: %d"%qtd_homem)
print("A quantidade de mulheres com menos de 20 anos cadastrdas é: %d"%qtd_mulher)
'''
Criei 3 variávei atribuidas o valor de 0 pois utilizamos para cacular as quantidades, conforme as perguntas.
Criei também a variável resp para saber se o usuário quer continuar respondendo ou finalizar o programa 'break'.
Usei o while true, pois quero que ele repita a perguntas várias vezes até que o usuáro decida parar com o comando 'N'
Pedi que informassem a idade; Pedi que informassem o sexo, porém fiz uma condição para que aceitem apenas M ou F, caso contrário, ele repete a pergunta.
Feito isso, utilizei o if para responder as perguntas e utilizei a formula para somar à variável existente+1.
''' |
e7fcefbf8508b463718639ae1098f2933eff8c24 | patiregina89/Exercicios-Logistica_Algoritimos | /Funcao_calculos.py | 771 | 3.921875 | 4 | import sys
'''ARQUIVOS NÃO EXECUTAVEIS. sao apenas funções pré-determinadas.'''
def somar():
x = float(input('Digite o primeiro número: '))
y = float(input('Digite o segundo número: '))
print('Somar: ', x + y)
def subtrair():
x = float(input('Digite o primeiro número: '))
y = float(input('Digite o segundo número: '))
print('Subtrair: ', x - y)
def multiplicar():
x = float(input('Digite o priemiro número: '))
y = float(input('Digite o segundo número: '))
print('Multiplicar: ', x * y)
def dividir():
x = float(input('Digite o primeiro número: '))
y = float(input('Digite o segundo número: '))
print('Dividir: ', x / y)
def sair():
print('Saindo do sistema!')
sys.exit(0) |
509db82ab08a4667d0642c5f952301717c291fb9 | patiregina89/Exercicios-Logistica_Algoritimos | /Condicao_Parada999.py | 1,444 | 4.21875 | 4 | print("*"*12,"FACULDADE CESUSC","*"*12)
print("CURSO: ANÁLISE E DESENV. DE SISTEMAS")
print("Discipl.: Lógica Computacional e Algorítimos")
print("Turma: ADS11")
print("Nome: Patricia Regina Rodrigues")
print("Exercício:Condição parada 999")
print(("*"*42))
'''
Crie um programa que leia vários números inteiros pelo teclado. O programa só vai
parar quando o usuário digitar o valor de 999 (flag), que é a condição de parada. No
final mostre quantos números foram digitados e qual foi a soma entre eles
(desconsiderando o flag - 999)
'''
soma = 0
num_digitado = 0
while True:
num = int(input("Digite um número ou 999 para sair: "))
if num == 999:
break
soma = soma + num
num_digitado = num_digitado + 1
print("A soma dos números digitados é: ",soma)
print("A quantidade de números digitados é: ", num_digitado)
'''
Criei uma variável soma atribuida o valor de 0, pois pedem a soma dos valores digitados.
Também criei a variável num_digitado com valor atribuido de 0 pois, o exercicio quer saber quantos números foram digitados.
Usei o while true pois significa que enquanto a condição for verdadeira, o sistema irá se repetir. Então:
enquanto o número digitado for diferente de 999, ele vai repetir o pedido de digitar novo número.
Assim que o usuário digitar 999, o programa se encerra e ele informa a soma dos números digitados e a quantidade de números digitados.
''' |
ec39f6b56f562c88fb97f60df1037443664419f4 | patiregina89/Exercicios-Logistica_Algoritimos | /repeticao_aninhada.py | 260 | 3.984375 | 4 | tabuada = 1
while tabuada<=10:
numero = 1
while numero <= 10:
print("%d x %d = %d"%(tabuada, numero, tabuada*numero))
numero = numero + 1
#numero += 1 ---> mesma coisa da sequencia acima
print("="*14)
tabuada+=1 |
7bb23b547c4e1c5993093195c726b8b54f42a820 | patiregina89/Exercicios-Logistica_Algoritimos | /Dic_comparando_paises.py | 1,543 | 3.984375 | 4 |
print()
#Criar dicionário
dic_Paises = {'Brasil': 211049519,
'França': 65129731,
'Portugal': 10226178,
'México': 10226178,
'Uruguai': 3461731}
#utilizar os métodos do dicionário
print('********************** 1 - Método **********************')
print(dic_Paises)
print(dic_Paises.keys())
print(dic_Paises.values())
print('A população extimada do Brasil é: ', dic_Paises.get('Brasil'))
print()
print()
#percorrer todos os elementos do meu dicionário
print('***** 2 - Percorrer todos os elemnetos do dicionário *****')
for k, v in dic_Paises.items():
print(k, '-->', v)
print()
print()
#usando outras funções
print('******************** 3 - Outras Funções ********************')
print('----- 3.1 - Len (contar número de chaves do dicionário -----')
print('Total de chaves: ', len(dic_Paises))
print()
print('---------- 3.2 - Min e Max (maior e menor chave) ----------')
print('Menor chaves: ', min(dic_Paises), '(ordem alfabética)')
print('Maior chaves: ', max(dic_Paises), '(ordem alfabética)')
print()
print()
#combinar dicionários
dic_Novos_Paises = {'Belize': 390351,
'Tanzânia': 58005461}
print('**************** 4 - Atualizando dicionários ****************')
dic_Paises.update(dic_Novos_Paises)
print('Dicionário Atualizado', dic_Paises)
print()
print()
#limpeza do dicionário
print('**************** 5 - Destruindo dicionário ****************')
dic_Paises.clear()
print(dic_Paises) |
dcf778368e954f93a6ae7e05677ad4b1f37384c8 | patiregina89/Exercicios-Logistica_Algoritimos | /Exercicio3_Notas.py | 695 | 4 | 4 | print("*"*12,"FACULDADE CESUSC","*"*12)
print("CURSO: ANÁLISE E DESENV. DE SISTEMAS")
print("Discipl.: Lógica Computacional e Algorítimos")
print("Turma: ADS11")
print("Nome: Patricia Regina Rodrigues")
print("Exercício 3 - Média notas")
print(("*"*42))
#3. Faça um Programa que leia 4 notas, mostre as notas e a média na tela.
nota1 = float(input('Informe a primeira nota: '))
nota2 = float(input('Informe a segunda nota:' ))
nota3 = float(input('Informe a terceira nota: '))
nota4 = float(input('Informe a quarta nota: '))
media = (nota1 + nota2 + nota3 + nota4) / 4
lista = [nota1, nota2, nota3, nota4]
print('A suas notas foram:{}, e a sua média final é {:.2f}'.format(lista, media)) |
9c2c799fbfd1d11762fcf1c25a2a413ae2087b91 | patiregina89/Exercicios-Logistica_Algoritimos | /Lista_Soma_Notas2.py | 229 | 3.765625 | 4 | notas = [0.0, 0.0, 0.0]
notas[0] = float(input("Informe a nota 1: "))
notas[1] = float(input("Informe a nota 2: "))
notas[2] = float(input("Informe a nota 3: "))
print("A somas das notas é: ", notas[0]+notas[1]+notas[2]) |
0b6d65ee7e88de9c04723eba487b5e807571cd2f | CoCode2018/Refresher | /Python/笨办法学Python3/Exercise 1.py | 1,216 | 3.5 | 4 | """
slightly
adv.轻微地,轻轻地;细长地,苗条地;〈罕〉轻蔑地;粗
exactly
adv.恰恰;确切地;精确地;完全地,全然
SyntaxError
语法错误
Usually
adv.通常,经常,平常,惯常地;一直,向来;动不动,一般;素
cryptic
adj.神秘的;隐藏的;有隐含意义的;使用密码的
Drills
n.钻头;操练( drill的名词复数 );军事训练;(应对紧急情况的)演习
v.训练;操练;钻(孔)( drill的第三人称单数 );打(眼)
explain
vt.& vi.讲解,解释
vt.说明…的原因,辩解
vi.说明,解释,辩解
#
An "octothorpe" is also called a "pound", "hash", "mesh", or any number of names.
Pick the one that makes you chill out.
common
adj.普通的;通俗的;[数学]公共的;共有的
n.普通;[法律](对土地、水域的)共有权;公共用地;平民
Common Student Questions
学生常见问题
"""
# ex1.py
print("Hello World!")
print("Hello Again")
print("I like typing this.")
print("This is fun.")
print('Yay! Printing.')
print("I'd much rather you 'not'.")
print('I "said" do not touch this.')
# Study Drills
print("学习演练")
# 注释
print("# 起注释作用")
|
a83d4a66c989c107a57dadf4dcfb8e597e14a107 | CoCode2018/Refresher | /Python/笨办法学Python3/Exercise 18.py | 1,416 | 4.71875 | 5 | """
Exercise 18: Names, Variables, Code, Functions
1.Every programmer will go on and on about functions
introduce
vt.介绍;引进;提出;作为…的
about to
即将,正要,刚要;欲
explanation
n.解释;说明;辩解;(消除误会后)和解
tiny
adj.极小的,微小的
n.小孩子;[医]癣
related
adj.有关系的;叙述的
vt.叙述(relate过去式和过去分词)
break down
失败;划分(以便分析);损坏;衰弱下来
except that
n.除了…之外,只可惜
asterisk
n.星号,星状物
vt.加星号于
parameter
n.[数]参数;<物><数>参量;限制因素;决定因素
indenting
n.成穴的
v.切割…使呈锯齿状( indent的现在分词 );缩进排版
colon
n.冒号;<解>结肠;科郎(哥斯达黎加货币单位
right away
就;立刻,马上;当时
"""
# this one if like your scripts with argv
def print_two(*args):
arg1, arg2, arg3 = args
print(F"arg1: {arg1}\narg2: {arg2}\narg3: {arg3}\nargs: {args}")
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print(F"arg1: {arg1}\narg2: {arg2}")
# this just takes one argument
def print_one(arg1):
print(F"arg1: {arg1}")
# this one takes no arguments
def print_none():
print("I got nothin'.")
print_two("Zed", "Shaw", "ZhouGua")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none() |
c0c7eb4b9ada3385e0f96acca76bcf758080851e | AlphaBitClub/alphabit-coding-challenge | /alphabit-coding-challenge-01/03_zeros/solutions/zeros.py | 432 | 3.625 | 4 | # count the multiplicity of the factor y in x
def multiplicity(x, y):
count = 0
while x % y == 0:
x //= y
count += 1
return count
n = int(input())
two = 0
five = 0
for _ in range(n):
x = int(input())
if x % 2 == 0:
two += multiplicity(x, 2)
if x % 5 == 0:
five += multiplicity(x, 5)
# the min is the number of pairs of (2, 5)
zeros = min(two, five)
# OUTPUT
print(zeros) |
a71c8a60aafc290dab24730570a42709f24d5627 | luislama/algoritmos_y_estructuras_de_datos | /algoritmos/17_suma_de_primos/suma_de_primos.py | 1,570 | 3.59375 | 4 | '''
Encuentre la suma de los numeros primos menores a 2 millones
'''
'''
Analisis
Anteriormente, el numero primo mayor a calcular fue el 10001, el algoritmo de buscar los numeros primos no era eficiente,
pero no representaba un problema
En este caso, el tope es de 2000000 y necesita otro enfoque
Se utiliza un arreglo para ir almacenando los numeros primos, sin embargo no es suficiente
Investigando, se encuentra un metodo que evita el tener que verificar si cada numero es primo dentro de la serie
Se utiliza un arreglo para marcar los numeros no primos dentro de la serie, y al avanzar por el arreglo, aquellos que
no estan marcados, son primos
0 1 2 3 4 5 6 7 8 9 10
1 1 0 0 1 0 1 0 1 1 1
0 no es primo
1 no es primo
2 si es primo, encuentro sus multiplos dentro de la serie
2 4 6 8 10
0 1 2 3 4 5 6 7 8 9 10
1 1 0 0 1 0 1 0 1 0 1
3 no esta marcado, es primo, encuentro sus multiplos
3 9
0 1 2 3 4 5 6 7 8 9 10
1 1 0 0 1 0 1 0 1 1 1
de esta manera, tachando los multiplos que son faciles de calcular, se pueden sumar los primos sin necesidad de hacer la verificacion
se necesita el arreglo de 2000001 elementos
'''
MAX = 2000000
numeros = [0]*(MAX + 1)
numeros[0] = 1
numeros[1] = 1
suma_de_primos = 0
for i in range(MAX + 1):
if numeros[i] == 0:
suma_de_primos += i
for mult in range(i, int(MAX/i) + 1):
numeros[i * mult] = 1
print("".join(["La suma de los numeros primos menores a ", str(MAX), " es: ", str(suma_de_primos)]))
|
55ba0cf476b6e3bb1b11adfee422b27374244d74 | sukritsangvong/Hearts | /main.py | 4,422 | 4 | 4 | #Final project for CS 111 with DLN
#PJ Sangvong and Ben Aoki-Sherwood
#Hearts
from heartCard import *
from playable import *
from turnFunction import *
from calculateScore import *
from roundFunction import *
from takeCardFromBoard import *
from botswap import *
from heartsBoard import *
def main():
'''Runs the card game Hearts, displayed in a graphics window (with some
information also in the terminal window).'''
input("Welcome to Hearts! Press ENTER to start.")
#Create the players and the starting deck
deck, players = createDeck(), generatePlayers()
#Deal the cards
for player in players:
assignHand(player,deck, 13)
makeSortedHand(player)
window = setup()
player0Hand = players[0].getHand()
clickZone = slotForCardOnHand(window, player0Hand)
Tie = False
roundCount = 1
#The game continues as long as no one reaches a score of 20. If a player
#reaches 20 points but there is a tie for the lowest score, play continues
while (players[0].getScore() < 20 and players[1].getScore() < 20 \
and players[2].getScore() < 20 and players[3].getScore() < 20) or Tie:
print("You: ", players[0].getHand())
print("-----------")
print("Bot 1: ", players[1].getHand())
print("-----------")
print("Bot 2: ", players[2].getHand())
print("-----------")
print("Bot 3: ", players[3].getHand())
print("-----------")
#Initializing variables at the beginning of each round
roundCount = roundCount % 4
displayTextChooseCard(window, roundCount, False)
cardSwap(players,roundCount, clickZone, window)
giveSwaps(players,roundCount)
displayTextChooseCard(window, roundCount, True)
player0Hand = players[0].getHand()
clickZone = slotForCardOnHand(window, player0Hand)
index2ofClubs = find2OfClubs(players)
#Updates the players and determines who will lead the next trick,
#as well as whether hearts have been broken yet or not
players, indexOfNextPlayer, isHeartPlayed, clickZone = \
turn(players, index2ofClubs, True, \
False, window, clickZone)
if index2ofClubs == 0:
player0Hand = players[0].getHand()
clickZone = slotForCardOnHand(window, player0Hand)
print("-x-x-x-x-x-x-x-x-x-x-x-x-x-x--x Turn Ended -x-x-x-x-x-x-x-x-x-x-x-x-x-x--x")
while players[0].getHand() != [[],[],[],[]]:
players, indexOfNextPlayer, isHeartPlayed, clickZone = \
turn(players, indexOfNextPlayer, False, \
isHeartPlayed, window, clickZone)
updateScore(players[indexOfNextPlayer])
players[indexOfNextPlayer].clearGraveyard()
playerScore = players[indexOfNextPlayer].getScore()
score(window, playerScore, indexOfNextPlayer, False)
print("-x-x-x-x-x-x-x-x-x-x-x-x-x-x--x Turn Ended -x-x-x-x-x-x-x-x-x-x-x-x-x-x--x")
scores = []
for player in players:
scores.append(player.getScore())
#generate new deck
deck = createDeck()
players = generatePlayers()
#give new hands
for player in players:
assignHand(player,deck, 13)
makeSortedHand(player)
player.setScore(scores[players.index(player)])
#new round
roundCount += 1
#determining if there is a tie at end of round
winningPlayerIndex = 0
lowestScore = 20
for player in players:
if player.getScore() < lowestScore:
lowestScore = player.getScore()
lowestScoreCount = 0
for player in players:
if player.getScore() == lowestScore:
lowestScoreCount += 1
winningPlayerIndex = players.index(player)
if lowestScoreCount > 1:
Tie = True
else:
Tie = False
player0Hand = players[0].getHand()
clickZone = slotForCardOnHand(window, player0Hand)
winner = ''
if winningPlayerIndex == 0:
winner = "You win!"
else:
winner = "Bot " + str(winningPlayerIndex) + " wins!"
print("Game Over!", winner)
if __name__ == "__main__":
main()
|
d5ae00e795446869e908aeec451a5dd8012dd487 | Darkman94/autoencoder | /encode_tf.py | 2,742 | 3.8125 | 4 | from tensorflow.examples.tutorials.mnist import input_data
#not sure this is working the way I think it is
#if it is it's a really poor model
#don't think I need one_hot, since I'm training an autoencoder
#not attempting to learn the classification
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
import tensorflow as tf
#Turn denoising on/off
corrupt = True
#the corruption function for the denoising
def corruption(x):
'''adds a corruption to the input variables uniformly distributed in [-1,1]
params:
x -> the (Tensorflow) value to be corrupted
'''
global corrupt
if corrupt:
return tf.multiply(x,tf.random_uniform(shape=tf.shape(x), minval = -1, maxval = 1, dtype = tf.float32))
else:
return x
#a placeholder is used to store values that won't change
#we'll load this with the MNIST data
#None indicates we'll take arbitrarily many entries in that dimension, na d784 is the size of an individual MNIST image
x = tf.placeholder(tf.float32, [None, 784])
#build our neural network
W_1 = tf.Variable(tf.zeros([784,512]))
b_1 = tf.Variable(tf.zeros([512]))
W_2 = tf.Variable(tf.zeros([512,256]))
b_2 = tf.Variable(tf.zeros([256]))
W_3 = tf.Variable(tf.zeros([256,128]))
b_3 = tf.Variable(tf.zeros([128]))
W_4 = tf.Variable(tf.zeros([128,64]))
b_4 = tf.Variable(tf.zeros([64]))
W_5 = tf.Variable(tf.zeros([64,128]))
b_5 = tf.Variable(tf.zeros([128]))
W_6 = tf.Variable(tf.zeros([128,256]))
b_6 = tf.Variable(tf.zeros([256]))
W_7 = tf.Variable(tf.zeros([256,512]))
b_7 = tf.Variable(tf.zeros([512]))
W_8 = tf.Variable(tf.zeros([512,784]))
b_8 = tf.Variable(tf.zeros([784]))
y_1 = tf.nn.sigmoid(tf.matmul(corruption(x), W_1) + b_1)
y_2 = tf.nn.sigmoid(tf.matmul(y_1, W_2) + b_2)
y_3 = tf.nn.sigmoid(tf.matmul(y_2, W_3) + b_3)
y_4 = tf.nn.sigmoid(tf.matmul(y_3, W_4) + b_4)
y_5 = tf.nn.sigmoid(tf.matmul(y_4, W_5) + b_5)
y_6 = tf.nn.sigmoid(tf.matmul(y_5, W_6) + b_6)
y_7 = tf.nn.sigmoid(tf.matmul(y_6, W_7) + b_7)
y = tf.nn.sigmoid(tf.matmul(y_7, W_8) + b_8)
#Get the function to minimize
loss = tf.nn.l2_loss(y - x)
#create a training step for (batch) gradient descent
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
l2diff = tf.sqrt( tf.reduce_sum(tf.square(tf.subtract(x, y)), reduction_indices=1))
loss_mean = tf.reduce_mean(l2diff)
with tf.Session() as sess:
#initialize our Variables
sess.run(tf.global_variables_initializer())
for _ in range(10000):
#load the next 50 values from MNIST (hre is where the batch comes in)
batch_x, batch_y = mnist.train.next_batch(50)
#run our training step (each Placeholder needs a value in the dictionary)
train_step.run(feed_dict={x: batch_x})
#get the accuracy
print(sess.run(loss_mean, feed_dict={x: mnist.test.images})) |
01d4eeafaf9ddbb6966fe3c9a3a29755942931be | pankajgupta119/Python | /piggy.py | 779 | 4.0625 | 4 | #A Piggybank contains 10 Rs coin, 5 Rs coin , 2 Rs coin and 1 Rs coin then calculate total amount.
print("\tPIGGY BANK")
num1=int(input("Enter the number of 10rs coin\n "))
result1=num1*10
print("The total amount of 10rs coin is",result1)
print("\n")
num2=int(input("Enter the number of 5rs coin\n "))
result2=num2*5
print("The total amount of 5rs coin is",result2)
print("\n")
num3=int(input("Enter the number of 2rs coin\n "))
result3=num3*2
print("The total amount of 2rs coin is",result3)
print("\n")
num4=int(input("Enter the number of 1rs coin\n "))
result4=num4*1
print("The total amount of 1rs coin is",result4)
print("\n")
print("THE TOTAL AMOUNT OF ALL THE COINS IS\n")
total=result1+result2+result3+result4
print(total)
|
008a644d92b235fb12c932f9d8d32785aa557c8b | pankajgupta119/Python | /swap.py | 176 | 3.984375 | 4 | num1=int(input("ENTER NUMBER1"))
num2=int(input("ENTER NUMBER2"))
print("nuber1=",num1)
print("nu2mber=",num2)
num1,num2=num2,num1
print("num1=",num1)
print("num2=",num2) |
7e64a3f0004ba7103ae527be9e661e18a548eef8 | Romko97/Python | /Codawars/1.py | 743 | 3.515625 | 4 | # boolean_list= [True, True, False, True, True, False, False, True]
# print(f"The origion list is{boolean_list}")
# res_true, res_false = [],[]
# for i, item in enumerate(boolean_list):
# temp = res_true if item else res_false
# temp.append(i)
# print(f"True indexes: {res_true}" )
# print(f"False indexes: {res_false}" )
# class Perens:
# def __init__(self, param):
# self.v1= param
# class Chaild(Perens):
# def __init__(self, param):
# self.v2= param
# op = Chaild(11)
# print(op.v1 +' '+ op.v2)
# print(r'\ndfs')
# one = chr(104)
# two = chr(105)
# print(one+two)
# dic = {}
# dic[(1,2,4)] = 8
# dic[(4,2,1)] = 10
# dic[(1,2)] = 12
# sum=0
# for k in dic:
# sum += dic[k]
# print(len(dic)+sum) |
a6ca59324734f9e4fcf75d443b17070b2b14138b | Romko97/Python | /Softserve/HOME_WORK_03.py | 2,926 | 3.625 | 4 | Zen = '''The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!'''
# Знайти кількість слів у стрічці
substring = ["better", "never", "is"]
for i in range(len(substring)):
count = Zen.count(substring[i])
print(count)
print('\n............................\n')
# Вивести весь текст у верхньому регістрі.
# upperString = Zen.upper()
# print(upperString)
print(Zen.upper())
print('\n............................\n')
# Замінити всі літери "і" на "&"
# replaced_i_to_ampersand = Zen.replace('i', '&')
# print(replaced_i_to_ampersand)
print(Zen.replace('i', '&'))
print('\n............................\n')
# Задано чотирицифрове натуральне число.
# first way of solution
# Знайти добуток цифр цього числа.
number = int(input("Please enter nnumber :"))
changed_type = str(number)
product = 1
for i in range(len(changed_type)):
product *= int(changed_type[i])
print("product is :", product)
print('\n............................\n')
# Записати число в реверсному порядку.
# the first way of solution
print('\n.first way of solution \n')
changed_type = str(number)
print(list(reversed(changed_type)))
# the second way of solution.
print('\n.second way of solution \n')
originNumber = number
Reverse = 0
while (number > 0):
Reminder = number % 10
Reverse = (Reverse * 10) + Reminder
number //= 10
print(f"Revers of {originNumber} is {Reverse}")
print('\n............................\n')
print("the third way of solution\n")
number = input("enter number again:")
print(number[::-1])
# Посортувати цифри, що входять в дане число
print(sorted(number))
print('\n............................\n')
# Поміняти між собою значення двох змінних, не використовуючи третьої змінної.
a = input("first var: ")
b = input("second var: ")
# print(f"first var:{a} \nsecond var: {b}")
a, b = b, a
print(f"first var:{a} \nsecond var: {b}")
|
62e85e9955191e8612ad7252c04c248315e3030e | Romko97/Python | /Codawars/06.02.20/Reversing_Words_in_a_String.py | 219 | 4.03125 | 4 | def reverse(st):
st = st.split()
st = st[::-1]
st = ' '.join(st)
return st
def reverse(st):
print(' '.join(st.split()[::-1]))
def reverse(st):
return " ".join(reversed(st.split())).strip()
|
c1cc2522e99d5022a7d680103e1a7c1431aafdf3 | steeju/Free-python-class-with-friends | /DAY 3.py | 1,144 | 3.984375 | 4 | #leap year program
name = int(input("year : "))
if (name%4==0 and name%100!=0) or (name%400==0):
print( name, "is a leap year")
else:
print( name, "not a leap year")
# leap year แต่ไม่ทัน
start = int(input())
end = int(input())
count = 0
for year in range (start, end+1):
if(year%4==0 and year%100!=0) or (year%400==0)
print (year)
count = count + 1 # <- count +1 ไปใส่ใน count
print("total number of leap year = ", count)
#natural number
sum 1 --> input
x = int(input("to which number? "))
sum = 0
for i in range (1, x+1):
#sum = sum + i วิธีล่างเร็วกว่า
sum += i
print (sum)
#sum 1^5 --> input^5
x = int(input("to which number? "))
sum = 0
for i in range (1, x+1):
#sum = sum + i วิธีล่างเร็วกว่า
sum += i**5
print (sum)
#factorial
x = int(input("to which number? "))
product = 1
for i in range (1, x+1):
product *= i
print (product)
#sum 1^n --> input^n
x = int(input("x: "))
n = int(input("n: ))
sum = 0
for i in range (1, x+1)
# sum = sum + i
sum += i**n
print (sum)
#loop
n = 0
while n < 10:
print(n)
|
ce715c678ac816847a3939e61700f50637ef1210 | samcoh/FinalProject206 | /finalproj.py | 39,723 | 3.578125 | 4 | import requests
import json
from bs4 import BeautifulSoup
import sys
import sqlite3
import plotly.plotly as py
import plotly.graph_objs as go
#QUESTIONS:
#1. How to write test cases
#2. Check to see if table okay (list parts)
#3. Joing the table and the data processing for plotly (is okay that i use some part classes)
#4. Does my project add up to enough points
#5. IMDB sometime does not let me do anymore scraping what should i do when this happens? I am afraid to delete my cache because i think if i do the website wont let me collect anymore data
#6. Plotly charts how do i add a title
#------------------LIST OF THINGS TO DO:
#1. Assign theater objects Ids in the class (do this by when inserting theters have own counter )
#2. Instead of grabbing data from movies using name grab it using IDs
num = 0
DBNAME = 'Imdb.sql'
#cache just the html for the sites
CACHE_FNAME = 'cache_theaters.json'
try:
cache_file = open(CACHE_FNAME, 'r')
cache_contents = cache_file.read()
CACHE_DICTION = json.loads(cache_contents)
cache_file.close()
except:
CACHE_DICTION = {}
CACHE = 'cache_movies.json'
try:
cache = open(CACHE, 'r')
contents = cache.read()
CACHE_DICTION_MOVIES = json.loads(contents)
cache.close()
except:
CACHE_DICTION_MOVIES = {}
def params_unique_combination(baseurl):
return baseurl
def cache_theaters(baseurl):
unique_ident = params_unique_combination(baseurl)
if unique_ident in CACHE_DICTION:
return CACHE_DICTION[unique_ident]
else:
resp = requests.get(baseurl)
CACHE_DICTION[unique_ident] = resp.text
dumped_json_cache = json.dumps(CACHE_DICTION)
fw = open(CACHE_FNAME,"w")
fw.write(dumped_json_cache)
fw.close()
return CACHE_DICTION[unique_ident]
def cache_movies(baseurl):
unique_ident = params_unique_combination(baseurl)
if unique_ident in CACHE_DICTION_MOVIES:
return CACHE_DICTION_MOVIES[unique_ident]
else:
resp = requests.get(baseurl)
CACHE_DICTION_MOVIES[unique_ident] = resp.text
dumped_json_cache = json.dumps(CACHE_DICTION_MOVIES)
fw = open(CACHE,"w")
fw.write(dumped_json_cache)
fw.close()
return CACHE_DICTION_MOVIES[unique_ident]
#defined classes
class Theater():
def __init__(self, name, url,street_address,city,state,zip,list_movies):
self.theater_name = name
self.theater_url = url
self.list_movies = list_movies
self.street_address = street_address
self.city = city
self.state = state
self.zip = zip
def __str__(self):
return "{}: {}, {} {}, {}".format(self.theater_name,self.street_address,self.city,self.state,self.zip)
class Movie():
def __init__(self, name, year, time, url, rating, genre, descrip, directors, num_directors, stars, num_stars, more_details_url, gross = "No Gross", weekend="No Opening Weekend Usa", budget="No Budget", cumulative = "No Cumulative Worldwide Gross"):
self.movie_name = name
self.movie_year = year
self.movie_time = time
self.movie_url = url
self.movie_rating = rating
self.movie_genre = str(genre)
self.movie_descrip = descrip
self.movie_directors = str(directors)
self.movie_number_of_directors = num_directors
self.movie_stars = str(stars)
self.movie_number_of_stars = num_stars
self.movie_more_details_url = more_details_url
self.movie_gross_usa = gross
self.movie_opening_weekend_usa = weekend
self.movie_budget = budget
self.movie_worldwide_gross = cumulative
def __str__(self):
return '''{}({})\n\tRating: {} \n\tMinutes: {} \n\tGenre: {} \n\tDirected by: {} \n\tStars: {}\n\tDescription:\n\t\t {}\n\tMONEY:\n\t\t Budget: {}\n\t\t Gross Profit in the USA: {}\n\t\t Opening Weekend in the USA: {}\n\t\t Cumulative Worldwide Gross: {}'''.format(self.movie_name,self.movie_year,self.movie_rating,self.movie_time,self.movie_genre,self.movie_directors,self.movie_stars,self.movie_descrip,self.movie_budget,self.movie_gross_usa,self.movie_opening_weekend_usa, self.movie_worldwide_gross)
#QUESTIONS:
#1. list_movietheaters: ask about not cachining the list of movies because they update everyday
#caching
#can cache list_movietheaters
#movie theaters within 5,10,20,and 30 miles away
def list_movietheaters(zip_code):
zip_code = zip_code
baseurl = "http://www.imdb.com"
url = "http://www.imdb.com/showtimes/location/US/{}".format(zip_code)
#page_text = requests.get(url).text
page_text= cache_theaters(url)
page_soup = BeautifulSoup(page_text, 'html.parser')
content = page_soup.find_all("span", itemprop = "name")
#print(content)
#content = page_soup.find_all("h5", class_ = "li_group")
list_theaters = []
num = 0
for x in content:
theater_name = x.text
theater_link = x.find("a")['href']
full_url = baseurl + theater_link
#uncomment and comment page_text for most recent movie list
# page_text= requests.get(full_url).text
page_text = cache_theaters(full_url)
page_soup = BeautifulSoup(page_text, 'html.parser')
content = page_soup.find_all("div", class_= "info")
movies = []
for y in content:
mov = y.find('h3').text.strip()
list_mov= mov.split("(")
movie_name = list_mov[0]
movies.append(movie_name)
#content = page_soup.find_all(class_= "article listo st")
#content = page_soup.find_all("div", itemtype= "http://schema.org/PostalAddress")
street_address= page_soup.find("span",itemprop="streetAddress").text
city = page_soup.find(itemprop="addressLocality").text
state = page_soup.find(itemprop="addressRegion").text
zip = page_soup.find(itemprop="postalCode").text
class_theaters = Theater(name = theater_name,url =full_url,street_address = street_address,city= city,state= state,zip=zip,list_movies = movies)
list_theaters.append(class_theaters)
# for x in list_theaters:
# movie_information(x)
insert_Theaters(list_theaters,zip_code)
return list_theaters
# content = page_soup.find_all("div", class_= "info")
# for y in content:
# movie_name = y.find('h3').text.strip()
# print(movie_name)
# movies.append(movie_name)
#this function takes in a theater class object
def movie_information(theater_class_object):
baseurl = "http://www.imdb.com"
url = theater_class_object.theater_url
#page_text = requests.get(url).text
page_text = cache_theaters(url)
page_soup = BeautifulSoup(page_text, 'html.parser')
#content= page_soup.find_all("div",class_="description")
#print(content)
content = page_soup.find_all("div", class_= "info")
#content = page_soup.find_all("div",class_="list_item even",itemtype="http://schema.org/Movie")
movies =[]
for y in content:
#movie_name = y.find("span",itemprop= "name").text.strip()
mov = y.find('h3').text.strip()
list_mov= mov.split("(")
movie_name = list_mov[0]
try:
movie_year = list_mov[1][:-1]
except:
movie_year = "No Movie Year"
try:
time = y.find("time",itemprop = "duration").text.strip().split()[0]
except:
time = "No Time"
try:
rating_info = y.find("span", itemprop = "contentRating")
rating = rating_info.find("img")["title"].strip()
except:
rating = "No Rating"
movie_url = y.find('a')['href']
full_url = baseurl + movie_url
page_text = cache_movies(full_url)
page_soup = BeautifulSoup(page_text, 'html.parser')
c = page_soup.find_all("td", class_= "overview-top")
for x in c:
g = x.find_all("span", itemprop = "genre")
genre = []
for s in g:
genre.append(s.text.strip())
descrip = x.find("div", class_="outline", itemprop = "description").text.strip()
d = x.find_all("span", itemprop= "director")
director = []
for f in d:
dir = f.find("a").text.strip()
director.append(dir)
number_of_directors = len(director)
a = x.find_all("span", itemprop = "actors")
stars= []
for actor in a:
act = actor.find("a").text
stars.append(act)
number_of_stars = len(stars)
link = x.find_all("h4",itemprop ="name")
#print(link)
for l in link:
link = l.find("a")['href']
movie_url = baseurl + link
page_text = cache_movies(movie_url)
page_soup = BeautifulSoup(page_text, 'html.parser')
# info = page_soup.find_all("div",class_="article",id="titleDetails")
# for z in info:
detail_info = page_soup.find_all("div",class_= "txt-block")
#print(detail_info)
gross = "No Gross"
weekend = "No Opening Weekend Usa"
budget = "No Budget"
cumulative = "No Cumulative Worldwide Gross"
for detail in detail_info:
try:
d = detail.find("h4",class_= "inline").text.strip()
if d == "Gross USA:":
gross = detail.text.strip()
gross = gross.split()[:3]
#print(gross)
gross= " ".join(gross)[:-1].split()[-1][1:]
#print(gross)
# else:
# gross = "No Gross USA"
#print(gross)
if d == "Opening Weekend USA:":
weekend = detail.text.strip()
weekend = weekend.split()[:4]
weekend =" ".join(weekend)[:-1].split()[-1][1:]
#print(weekend)
# else:
# weekend = "No Opening Weekend USA"
#print(weekend)
if d == "Budget:":
budget = detail.text.strip()
budget = budget.split(":")[1].split("(")[0][1:]
#print(budget)
# else:
# budget = "No Budget"
#print(budget)
if d == "Cumulative Worldwide Gross:":
cumulative = detail.text.strip()
cumulative= cumulative.split()[:4]
cumulative=" ".join(cumulative)[:-1].split()[-1][1:]
except:
#print("except")
continue
mov_object = Movie(name = movie_name, year = movie_year, time = time ,url = full_url, rating = rating, genre = genre, descrip = descrip, directors = director, num_directors = number_of_directors, stars = stars, num_stars = number_of_stars, more_details_url= movie_url, gross = gross, weekend= weekend, budget = budget, cumulative = cumulative)
movies.append(mov_object)
# print(movie_name)
# print(movie_year)
# print(time)
# print(full_url)
# print(descrip)
# print(director)
# print(number_of_directors)
# print(stars)
# print(number_of_stars)
# print(movie_url)
# print(gross)
# print(weekend)
# print(budget)
# print(movies)
insert_Movies(movies,theater_class_object)
return movies
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
# for x in mov:
# print(x.movie_budget,x.movie_gross_usa,x.movie_opening_weekend_usa)
# for x in mov:
# print(x.movie_name)
#making the database:
def init_db(db_name):
conn = sqlite3.connect(db_name)
cur = conn.cursor()
statement = '''
DROP TABLE IF EXISTS 'Movies';
'''
cur.execute(statement)
statement = '''
DROP TABLE IF EXISTS 'Theaters';
'''
cur.execute(statement)
conn.commit()
#left out these three from the table:
#self.movie_url = url
#self.movie_descrip = descrip
#self.movie_more_details_url = more_details_url
statement = '''
CREATE TABLE 'Movies' (
'Id' INTEGER PRIMARY KEY AUTOINCREMENT,
'Name' TEXT NOT NULL,
'ReleaseYear' INTEGER,
'Minutes' INTEGER,
'Rating' TEXT,
'Genre' TEXT NOT NULL,
'Directors' TEXT NOT NULL,
'NumberOfDirectors' INTEGER NOT NULL,
'Stars' TEXT NOT NULL,
'NumberOfStars' INTEGER NOT NULL,
'Budget' INTEGER,
'GrossProfitUSA' INTEGER,
'OpeningWeekendUSA' INTEGER,
'CumulativeWorldwideGross' INTEGER
);
'''
cur.execute(statement)
conn.commit()
#self.theater_url = url
statement = '''
CREATE TABLE 'Theaters' (
'Id' INTEGER PRIMARY KEY AUTOINCREMENT,
'EnteredZipCode' TEXT NOT NULL,
'Name' TEXT NOT NULL,
'StreetAddress' TEXT,
'City' TEXT,
'State' TEXT,
'ZipCode' TEXT,
'MoviesPlaying' TEXT
);
'''
cur.execute(statement)
conn.commit()
conn.close()
def insert_Theaters(List_Theater_Objects,zip):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
for x in List_Theater_Objects:
Name = x.theater_name
EnteredZipCode = zip
StreetAddress = x.street_address
City = x.city
State = x.state
ZipCode= x.zip
MoviesPlaying = None
insert = (None, EnteredZipCode, Name, StreetAddress,City, State,ZipCode,MoviesPlaying)
statement = 'INSERT INTO Theaters VALUES (?,?,?,?,?,?,?,?)'
cur.execute(statement, insert)
conn.commit()
conn.close()
#update_movies_playing(List_Theater_Objects)
def insert_Movies(List_Movie_Objects,theater_class_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
movies_in_sql = []
for x in List_Movie_Objects:
Name = x.movie_name
if Name in movies_in_sql:
continue
else:
movies_in_sql.append(Name)
ReleaseYear = x.movie_year
if ReleaseYear == "No Movie Year":
ReleaseYear = None
Minutes = x.movie_time
if Minutes == "No Time":
Minutes = None
Rating = x.movie_rating
if Rating == "No Rating":
Rating = None
Genre = x.movie_genre
Directors = x.movie_directors
NumberOfDirectors = x.movie_number_of_directors
Stars = x.movie_stars
NumberOfStars = x.movie_number_of_stars
Budget = x.movie_budget
if Budget == "No Budget":
Budget = None
GrossProfitUSA = x.movie_gross_usa
if GrossProfitUSA == "No Gross":
GrossProfitUSA = None
OpeningWeekendUSA = x.movie_opening_weekend_usa
if OpeningWeekendUSA == "No Opening Weekend Usa":
OpeningWeekendUSA = None
CumulativeWorldwideGross = x.movie_worldwide_gross
if CumulativeWorldwideGross == "No Cumulative Worldwide Gross":
CumulativeWorldwideGross = None
insert = (None,Name,ReleaseYear,Minutes,Rating,Genre,Directors,NumberOfDirectors,Stars,NumberOfStars,Budget,GrossProfitUSA,OpeningWeekendUSA,CumulativeWorldwideGross)
statement = 'INSERT INTO Movies '
statement += 'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
cur.execute(statement, insert)
conn.commit()
conn.close()
update_movies_playing(theater_class_object)
#get the list of movies from theaters
def update_movies_playing(theater_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
MoviesPlaying= ""
M = []
MoviesShowing = theater_object.list_movies
theater_name = theater_object.theater_name
for x in MoviesShowing:
statement = '''
SELECT Movies.Id
FROM Movies
WHERE Movies.Name = "{}"
'''.format(x)
cur.execute(statement)
for y in cur:
id_ = str(y[0]) + ','
MoviesPlaying = MoviesPlaying + id_
#MoviesPlaying = MoviesPlaying + str(id_) + ","
#MoviesPlaying.append(str(id_))
M.append(MoviesPlaying[:-1])
update = (M)
statement = '''
UPDATE Theaters
SET MoviesPlaying=?
WHERE Name = '{}'
'''.format(theater_name)
cur.execute(statement,update)
conn.commit()
conn.close()
#init_db(DBNAME)
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
#plotly graphs:
#Type: Grouped Bar Chart
#Shows:movie budget compared to cumulative worldwide gross for movies playing at a selected theater
def budget_and_cumulativegross(theater_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
try:
theater_streetaddress = theater_object.street_address
theater_name = theater_object.theater_name
title = 'Movie Budget Compared to Cumulative Worldwide Gross for Movies Playing at {}'.format(theater_name)
budget = []
worldwide_gross = []
MoviesShowing = []
statement = '''
SELECT MoviesPlaying
FROM Theaters
WHERE Name = "{}" AND StreetAddress = "{}"
LIMIT 1
'''.format(theater_name,theater_streetaddress)
cur.execute(statement)
for x in cur:
movie_ids=x[0]
movie_ids=movie_ids.split(',')
print(movie_ids)
for x in movie_ids:
statement = '''
SELECT Budget,CumulativeWorldwideGross,Name
FROM Movies
WHERE Id = {}
'''.format(x)
cur.execute(statement)
for y in cur:
if y[0] == None and y[1]== None:
continue
elif y[0] == None or y[1]== None:
continue
else:
budget.append(y[0])
worldwide_gross.append(y[1])
MoviesShowing.append(y[2])
trace1 = go.Bar(
x = MoviesShowing,
y = budget,
name = 'Budget'
)
trace2 = go.Bar(
x = MoviesShowing,
y = worldwide_gross,
name = 'Cumulative Worldwide Gross'
)
data = [trace1,trace2]
layout = go.Layout(
title = title,
barmode = 'group',
yaxis=dict(title='Dollars'),
xaxis=dict(title='Movies Playing')
)
fig = go.Figure(data = data, layout= layout)
py.plot(fig, filename = 'Movie Budget Compared to Cumulative Worldwide Gross for Movies Playing')
except:
print("Data not available to make this chart")
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
# here =budget_and_cumulativegross(movies[0])
#Type: Bar Chart
#Shows: movie length in minutes for movies playing
def minutes_of_movies(theater_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
try:
theater_streetaddress = theater_object.street_address
theater_name = theater_object.theater_name
title = 'Movie Length (in Minutes) for Movies Playing at {}'.format(theater_name)
MoviesShowing = []
minutes = []
statement = '''
SELECT MoviesPlaying
FROM Theaters
WHERE Name = "{}" AND StreetAddress = "{}"
LIMIT 1
'''.format(theater_name,theater_streetaddress)
cur.execute(statement)
for x in cur:
movie_ids=x[0]
movie_ids=movie_ids.split(',')
for x in movie_ids:
statement = '''
SELECT Minutes,Name
FROM Movies
WHERE Id = {}
'''.format(x)
cur.execute(statement)
for y in cur:
if y[0] == None:
continue
else:
minutes.append(y[0])
MoviesShowing.append(y[1])
data = [go.Bar(x=MoviesShowing,y= minutes)]
layout = go.Layout(
title = title,
yaxis=dict(title='Length of Movie (Minutes)'),
xaxis = dict(title = "Movies Playing")
)
fig = go.Figure(data = data, layout= layout)
py.plot(fig, filename='Movie Time (Minutes)')
except:
print("Data not avaliable to make this chart")
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
# here =minutes_of_movies(movies[0])
#Type: Pie Chart
#Shows: a selected movies' percentage revenue that came from the U.S compared to the percentage that came from the rest of ther world.
def gross_usa_vs_cumulativegross(movie_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
try:
movie = movie_object.movie_name
title = "{}Movie: Revenue From U.S Compared to Revenue From the Rest of the World".format(movie)
statement = '''
SELECT GrossProfitUSA,CumulativeWorldwideGross
FROM Movies
WHERE Name = "{}"
'''.format(movie)
cur.execute(statement)
for y in cur:
if y[0] == None and y[1]== None:
continue
elif y[0] == None or y[1]== None:
continue
else:
#percent_us = y[1].split(',')/int(y[0].split(',').join()) #U.S percentage
world = y[1].split(',')
usa = y[0].split(',')
percent_us= int("".join(usa))/int("".join(world))
percent_world = 1 - percent_us
fig = {
'data': [{'labels': ["% Revenue From the United States", "% Revenue From the Rest of the World"],
'values': [percent_us, percent_world],
'type': 'pie'}],
'layout': {'title': title}
}
py.plot(fig)
except:
print("Data not avaliable to make this chart")
# init_db(DBNAME)
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
# here =gross_usa_vs_cumulativegross(mov[3])
#Type: Scatter Plot
#Shows: movie length (in minutes) compared to movie budget for movies playing
def time_budget(theater_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
try:
theater_streetaddress = theater_object.street_address
theater_name = theater_object.theater_name
title = 'Length of Movie (minutes) Compared to Movie Budget for Movies Playing at {}'.format(theater_name)
budget = []
minutes = []
MoviesShowing = []
statement = '''
SELECT MoviesPlaying
FROM Theaters
WHERE Name = "{}" AND StreetAddress = "{}"
LIMIT 1
'''.format(theater_name,theater_streetaddress)
cur.execute(statement)
for x in cur:
movie_ids=x[0]
movie_ids=movie_ids.split(',')
for x in movie_ids:
statement = '''
SELECT Budget,Minutes,Name
FROM Movies
WHERE Id = {}
'''.format(x)
cur.execute(statement)
for y in cur:
if y[0] == None and y[1]== None:
continue
elif y[0] == None or y[1]== None:
continue
else:
budget.append(y[0])
minutes.append(y[1])
MoviesShowing.append(y[2])
trace1 = go.Scatter(
x = MoviesShowing,
y = budget,
name = 'Budget'
)
trace2 = go.Scatter(
x = MoviesShowing,
y = minutes,
name = 'Time (minutes)',
yaxis='y2'
)
data = [trace1,trace2]
layout = go.Layout(
title = title,
yaxis=dict(
title='Dollars'
),
yaxis2=dict(
title='Length of Movie (Minutes)',
titlefont=dict(color='rgb(148, 103, 189)'),
tickfont=dict(color='rgb(148, 103, 189)'),
overlaying='y',
side='right'
),
xaxis=dict(title='Movies Playing')
)
fig = go.Figure(data = data, layout= layout)
py.plot(fig, filename = 'Length of Movie Compared to Movie Budget')
except:
print("Data not avaliable to make this chart")
# init_db(DBNAME)
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
# here =time_budget(movies[0])
#Type: Grouped Bar Chart
#Shows: Gross Profit Compared to Gross Profit During Opening Weekend in the USA for Movies Playing
def OpeningWeekendUSA_compared_GrossUSA(theater_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
try:
theater_streetaddress = theater_object.street_address
theater_name = theater_object.theater_name
title = 'Gross Profit Compared to Gross Profit During Opening Weekend in the USA for Movies Playing at {}'.format(theater_name)
openingweekend = []
gross = []
MoviesShowing = []
statement = '''
SELECT MoviesPlaying
FROM Theaters
WHERE Name = "{}" AND StreetAddress = "{}"
LIMIT 1
'''.format(theater_name,theater_streetaddress)
cur.execute(statement)
for x in cur:
movie_ids=x[0]
movie_ids=movie_ids.split(',')
for x in movie_ids:
statement = '''
SELECT GrossProfitUSA,OpeningWeekendUSA,Name
FROM Movies
WHERE Id = {}
'''.format(x)
cur.execute(statement)
for y in cur:
if y[0] == None and y[1]== None:
continue
elif y[0] == None or y[1]== None:
continue
else:
gross.append(y[0])
openingweekend.append(y[1])
MoviesShowing.append(y[2])
trace1 = go.Bar(
x = MoviesShowing,
y = openingweekend,
name = 'Opening Weekend USA'
)
trace2 = go.Bar(
x = MoviesShowing,
y = gross,
name = 'Gross Profit USA'
)
data = [trace1,trace2]
layout = go.Layout(
title = title,
barmode = 'group',
yaxis=dict(title='Dollars'),
xaxis=dict(title='Movies Playing')
)
fig = go.Figure(data = data, layout= layout)
py.plot(fig, filename = 'Gross Profit USA Compared to Opening Weekend USA')
except:
print("Data not avaliable to make this chart")
# init_db(DBNAME)
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
# here =OpeningWeekendUSA_compared_GrossUSA(movies[0])
# r=list_movietheaters("60022")
# i=movie_information(r[0])
# gross_usa_vs_cumulativegross(i[2])
#zip #
# theater #
# movie info #
#interactive part
def interactive():
print('Enter "help" at any point to see a list of valid commands')
response = input('Please type in the zipcode command (or "exit" to quit): ')
while response != 'exit':
split_response = response.split()
if split_response[0]== "zip" and len(split_response[1]) == 5:
try:
int(split_response[1])
result = list_movietheaters(split_response[1])
if len(result) == 0:
print("No theaters near the zip code entered.")
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
print("List of Theaters near {}: ".format(split_response[1]))
num = 0
dic_theaters = {}
length = len(result)
for t in result:
num += 1
string = t.__str__()
dic_theaters[num] = t
if length > 10:
if num == 11:
more_theaters = input("Would you like to see more theater options (type: 'yes' or 'no')?: ")
if more_theaters.lower() == 'yes':
print("{}. {}".format(num,string))
continue
else:
break
print("{}. {}".format(num,string))
except:
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
elif split_response[0] == "theater":
try:
if int(split_response[1]) not in dic_theaters.keys():
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
else:
for x in dic_theaters:
if int(split_response[1]) == x:
obj = dic_theaters[x]
results = movie_information(obj)
if len(results) == 0:
print("No movies showing for the theater you selected.")
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
dic_movies_playing = {}
num = 0
print("List of Movies Playing at {}: ".format(obj.theater_name))
for x in results:
num += 1
string = x.movie_name
dic_movies_playing[num]= x
print("{}. {}".format(num, string))
graph = input('Would you like to see a graph of movie budget compared to cumulative worldwide gross ("yes or "no")?: ')
graph2 = input('Would you like to see a graph of movie time ("yes or "no")?: ')
graph3 = input('Would you like to see a graph of movie budget compared to movie length ("yes or "no")?:')
graph5 = input('Would you like to see a graph of Gross Profit USA compared Opening Weekend USA ("yes or "no")?:')
if graph.lower() == "yes":
budget_and_cumulativegross(obj)
if graph2.lower() == "yes":
minutes_of_movies(obj)
if graph3.lower() == "yes":
time_budget(obj)
if graph5.lower() == "yes":
OpeningWeekendUSA_compared_GrossUSA(obj)
except:
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
#graph = input('Would you like to see a graph of movie budget compared to cumulative worldwide gross("yes or "no" )?: ')
elif split_response[0] == "movie" and split_response[1] == "info":
try:
if int(split_response[2]) not in dic_movies_playing.keys():
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
for x in dic_movies_playing:
if x == int(split_response[2]):
movie_obj = dic_movies_playing[x]
print(movie_obj)
graph4 = input('Would you like to see a graph that compares revenue from the U.S versus the rest of the world ("yes" or "no")?: ')
if graph4.lower() == "yes":
gross_usa_vs_cumulativegross(movie_obj)
except:
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
elif "help" == response:
print("\tzip <zipcode>")
print("\t\t available anytime")
print("\t\tlists all theaters between 5 and 30 miles away from the zipcode entered")
print("\t\tvalid inputs: a 5 digit zip code")
print("\ttheater <result_number>")
print("\t\tavailable only if there is an active result set (a list of theaters near a zipcode specified)")
print("\t\tlists all movies showing at the theater selected")
print("\t\tvalid inputs: an integer 1-len (result_set_size)")
print("\tmovie info <result_number>")
print("\t\tavailable only if there is an active result set (a list of movies showing at a specified theater)")
print("\t\tshows further information about the movie selected")
print("\t\tvalid inputs: an integer 1-len (result_set_size)")
print("\texit")
print("\t\texits the program")
print("\thelp")
print("\t\tlists available commands (these instructions)")
else:
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
response = input('Please type in a command (or "exit" to quit): ')
if response == "exit":
print("Goodbye!")
continue
# try:
# if response != "help":
# response = int(response)
# except:
# response = input('Please type in a valid command (or "help" for more options): ')
# if response == "exit":
# print("Goodbye!")
# continue
# if len(str(response)) == 5:
# result = list_movietheaters(response)
# print("List of Theaters near {}: ".format(response))
# num = 0
# dic_theaters = {}
# length = len(result)
# for t in result:
# num += 1
# string = t.__str__()
# dic_theaters[num] = t
# if length > 10:
# if num == 11:
# more_theaters = input("Would you like to see more theater options (type: 'yes' or 'no')?: ")
# if more_theaters.lower() == 'yes':
# print("{}. {}".format(num,string))
# continue
# else:
# break
# print("{}. {}".format(num,string))
# elif len(str(response)) < 5:
# if response not in dic_theaters.keys():
# response = input('Please type in a valid command (or "help" for more options): ')
# if response == "exit":
# print("Goodbye!")
# continue
# else:
# for x in dic_theaters:
# if response == x:
# obj = dic_theaters[x]
# results = movie_information(obj)
# dic_movies_playing = {}
# num = 0
# print("List of Movies Playing at {}: ".format(obj.theater_name))
# for x in results:
# num += 1
# string = x.movie_name
# dic_movies_playing[num]= x
# print("{}. {}".format(num, string))
# if int(response) not in dic_movies_playing.keys():
# response = input('Please type in a valid command (or "help" for more options): ')
# if response == "exit":
# print("Goodbye!")
# continue
# for x in dic_movies_playing:
# if x == int(response):
# movie_obj = dic_movies_playing[x]
# print(movie_obj)
# response = input('Type in a number to see more information about a movie (or help for more options): ')
# try:
# int(response)
# except:
# if response == "exit":
# print("Goodbye!")
# continue
# else:
# response = input('Please type in a valid command (or "help" for more options): ')
# if response == "exit":
# print("Goodbye!")
# continue
#response = input('Please type in a zipcode (or exit to escape): ')
#commands:
#zip <type zip code>
#theater <type number>
#movie <type number>
# if response == "exit":
# print("Goodbye!")
# continue
# elif response == "help":
# continue
# elif len(str(response)) == 5:
# continue
# elif type(response) == type(""):
# try:
# response = int(response)
# except:
# response input('Please enter a valid command (or "help" for more options): ')
# continue
# try:
# response = int(response)
# except:
# response = input('Please enter a valid zipcode (or exit to escape): ')
# if response == "exit":
# print("Goodbye!")
# continue
# if response == 'help':
# response = input('Enter a command: ')
# continue
# pass
# if
#table 1: theaters
#table 2: movies
#theaters column movies contain a string ('1,2,3,4,5,6,7,')
#theaters playing this list of movies
#str.split(',') get movie info for all those
#movies tables do need any information on what movies are playing
#movies can delete everytime it runs keep the theater cache
#print theaters near zipcode
#then they pick a theater number and tells the movies
#they can pick a movie number and it tells the movies
#pie chart showing the ratings for the movie
#release month (how long specific movies are in theaters) --> time line graph (or you can do gross sales ---> distribution of gross sales per movie per theater)
#-------------------------------------------------------
#table 1:movies
#join on movie titles or movie directors
#table 2: theaters and zip codes column for list of movies
#theaters table: id, zip code, address, movies list
#just keep adding them to the database
#can just use the cache data
#tables all the movie information
#join on the movies playing at that theater
#movie theaters id
#table 1: theaters, autoincriment unique id
#cant multiple theaters show the same movie
#movies: column with theater id
#movie id as a foreign key in the theater table
#beautiful soup documentation
#interactive part
if __name__ == '__main__':
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
init_db(DBNAME)
interactive()
#result=list_movietheaters("60022")
#b = budget_and_cumulativegross(result[0])
#print(b)
# user = input("Enter a zipcode in the United States: ")
# while user != "exit":
|
46b164ad9c3a01ee945fee69cd8ec8676fc2f154 | vthomas1908/yahtzee | /functions.py | 4,616 | 3.828125 | 4 | # Copyright (c) 2014 Thomas Van Klaveren
# create the function for Yahtzee game. This will evaluate dice and
# determine the points eligible for the score card item selected
#function checks the values of dice and returns a list containing the numbers
#of same valued dice (ie dice 6,2,6,6,2 would return [3,2])
def same_val_check(dice_list):
d = {}
l = []
for i in dice_list:
if i not in d:
d[i] = 1
else:
d[i] += 1
for i in d:
if d[i] not in l:
l.append(d[i])
return l
#function adds sum of dice values and returns that value
def dice_sum(dice_list):
x = 0
for i in dice_list:
x += i
return x
# tried to write this function as a module to import into my main file,
# however, tkinter needed this to be in the class where it was called from
# the radiobutton command
"""
def give_val(dice_results, score_card, dictionary, item):
val = 0
dice_vals = same_val_check(dice_results)
if score_card.get() == "ones":
for i in dice_results:
if i == 1:
val += 1
dictionary["ones"] = val
dictionary["total1"] += val
dictionary["total_score"] += val
item.configure(text = dictionary["ones"])
elif score_card.get() == "twos":
for i in dice_results:
if i == 2:
val += 1
dictionary["twos"] = val
dictionary["total1"] += val
dictionary["total_score"] += val
elif score_card.get() == "threes":
for i in dice_results:
if i == 3:
val += 1
dictionary["threes"] = val
dictionary["total1"] += val
dictionary["total_score"] += val
elif score_card.get() == "fours":
for i in dice_results:
if i == 4:
val += 1
dictionary["fours"] = val
dictionary["total1"] += val
dictionary["total_score"] += val
elif score_card.get() == "fives":
for i in dice_results:
if i == 5:
val += 1
dictionary["fives"] = val
dictionary["total1"] += val
dictionary["total_score"] += val
elif score_card.get() == "sixes":
for i in dice_results:
if i == 6:
val += 1
dictionary["sixes"] = val
dictionary["total1"] += val
dictionary["total_score"] += val
elif score_card.get() == "three kind":
for i in range(3,6):
if i in dice_vals:
val = dice_sum(dice_list)
break
dictionary["three_kind"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
elif score_card.get() == "four kind":
for i in range(4,6):
if i in dice_vals:
val = dice_sum(dice_list)
break
dictionary["four_kind"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
elif score_card.get() == "full house":
if 3 in dice_vals and 2 in dice_vals:
val = 25
elif 5 in dice_vals:
val = 25
dictionary["full_house"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
elif score_card.get() == "sm straight":
for i in range(1,7):
if [i, i+1, i+2, i+3] <= sort(dice_results):
val = 30
elif 5 in dice_vals:
val = 30
dictionary["sm_straight"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
elif score_card.get() == "lg straight":
for i in range(1,7):
if [i, i+1, i+2, i+3, i+4] <= sort(dice_results):
val = 40
elif 5 in dice_vals:
val = 40
dictionary["lg_straight"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
elif score_card.get() == "chance":
val = dice_sum(dice_listi)
dictionary["chance"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
elif score_card.get() == "yahtzee":
dice_vals = same_val_check(dice_results)
if 5 in dice_vals:
val = 50
dictionary["yahtzee"] = val
dictionary["total2"] += val
dictionary["total_score"] += val
if dictionary["ones"] + dictionary["twos"] + dictionary["threes"] + \
dictionary["fours"] + dictionary["fives"] + dictionary["sixes"] > 62:
dictionary["bonus"] = 35
dictionary["total1"] += 35
"""
|
96720afe434563414e5a8167964e4759a4696186 | tadteo/nnn | /src/utils.py | 835 | 3.53125 | 4 | #select the best two individuals
def select_best_two(population):
if population[0].score >= population[1].score:
mx=population[0].score
best = population[0]
second_best_value = population[1].score
second_best = population[1]
else:
mx=population[1].score
best = population[1]
second_best_value = population[0].score
second_best = population[0]
for i in range(2,len(population)):
if population[i].score>mx:
second_best_value = mx
second_best = best
mx=population[i].score
best=population[i]
elif population[i].score>second_best_value and mx != population[i].score:
second_best_value=population[i].score
second_best=population[i]
return best, second_best
|
3bcd2fad9fbb8028a7b92da712c3c3f5f13c3f84 | spoofdoof/2018 | /SP/assign3/decrypt.py | 2,302 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import string
from collections import defaultdict, Counter
def read_file(filename):
with open(filename) as lines:
for line in lines:
yield line.strip().decode('hex')
def xor_combinations(data):
"""
Returns all posible combinations of XORs between data entries
TODO: use numpy arrays
>>> list(xor_combinations(["AAA","AAA"]))
[('AAA', 'AAA', '\x00\x00\x00')]
>>> list(xor_combinations(["AAA","BBB", "CCCC"]))
[('AAA', 'BBB', '\x03\x03\x03'), ('AAA', 'CCCC', '\x02\x02\x02'), ('BBB', 'CCCC', '\x01\x01\x01')]
"""
import itertools
for ct1, ct2 in itertools.combinations(data,2):
xorred = []
for char1, char2 in zip(ct1, ct2):
xorred.append(chr(ord(char1) ^ ord(char2)))
yield ct1, ct2, "".join(xorred)
def statistics(data):
"""Returns list of possible values for each byte of key"""
possibilities = defaultdict(list)
for ct1, ct2, xorred in data:
for (i, char) in enumerate(xorred):
# The unlimate hint was given at Question itself:
# Hint: XOR the ciphertexts together, and consider what happens when a space is XORed with a character in [a-zA-Z].
if char in string.letters:
possibilities[i].extend([ord(ct1[i])^32, ord(ct2[i])^32])
return possibilities
def guess_key(possibilities):
"""
Simplest heuristics ever - just return most common value for each dict key
XXX: sic! Because of that output is not 100% correct. We should take into
an account english letter distribution.
"""
return "".join(chr(Counter(item).most_common(1)[0][0]) for item in possibilities.values())
if __name__ == '__main__':
import logging
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", type="string", dest="file", default="ciphertexts.txt")
(options, args) = parser.parse_args()
data = list(read_file(options.file))
possibilities = statistics(xor_combinations(data))
key = guess_key(possibilities)
logging.warn("Possible key: {0}".format(key.encode('hex')))
from encrypt import strxor
for target in data:
logging.warning("Partially recovered data: {0}".format(strxor(target, key)))
|
e7caaeace5bfd268d90db767c2d8df6d1539fca6 | JuDePom/algooo | /lda/prettyprinter.py | 2,077 | 3.9375 | 4 | class PrettyPrinter:
"""
Facilitates the making of a properly-indented file.
"""
# must be defined by subclasses
export_method_name = None
def __init__(self):
self.indent = 0
self.strings = []
self.already_indented = False
def put(self, *items):
"""
Append items to the source code at the current indentation level.
If an item is a string, append it right away; otherwise, invoke
`item.<export_method_name>(self)`.
"""
for i in items:
if type(i) is str:
if not self.already_indented:
self.strings.append('\t' * self.indent)
self.already_indented = True
self.strings.append(i)
else:
getattr(i, self.export_method_name)(self)
def indented(self, exportfunc, *args):
"""
Append items to the source code at an increased indentation level.
:param exportfunc: export function. Typically put, putline, or join.
:param args: arguments passed to exportfunc
"""
self.indent += 1
exportfunc(*args)
self.indent -= 1
def newline(self, count=1):
"""
Append line breaks to the source code.
:param count: optional number of line breaks (default: 1)
"""
self.strings.append(count*'\n')
self.already_indented = False
def putline(self, *items):
"""
Append items to the source code, followed by a line break.
"""
self.put(*items)
self.newline()
def join(self, iterable, gluefunc, *args):
"""
Concatenate the elements in the iterable and append them to the source
code. A 'glue' function (typically put()) is called between each
element. Note: This method is similar in purpose to str.join().
:param gluefunc: glue function called between each element
:param args: arguments passed to gluefunc
"""
it = iter(iterable)
try:
self.put(next(it))
except StopIteration:
return
for element in it:
gluefunc(*args)
self.put(element)
def __repr__(self):
"""
Return the source code built so far.
"""
return ''.join(self.strings)
class LDAPrettyPrinter(PrettyPrinter):
export_method_name = "lda"
class JSPrettyPrinter(PrettyPrinter):
export_method_name = "js"
|
5ecae8a199ce0b5e87bb6d57f4386a5c8ba29d31 | Riableo/analisis | /Ejercicios/insercion.py | 396 | 3.921875 | 4 | def Insercion(Vector):
for i in range(1,len(Vector)):
actual = Vector[i]
j = i
#Desplazamiento de los elementos de la matriz }
while j>0 and Vector[j-1]>actual:
Vector[j]=Vector[j-1]
j = j-1
#insertar el elemento en su lugar
Vector[j]=actual
return(Vector)
te = [8, 1, 3, 2]
print(Insercion(te))
|
63d77f48f26c15c1d060ba2f50b82386016a6389 | Riableo/analisis | /Ejercicios/Multiplos.py | 367 | 3.890625 | 4 | tr=0
while tr == 0:
try:
Num=int(input("Ingresar numero: "))
Num_I=int(input("Ingresar numero: "))
N=Num%Num_I
N1=Num_I%Num
if N == 0 or N1 == 0:
print("Sao Multiplos")
else:
print("Nao sao Multiplos")
except ValueError:
print("Solo números por favor")
tr=int(input("Volver a realizar diferencia \n 0: sí !0:No: "))
|
331a82a167fd30e270ec8db699145caba71a80d3 | skyhuge/python-demo | /muti_params.py | 1,204 | 4.0625 | 4 | def calc(nums):
sum = 0
for n in nums:
sum += n
return sum
# 可变参数
def add_nums(*nums):
sum = 0
for n in nums:
sum += n
return sum
# 关键字参数
def print_nums(name, age, **kw):
# kw.clear() # 对kw的操作不会改变extra的值
print('name is %s , age is %s , other is %s' % (name, age, kw))
# 命名关键字参数
def print_info(name, age, *args, addr, job):
print('name is %s , age is %s , addr is %s , job is %s ' % (name, age, addr, job))
print('* is ', args) # args 其实是一个只有一个元素的tuple
# 参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数
def example(a, b=1, *, c, d, **kw):
print(a, b, c, d, kw)
def exam(*args, **kw):
print(args.__add__((6,)), kw)
if __name__ == '__main__':
l = [1, 2, 4, 3, 5]
print(calc(l))
print(add_nums(*l))
extra = {'job': 'Engineer', 'address': 'Shanghai'}
print_nums('ashin', 24, gender='male')
print_nums('ashin', 24, **extra)
print_info('ashin', 24, extra, addr='China', job='Engineer')
example('hello', c='adc', d='world', **extra)
exam(*l, **extra)
|
f19d3a39693428d4ff85fc65e8cdc734c1b8f5d0 | 6Kwecky6/PyForProggers | /Lecture4/TimeTableDraw.py | 1,224 | 4.0625 | 4 | import turtle
import math
step = 0
def drawCircle(rad, num_points, pen):
# placing the circle down by rad to make the center of it origo
pen.up()
pen.goto(0,-rad)
pen.down()
# Drawing the circle
pen.circle(rad)
pen.up()
#Moves along the circle to yield points
for it in range(num_points):
yield [math.sin(step*it)*rad,math.cos(step*it)*rad] #This yields each point
def drawLine(rad,num_points,cur_point,multiplic,x_pos,y_pos,pen):
to_pos = [math.sin(step*(cur_point*multiplic%num_points))*rad,math.cos(step*(cur_point*multiplic%num_points))*rad]
pen.goto(x_pos,y_pos)
pen.down()
pen.goto(to_pos[0],to_pos[1])
pen.up()
def main():
pen = turtle.Turtle()
num_points = 300
rad = 200
multiplic = 4
window = turtle.Screen()
global step # This is the length between each point on the circle
step = (math.pi * 2) / num_points
pen.speed(10)
#Draws the circle
points = drawCircle(rad,num_points, pen)
# Draws each line
for it in range(num_points):
to_pos = next(points)
drawLine(rad,num_points,it, multiplic,to_pos[0],to_pos[1],pen)
window.exitonclick()
if __name__ == '__main__':
main() |
eac82a0b61c8bee65c15b3078150af5f711c45d5 | pinpin3152/python | /Assignment_cointoss.py | 837 | 3.78125 | 4 | import random
def coin(toss):
if toss == 0:
return "head"
else:
return "tail"
head = 0
tail = 0
i = 1
while i < 5001:
X = random.randint(0,1)
if X == 0:
head += 1
else:
tail += 1
print "Attempt #" + str(i) + ": Throwing a coin... It's a " + coin(X) + "! ... Got " + str(head) + " head(s) so far and " + str(tail) + " tail(s) so far"
i += 1
'''
#answer sheet solution
import random
import math
print 'Starting the program'
head_count = 0
tail_count = 0
for i in range(1,5001):
rand = round(random.random())
if rand == 0:
face = 'tail'
tail_count += 1
else:
face = 'head'
head_count += 1
print "Attempt #"+str(i)+": Throwing a coin...It's a "+face+"!...Got "+str(head_count)+" head(s) and "+str(tail_count)+" tail(s) so far"
print 'Ending the program, thank you!'
''' |
63a21b76e45777b7fa2b333df3bf46b56920c304 | Tornike-Skhulukhia/Principles-of-data-science-book-working-files | /scripts/chapter 10/point_estimates.py | 1,168 | 3.625 | 4 | from import_helpers import (
np,
pd,
plt,
)
from scipy import stats
from scipy.stats import poisson
# why do they use loc > 0 in the book???
long_breaks = poisson.rvs(loc=0, mu=60, size=3000)
short_breaks = poisson.rvs(loc=0, mu=15, size=6000)
breaks = np.concatenate([long_breaks, short_breaks])
# pd.Series(breaks).hist()
parameter = np.mean(breaks)
if __name__ == '__main__':
print(f'Population parameter - Mean = {parameter:.3f}')
sample_breaks = np.random.choice(breaks, size=100)
print(f'Point estimate - Mean based on sample = {np.mean(sample_breaks):.3f}')
# calculate more samples
point_estimates = [np.mean(np.random.choice(breaks, 100)) for _ in range(500)]
estimates_mean = np.mean(point_estimates)
print(f'Mean of 500 point estimates = {estimates_mean:.3f}')
print(f'Difference from parameter {estimates_mean - parameter:.3f} ({(estimates_mean - parameter) / parameter * 100:.3f}%)')
plt.title('Distribution of 500 point estimate means')
pd.Series(point_estimates).hist(bins=50)
plt.show()
|
f4034f05130cfa6c9d6f1af443f1651da5534e28 | stoicswe/CSCI315A-BigData | /HW6_NathanBunch/Boltzman Machine Example/rbm.py | 14,152 | 3.828125 | 4 | from __future__ import print_function
import numpy as np
class RBM:
def __init__(self, num_visible, num_hidden):
self.num_hidden = num_hidden
self.num_visible = num_visible
self.debug_print = True
# Initialize a weight matrix, of dimensions (num_visible x num_hidden), using
# a uniform distribution between -sqrt(6. / (num_hidden + num_visible))
# and sqrt(6. / (num_hidden + num_visible)). One could vary the
# standard deviation by multiplying the interval with appropriate value.
# Here we initialize the weights with mean 0 and standard deviation 0.1.
# Reference: Understanding the difficulty of training deep feedforward
# neural networks by Xavier Glorot and Yoshua Bengio
np_rng = np.random.RandomState(1234)
self.weights = np.asarray(np_rng.uniform(
low=-0.1 * np.sqrt(6. / (num_hidden + num_visible)),
high=0.1 * np.sqrt(6. / (num_hidden + num_visible)),
size=(num_visible, num_hidden)))
print(self.weights)
# Insert weights for the bias units into the first row and first column.
self.weights = np.insert(self.weights, 0, 0, axis = 0)
self.weights = np.insert(self.weights, 0, 0, axis = 1)
print(self.weights)
def train(self, data, max_epochs = 1000, learning_rate = 0.1):
"""
Train the machine.
Parameters
----------
data: A matrix where each row is a training example consisting of the states of visible units.
"""
num_examples = data.shape[0]
#print(data)
#print(num_examples)
# Insert bias units of 1 into the first column.
# here is when the intercept is added
# y = ax + b*1
# that is why 1 is added, since it describes the bias
data = np.insert(data, 0, 1, axis = 1) # intercept like sciklit learn is added into the weights
#print(data)
for epoch in range(max_epochs):
# Clamp to the data and sample from the hidden units.
# (This is the "positive CD phase", aka the reality phase.)
#print("DATA")
#print(data)
pos_hidden_activations = np.dot(data, self.weights)
#print("POS HIDDEN ACTIVATIONS")
#print(pos_hidden_activations)
#print(pos_hidden_activations)
pos_hidden_probs = self._logistic(pos_hidden_activations)
#print("POS HIDDEN PROBS")
#print(pos_hidden_probs)
#print(pos_hidden_probs)
pos_hidden_probs[:,0] = 1 # Fix the bias unit.
#print("POS HIDDEN PROBS FIX")
#print(pos_hidden_probs)
#print(pos_hidden_probs)
pos_hidden_states = pos_hidden_probs > np.random.rand(num_examples, self.num_hidden + 1)
#print("POS HIDDEN STATES")
#print(pos_hidden_states)
#print(">>>>>>>>>>>>>>>>>>>>>>")
#print(pos_hidden_states)
# Note that we're using the activation *probabilities* of the hidden states, not the hidden states
# themselves, when computing associations. We could also use the states; see section 3 of Hinton's
# "A Practical Guide to Training Restricted Boltzmann Machines" for more.
pos_associations = np.dot(data.T, pos_hidden_probs)
#print("POS ASSOCIATIONS")
#print(pos_associations)
#print(pos_associations)
# Reconstruct the visible units and sample again from the hidden units.
# (This is the "negative CD phase", aka the daydreaming phase.)
neg_visible_activations = np.dot(pos_hidden_states, self.weights.T)
# print("NEG VISIBLE ACTIVATIONS")
#print(neg_visible_activations)
#print(neg_visible_activations)
neg_visible_probs = self._logistic(neg_visible_activations)
# print("NEG VISIBLE PROBS LOGISTICS")
#print(neg_visible_probs)
#print(neg_visible_probs)
neg_visible_probs[:,0] = 1 # Fix the bias unit.
# print("NEG VISIBLE PROBS FIX")
# print(neg_visible_probs)
#print(neg_visible_probs)
neg_hidden_activations = np.dot(neg_visible_probs, self.weights)
# print("NEG HIDDEN ACTIVATIONS")
# print(neg_hidden_activations)
#print(neg_hidden_activations)
neg_hidden_probs = self._logistic(neg_hidden_activations)
# print("NEG HIDDEN PROBS LOGISTICS")
# print(neg_hidden_probs)
#print(neg_hidden_probs)
# Note, again, that we're using the activation *probabilities* when computing associations, not the states
# themselves.
neg_associations = np.dot(neg_visible_probs.T, neg_hidden_probs)
# print("NEG ASSOCIATIONS")
# print(neg_associations)
#print(neg_associations)
# Update weights.
self.weights += learning_rate * ((pos_associations - neg_associations) / num_examples)
# print("WEIGHT UPDATE")
# print(self.weights)
#print(self.weights)
error = np.sum((data - neg_visible_probs) ** 2)
#print(error)
if self.debug_print:
print("Epoch %s: error is %s" % (epoch, error))
def run_visible(self, data):
"""
Assuming the RBM has been trained (so that weights for the network have been learned),
run the network on a set of visible units, to get a sample of the hidden units.
Parameters
----------
data: A matrix where each row consists of the states of the visible units.
Returns
-------
hidden_states: A matrix where each row consists of the hidden units activated from the visible
units in the data matrix passed in.
"""
num_examples = data.shape[0]
# Create a matrix, where each row is to be the hidden units (plus a bias unit)
# sampled from a training example.
hidden_states = np.ones((num_examples, self.num_hidden + 1))
# Insert bias units of 1 into the first column of data.
data = np.insert(data, 0, 1, axis = 1)
# Calculate the activations of the hidden units.
hidden_activations = np.dot(data, self.weights)
# Calculate the probabilities of turning the hidden units on.
hidden_probs = self._logistic(hidden_activations)
# Turn the hidden units on with their specified probabilities.
hidden_states[:,:] = hidden_probs > np.random.rand(num_examples, self.num_hidden + 1)
# Always fix the bias unit to 1.
# hidden_states[:,0] = 1
# Ignore the bias units.
hidden_states = hidden_states[:,1:]
return hidden_states
# TODO: Remove the code duplication between this method and `run_visible`?
def run_hidden(self, data):
"""
Assuming the RBM has been trained (so that weights for the network have been learned),
run the network on a set of hidden units, to get a sample of the visible units.
Parameters
----------
data: A matrix where each row consists of the states of the hidden units.
Returns
-------
visible_states: A matrix where each row consists of the visible units activated from the hidden
units in the data matrix passed in.
"""
num_examples = data.shape[0]
# Create a matrix, where each row is to be the visible units (plus a bias unit)
# sampled from a training example.
visible_states = np.ones((num_examples, self.num_visible + 1))
# Insert bias units of 1 into the first column of data.
data = np.insert(data, 0, 1, axis = 1)
# Calculate the activations of the visible units.
visible_activations = np.dot(data, self.weights.T)
# Calculate the probabilities of turning the visible units on.
visible_probs = self._logistic(visible_activations)
# Turn the visible units on with their specified probabilities.
visible_states[:,:] = visible_probs > np.random.rand(num_examples, self.num_visible + 1)
# Always fix the bias unit to 1.
# visible_states[:,0] = 1
# Ignore the bias units.
visible_states = visible_states[:,1:]
return visible_states
def daydream(self, num_samples):
"""
Randomly initialize the visible units once, and start running alternating Gibbs sampling steps
(where each step consists of updating all the hidden units, and then updating all of the visible units),
taking a sample of the visible units at each step.
Note that we only initialize the network *once*, so these samples are correlated.
Returns
-------
samples: A matrix, where each row is a sample of the visible units produced while the network was
daydreaming.
"""
# Create a matrix, where each row is to be a sample of of the visible units
# (with an extra bias unit), initialized to all ones.
samples = np.ones((num_samples, self.num_visible + 1))
# Take the first sample from a uniform distribution.
samples[0,1:] = np.random.rand(self.num_visible)
# Start the alternating Gibbs sampling.
# Note that we keep the hidden units binary states, but leave the
# visible units as real probabilities. See section 3 of Hinton's
# "A Practical Guide to Training Restricted Boltzmann Machines"
# for more on why.
for i in range(1, num_samples):
visible = samples[i-1,:]
# Calculate the activations of the hidden units.
hidden_activations = np.dot(visible, self.weights)
# Calculate the probabilities of turning the hidden units on.
hidden_probs = self._logistic(hidden_activations)
# Turn the hidden units on with their specified probabilities.
hidden_states = hidden_probs > np.random.rand(self.num_hidden + 1)
# Always fix the bias unit to 1.
hidden_states[0] = 1
# Recalculate the probabilities that the visible units are on.
visible_activations = np.dot(hidden_states, self.weights.T)
visible_probs = self._logistic(visible_activations)
visible_states = visible_probs > np.random.rand(self.num_visible + 1)
samples[i,:] = visible_states
# Ignore the bias units (the first column), since they're always set to 1.
return samples[:,1:]
def _logistic(self, x):
return 1.0 / (1 + np.exp(-x))
# Nathan's definitions that have been added
# weights in the sciklit learn is known as components and here it is weights
# create the collowing:
#def fit(self, data, y=None):
# #fix the way the weights are generated....its incorrect size
# n_samples = data.shape[0]
# vis = data.shape[1]
# hid = data.shape[0] * data.shape[1]
# np_rng = np.random.RandomState(1234)
# self.weights = np.asarray(np_rng.uniform(low=-0.1 * np.sqrt(6. / (hid + vis)), high=0.1 * np.sqrt(6. / (hid + vis)),size=(vis, hid)))
# self.weights = np.insert(self.weights, 0, 0, axis = 0)
# self.weights = np.insert(self.weights, 0, 0, axis = 1)
# n_batches = int(np.ceil(float(n_samples) / 4))
#batch_slices = list(gen_even_slices(n_batches * 4,n_batches, n_samples))
# batch_slices = list(data[0:n_batches*4:n_batches])
# for iteration in range(1, 5000 + 1):
# for batch_slice in batch_slices:
# #self._fit(X[batch_slice])
# self._fit(data[batch_slice])
# print("Iteration %d, pseudo-likelihood = %.2f" % (iteration, self.score_samples(X).mean()))
#idk why but this is an error
#def _fit(self, data):
#h_pos = self._mean_hiddens(v_pos)
# v_neg = self._sample_visibles(self.h_samples_, rng)
# h_neg = self._mean_hiddens(v_neg)
# lr = float(self.learning_rate) / v_pos.shape[0]
# update = safe_sparse_dot(v_pos.T, h_pos, dense_output=True).T
# update -= np.dot(h_neg.T, v_neg)
# self.components_ += lr * update
# self.intercept_hidden_ += lr * (h_pos.sum(axis=0) - h_neg.sum(axis=0))
# self.intercept_visible_ += lr * (np.asarray(
# v_pos.sum(axis=0)).squeeze() -
# v_neg.sum(axis=0))
# h_neg[rng.uniform(size=h_neg.shape) < h_neg] = 1.0 # sample binomial
# self.h_samples_ = np.floor(h_neg, h_neg)
#pos_hidden_activations = np.dot(data, self.weights)
#pos_hidden_probs = self._logistic(pos_hidden_activations)
#pos_hidden_probs[:,0] = 1 # Fix the bias unit.
#pos_hidden_states = pos_hidden_probs > np.random.rand(num_examples, self.num_hidden + 1)
# Note that we're using the activation *probabilities* of the hidden states, not the hidden states
# themselves, when computing associations. We could also use the states; see section 3 of Hinton's
# "A Practical Guide to Training Restricted Boltzmann Machines" for more.
#pos_associations = np.dot(data.T, pos_hidden_probs)
# Reconstruct the visible units and sample again from the hidden units.
# (This is the "negative CD phase", aka the daydreaming phase.)
#neg_visible_activations = np.dot(pos_hidden_states, self.weights.T)
#neg_visible_probs = self._logistic(neg_visible_activations)
#neg_visible_probs[:,0] = 1 # Fix the bias unit.
#neg_hidden_activations = np.dot(neg_visible_probs, self.weights)
#neg_hidden_probs = self._logistic(neg_hidden_activations)
# Note, again, that we're using the activation *probabilities* when computing associations, not the states
# themselves.
#neg_associations = np.dot(neg_visible_probs.T, neg_hidden_probs)
# Update weights.
#self.weights += learning_rate * ((pos_associations - neg_associations) / num_examples)
#error = np.sum((data - neg_visible_probs) ** 2)
#if self.debug_print:
# print("Fit Iteration %s: error is %s" % (epoch, error))
#def score_samples():
if __name__ == '__main__':
r = RBM(num_visible = 6, num_hidden = 2)
training_data = np.array([[1,1,1,0,0,0],[1,0,1,0,0,0],[1,1,1,0,0,0],[0,0,1,1,1,0], [0,0,1,1,0,0],[0,0,1,1,1,0]])
#r.train(training_data, max_epochs = 5000) #default
r.train(training_data, max_epochs = 5000)
#r.fit(training_data)
print("Weights:")
print(r.weights)
print()
user = np.array([[0,0,0,1,1,0]])
print("Get the category preference:")
print(r.run_visible(user))
print()
userPref = np.array([[1,0]])
print("Get the movie preference:")
print(r.run_hidden(userPref))
print()
print("Daydream for (5):")
movieWatch = r.daydream(5)
print(movieWatch)
#print(movieWatch[:,3])
#print("Get daydream category preferences:")
#print(r.run_visible(np.array(movieWatch[:,2]))) |
ff66222e7d4764345f053a966e2b0cd81255667f | adhed/shortest-path | /shortest_path.py | 1,002 | 4.0625 | 4 | from point import Point
from algorithm import Algorithm
def ask_for_points():
points = []
points_counter = int(input("Podaj proszę liczbę punktów jaką będziesz chciał przeliczyć: "))
for idx in range(points_counter):
x = int(input("Podaj współrzędną X dla punktu nr {0}: ".format(idx+1)))
y = int(input("Podaj współrzędną Y dla punktu nr {0}: ".format(idx+1)))
point = Point(idx+1, x, y)
points.append(point)
return points
def ask_for_starting_point():
try:
starting_point = int(input("Podaj numer punktu startowego: "))
except:
print("Czy aby na pewno podałeś numer?")
return starting_point
def main():
print("Witaj w algorytmie przeliczania najkrótszej ścieżki!")
points = ask_for_points()
starting_point_number = ask_for_starting_point()
algorithm = Algorithm(points, starting_point_number)
algorithm.calculate_shortest_path()
if __name__ == "__main__":
main() |
0e69f61ef23bc9b2dc698670ed063a51fe8fb2c1 | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codeforces/653_div_3/b.py | 1,358 | 3.546875 | 4 | from sys import stdin
from collections import defaultdict as dd
from collections import deque as dq
import itertools as it
from math import sqrt, log, log2
from fractions import Fraction
t = int(input())
for _ in range(t):
n = int(input())
nummoves = 0
flag = 0
while n!=1:
if n%3!=0:
flag = 1
break
if n%6 == 0:
n //= 6
else:
n*=2
nummoves += 1
if flag: print(-1)
else: print(nummoves)
## Intended solution
# If the number consists of other primes than 2 and 3 then the answer is -1. Otherwise, let cnt2 be the number of twos in the factorization of n and cnt3 be the number of threes in the factorization of n. If cnt2>cnt3 then the answer is -1 because we can't get rid of all twos. Otherwise, the answer is (cnt3−cnt2)+cnt3.
def editorial():
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
count3 = 0
while n % 3 == 0:
n //= 3
count3 += 1
count2 = 0
while n % 2 == 0:
n //= 2
count2 += 1
if n != 1 or count2 > count3:
print(-1)
continue
print(count3 + (count3 - count2))
|
9336374508ea58e1706637d9d20636ab94d08b4c | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codeforces/644 Div 3/C.py | 1,094 | 3.96875 | 4 | # A pair (x, y) is similar if they have same parity, i.e., x%2 == y%2 OR they are consecutive |x-y| = 1
t = int(input())
for _ in range(t):
# n is even (given in question, also a requirement to form pairs)
n = int(input())
arr = list(map(int, input().split()))
# There are only two cases: no.of even (and odd) pairs is even OR no.of even (and odd) pairs is odd. [n is even]
even_pair_count = 0
for num in arr:
if num%2 == 0: even_pair_count += 1
if even_pair_count%2==0: # there are even no. of even pairs and odd pairs
print('YES')
continue
else:
# both (even and odd pairs) are odd.
# If we can find a SINGLE |x-y| consecutive number pair (one will be even, other odd because consecutive), we can exclude (x, y) from the array. This leaves us with even no. of (even and odd) pairs.
arr.sort()
ans = 'NO'
for i in range(1, n):
if arr[i] - arr[i-1] == 1:
ans = 'YES'
break
print(ans)
|
fad5fe4ca3e87197c4d7204999ed5fef4f81220a | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codechef/ANSLEAK.py | 439 | 3.59375 | 4 | from collections import Counter
def get_most_frequent(solns):
return Counter(solns).most_common()[0][0]
if __name__ == "__main__":
T = int(input())
for _ in range(T):
ans = []
n, m, k = list(map(int, input().split()))
for _ in range(n):
solns = list(map(int, input().split()))
ans.append(get_most_frequent(solns))
print(' '.join([str(i) for i in ans]))
|
9e364b774c5ccd44d3897cd98983a4d7bf072cd7 | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Atcoder/172/d.py | 1,294 | 3.828125 | 4 | n = int(input())
# Check out atcoder editorial for this, beautifully explained. Same as geothermal's but it also shows how this idea was thought
# https://img.atcoder.jp/abc172/editorial.pdf
def sieve(n):
# 1.9 seconds.
# 1 and n are divisors for every n.
is_prime = [2]*(n + 1)
is_prime[0], is_prime[1] = 0, 0
# is_prime holds the number of positive divisors of N. Instead of being a bool of 0/1 for prime/not prime. for example of N=24---> is_prime[24] = 6 (1, 2, 3, 4, 6 ,24)
for num in range(2, n+1//2):
for mult in range(2*num, n+1, num):
is_prime[mult] += 1
ans = 1
# i is N. elem is f(N)
for i, elem in enumerate(is_prime[2:]):
ans += (elem)*(i + 2)
print(ans)
def geothermal(n):
# Source: https://codeforces.com/blog/entry/79438
# Let's reframe the problem by considering the total contribution each divisor makes to the answer. For any given i, i contributes K to the sum for each K from 1 to N such that K is a multiple of i.
ans = 0
for i in range(1, n+1):
mult = n//i
ans += (mult*(mult + 1)*i)//2
print(ans)
# O(N) solution; 170ms
geothermal(n)
# O(N* some log factors) much slower than geo's; 1940ms
sieve(n)
|
a1c657c309fabf23cd2f255e0431ec673c2d8470 | anoubhav/Codeforces-Atcoder-Codechef-solutions | /Codeforces/Educational Round 88/C.py | 1,885 | 3.671875 | 4 | # If there are even number of cups, the attained temperature is always: (h+c)/2. If there are odd number of total cups (let it be 2*x - 1). There are x hot cups and (x-1) cold cups. The attained temperature is given by (h*x + c*(x-1))/2*x-1 = t_attained ---- EQN 1
# In the odd no. of cups case, the no. of hot cups is ALWAYS one more than no. of cold cups, so t_attained > (h+c)/2.
# If t_desired < (h+c)/2 --> the answer is two cups.
# If t_desired > (h+c)/2 --> the answer consists of odd no. of cups. This can be obtained by solving EQN 1 for x by substituting t_attained by t_desired.
# x = (t_desired - c)/ (h + c - 2*t_desired). Solving this we get a fractional value for x.
# The answer will be 2*min(t_desired - t_attained_floor_x, t_desired - t_attained_ceil_x)-1.
# As x, gives us the number of h cups. The answer is total number of cups which is 2*x - 1
# Solve above equation for x (no. of hot cups) by replacing t_attained with t_desired.
## Failing on the test case:
# 1
# 999977 17 499998
# Output = 499979
# Answer = 499981
from sys import stdin, stdout
from decimal import Decimal # tried using decimal module to get more precision.
t = int(input())
for _ in range(t):
h, c, t = map(int, stdin.readline().split())
if (h+c) >= 2*t:
print(2)
else:
x1 = (c-t)//(h+c- 2*t) # floor x
x2 = x1 + 1 # ceil x
# get both average temperature and check which is minimum
t1 = Decimal((h*x1 + c*(x1 - 1))/((2*x1) - 1))
t2 = Decimal((h*x2 + c*(x2 - 1))/((2*x2) - 1))
# print(t1, t2, abs_avg_x1, abs_avg_x2)
t = Decimal(t)
abs_avg_x1 = Decimal(abs(t - t1))
abs_avg_x2 = Decimal(abs(t - t2))
if abs_avg_x1<=abs_avg_x2:
print(2*x1 - 1)
else:
print(2*x2 - 1)
|
f05605470e60d9342fc96dca170bc90e9418cac4 | Mustafa-pnevma-galinis/Basic-Algorithms | /Agorithms.py | 11,412 | 4.34375 | 4 | #بسم اللّه و الصلاة و السلام على جميع الأنبياء و المرسلين و آل بيوتهم الطاهرين المقربين و على من تبعهم بإحسانٍ إلى يوم الدين
# ◙◙ (α) Merge Sort Algorithm
count = 0
lst = [4,6,8,1,3,2,5,7]
sectorA = lst[0:4]
sectorB = lst[4:8]
# ◘◘@Note: to allocate the size of the array before initialisation.
#sortedArray = [][:5]
sortedArray = []
count = 0
# ◘◘@Note: to print the entire array elements without for loop.
'''print(*sectorA,sep ="\n")
print('\n'.join(map(str, sectorA)))'''
'''for i in range(1):
if (sectorA[-1] < sectorA[0] and sectorA[-1] < sectorA[1] and sectorA[-1] < sectorA[2]):
sortedArray.append(sectorA[-1])
if(sectorA[0] < sectorA[1] and sectorA[0] < sectorA[2] ):
sortedArray.append(sectorA[0])
if(sectorA[1] < sectorA[2]):
sortedArray.append(sectorA[1])
sortedArray.append(sectorA[2])
'''
'''for i in sectorA:
if(sectorA[-1] < i):
sortedArray.append(sectorA[-1])
if(sectorA[0] < i):
sortedArray.append(sectorA[0])
if (sectorA[1] < i):
sortedArray.append(sectorA[1])
sortedArray.append(sectorA[2])
'''
# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
# ◙◙ {Select Sorting Algorithms}
#───────────────────────────────────────────────────────────────────────────────────
#◘◘@Note: to sort a list we need firstly to set the minimum number {declare a new variable} as the first index on the list; either it is the minimum or not,
# then compare that number with the rest numbers on the list, after getting the {real minimum number}, set it to be the first index on the list.
unsortedLst = [7,11,8,1,4,2,3,9,12,10]
for i in range(len(unsortedLst)):
# Find the minimum element in remaining
# unsorted array
min_number = i
for j in range(i+1, len(unsortedLst)):
if unsortedLst[min_number] > unsortedLst[j]:
min_number = j
# Swap the found minimum element with
# the first element
unsortedLst[i], unsortedLst[min_number] = unsortedLst[min_number], unsortedLst[i]
'''print(unsortedLst)'''
# ◘◘Select Sorting Algorithm illustration;
'''
◘ for i in range (11):
min_number = 0
for j in range(1,11):
if (unsortedLst[0] > unsortedLst[1]):
min_number = 1
▬# Then Swapping indices, The min_number will get in-place
of the higher_number; That process will continuosly occured till
the array got arranged.
'''
# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
# ◙◙ {Bubble Sorting Algorithms}
#───────────────────────────────────────────────────────────────────────────────────
def bubbleSort(array):
n = len(array)
for i in range(n-1): # ◘◘ {n-1} because the last element has the index No. [(len(array)-1)].
for j in range(0,n-i-1):
if (array[j] > array[j+1]):
array[j], array[j+1] = array[j+1], array[j]
return array
'''
# ◘◘Illustration: ▬ On first iteration
for i in range(7):
for j in range(0,6): # On first iteration i = 0
if (array[1] > array[2]): # ▬ if True > then swap the indices values.
array[1], array[2] = array[2],array[1]
'''
'''print(bubbleSort([1,3,4,5,8,6,7,2]))'''
# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
# ◙◙ {Insertion Sorting Algorithms}
#───────────────────────────────────────────────────────────────────────────────────
L = [4,5,8,9,2,1,3,7,6]
for i in range(1,len(L)):
k = L[i]
j = i - 1
while (j >= 0 and L[j] > k):
L[j+1] = L[j]
j = j - 1
L[j+1] = k
'''Algorithm Analysis'''
'''k = L[0]
j = 0'''
# if {Ture} then looping
'''while (1 >= 0 and 4 > 5):
L[2] = L[1]
j = 0 '''
# if False then keep it in its index.
'''L[j+1] = k ◘◘ As {j+1 = 1}
'''
# ◘ get the integer value of division. » use (//) ▬ for example: {//2}.
'''print(len(L) //2)'''
# ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
# ◙◙ {Merge Sort Algorithm}
#───────────────────────────────────────────────────────────────────────────────────
# ◘ To define this Algorithm we need to pass through some steps:
# ○ α) Divide the main array by its length for sub-arrays.
# ○ ß) Sorting elements.
# ○ Γ) Merging elements in sub-arrays; finally merge sub-arrays to the final form of array.
def mergeSort(array):
if (len(array) > 1):
mid_length = len(array) //2 # ◘ Get the integer number of the length.
# ◙ Dividing the main array to (2) sectors {Right -- Left}..
L = array[:mid_length]
R = array[mid_length:]
# Then Sorting The Right and Left sector Separately.
# ◘◘ The Passed array will be divided till reaching out one element of each array to be compared with.
mergeSort(L)
mergeSort(R)
i = j = k = 0
# ◘ Loop till the reaching the length of both arrays and copying the main array elements
# on both sub-arrays.
# »» On this step: Dividing the main array to {2 arrays}; while one of these arrays
# will contain the smaller valued elements and the other will contain the higher valued elements.
while i < len(L) and j < len(R):
# ○ Comparing with first elements in both arrays.
# » If the left side element is smaller than the right side element.
if (L[i] < R[j]):
# ◘ Replacing the first element in the main arrays with the smaller number.
array[k] = L[i]
i += 1
# » If the Right side element is smaller than the left side element.
else:
array[k] = R[j]
j += 1
k += 1
while i < len(L):
array[k] = L[i]
i += 1
k += 1
while j < len(R):
array[k] = R[j]
j += 1
k += 1
return array
'''print(mergeSort([5,6,1,3,2,7,9,8,4]))'''
#────────────────────────────────────important──────────────────────────────────────
# α)
# ▬▬ Check if a String contains an integer number:
'''x = "asdfas5654asd"
for i in range(len(x)):
try:
if (isinstance(int(x[i]), int)):
print("Integer")
except ValueError:
print("Not Integer")
'''
# ß)
# ▬▬ Inverting string value.
# ◘ Method_1
'''print(string[::-1])'''
# ◘ Method_2
'''x = ""
count = len(string) -1
for i in string:
x += string[count]
count -= 1'''
# Γ)
# ▬▬ getting the absolute number from float value.
'''if int(n) < n:
print(int(n) + 1)
else:
print(n)'''
# Σ)
# ▬▬ using enumerate function; Note that {enumerate} will print a type (list) in a form of dictionary {key and values}.
'''lst = ["GTX 1650","GTX 980","GTX 970","RTX 2070"]
for i,j in enumerate(lst):
print(i,j)
'''
'''
0 GTX 1650
1 GTX 980
2 GTX 970
3 RTX 2070
'''
# σ)
# ▬▬ using {.round()} function that is mainly used to get the nearest decimals according to the past argument.
''' ◘ Note: that while the the parameter passed to this argument is <-number> » That will return the nearest 100 number.
# ╚ For example: x = 5555.456156187 └ print(round(x,-2)) ▬ returns 5600'''
x = -10
y = 5
#print(min(abs(y),abs(x)))
# µ)
# ▬▬ remove an item from a list and add it to an appended new list.
'''
def remove_item(x):
if x == 30:
lst_1.reverse()
lst.append(lst_1)
return False
if x > 30:
lst.remove(x)
lst_1.append(x)
remove_item(x - 1)
return lst
'''
# τ)
# ▬▬ return a key for the specified value in dictionary.
'''def get_required_item(item_1,item_2,item_3):
dictionary = {"GTX 1650":item_1,"RTX 2070":item_2,"RTX 3080":item_3}
for key,value in dictionary.items():
if value:
return key'''
#───────────────────────────────────────────────────────────────────────────────────
# Check your answer
#q6.check()
#print(exactly_one_topping(False,True,False))
'''
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]
lst = [x for x in l if x > 4]
print(lst)'''
dic = {"GTX 1650":2900,"GTX 2060":5700,"RTX 3080":2900}
x = 2900
#print(remove_item(40))
#print(lst)
'''
def exactly_one_topping(ketchup, mustard, onion):
"""Return whether the customer wants exactly one of the three available toppings
on their hot dog.
"""
lst = []
topping_dictionary = {"Ketchup":ketchup,"Mustard":mustard,"Onion":onion}
for key, value in topping_dictionary.items():
if value == True:
lst.append(key)
return lst
print(exactly_one_topping(True,True,False))
'''
def select_second(L):
"""Return the second element of the given list. If the list has no second
element, return None.
"""
if len(L) > 2:
return L[1]
else:
return None
|
93981da08850dd74b5752556d1b8f0ede9c75d1d | 6qos/CSE | /notes/venv/Semester 2 Note.py | 346 | 3.921875 | 4 | print("Hello World")
# Cookies
cars = 5
driving = True
print("I have %s cars" % cars)
age = input("How Old Are You?")
print("%s?? Really??"% age)
colors = ["Red", "Blue", "Black", "White"]
colors.append("Cyan")
print(colors)
import string
print(list(string.ascii_letters))
print(string.digits)
print(string.punctuation)
print(string.printable)
|
a284d342205f358abf46a778680e060ac193cc3d | senthilkumarr2212/python | /Day1.py | 876 | 3.96875 | 4 | # Task 1
names = ["john", "jake", "jack", "george", "jenny", "jason"]
for name in names:
if len(name) < 5 and 'e' not in name:
print('Printing Unique Names : ' +name)
# Task 2
str = 'python'
print('c' + str[1:])
# Task 3
dict = {"name": "python", "ext": "py", "creator": "guido"}
print(dict.keys())
print(dict.values())
# Task 4
for i in range(101):
if i % 3 == 0 and i % 5 == 0:
print("fizzbuzz")
elif i % 3 == 0:
print("fizz")
elif i % 5 == 0:
print("buzz")
else:
print("nothing")
# Task 5
guessnum = input("Enter your Guess Number :")
num = 20
if int(guessnum) == num:
print("You guessed correctly")
elif int(guessnum) > num:
print("Your Guess value is greater than the actual number")
else:
print("Your Guess value is less than the actual number")
|
6e12c901e0706b05f3ac67dd2e0c5df3215855bf | gothaur/the_game | /projectile.py | 2,174 | 3.9375 | 4 | import pygame
from pygame.sprite import Sprite
from penguin import Enemy
class Projectile(Sprite):
def __init__(self, settings, penguin, f_img, b_img):
"""
:param penguin: penguin which fired projectile
:param f_img: image faced forward
:param b_img: image faced backward
"""
super().__init__()
self.direction = penguin.move_left
if self.direction:
self.width = b_img.get_width()
self.height = b_img.get_height()
else:
self.width = f_img.get_width()
self.height = f_img.get_height()
if self.direction or type(penguin) == Enemy:
self.x = penguin.x - int(penguin.get_width() * 0.35)
else:
self.x = penguin.x + int(penguin.get_height())
self.y = penguin.y + int(penguin.get_width() * 0.25)
self.penguin = penguin
self.f_img = f_img
self.b_img = b_img
self.settings = settings
self.name = "Projectile"
def draw(self, win):
"""
Draws projectile on the screen
:return: None
"""
if self.direction or type(self.penguin) == Enemy:
image = self.b_img
else:
image = self.f_img
win.blit(image, (self.x, self.y))
def move(self):
"""
Moves projectile on the screen
:return: None
"""
if self.direction or type(self.penguin) == Enemy:
self.x -= (self.penguin.get_vel() + self.settings.bullet_speed)
else:
self.x += self.penguin.get_vel() + 15 + self.settings.bullet_speed
def collide(self, penguin):
"""
Checks if projectile collides with penguin
:param penguin:
:return: True if collided
"""
penguin_mask = penguin.get_mask()
if self.direction or type(penguin) == Enemy:
projectile_mask = pygame.mask.from_surface(self.b_img)
else:
projectile_mask = pygame.mask.from_surface(self.f_img)
offset = (self.x - penguin.get_x(), self.y - penguin.get_y())
return penguin_mask.overlap(projectile_mask, offset)
|
8e4078ae8d366d00cc83fdb60acfed096f252a1e | VINITHAKANDASAMY/python_programming | /hunter/upper.py | 74 | 3.890625 | 4 | list = ['vibi','john','peter']
for item in list:
print(item.upper())
|
90472457e00f25dfca4f589b398a60f47cd311c8 | VINITHAKANDASAMY/python_programming | /player/vowel.py | 151 | 4.03125 | 4 | v1=input("enter an alphabet")
if v1 in ('a','e','i','o','u'):
print("given alphabet is vowel")
else:
print("given alphabet is consonant")
|
ce9090dbbbc2431d045c37550b6704403938a23b | justinchoys/learn_python | /ex43.py | 2,904 | 3.75 | 4 | from sys import exit
from random import randint
from textwrap import dedent
class Scene(object):
def enter(self):
print("This is not a configured scene, use a subclass")
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')
while current_scene != last_scene: #check if current scene is the ending
next_scene_name = current_scene.enter() #enter current scene and get return value
current_scene = self.scene_map.next_scene(next_scene_name) #use return value to update current scene
class Death(Scene):
def enter(self):
print("You are dead")
exit(1)
pass
class CentralCorridor(Scene):
def enter(self):
n = input("You enter the central corridor, Shoot, Dodge, or Tell Joke:")
if n == "Shoot":
return 'death'
elif n == "Dodge":
return 'death'
elif n == "Tell Joke":
return 'laser_weapon_armory'
else:
print("does not compute")
return 'central_corridor'
class LaserWeaponArmory(Scene):
def enter(self):
print("You enter the laser weapon armory, you have 10 guesses for 3 digit code:")
code = f"{randint(1,9)}{randint(1,9)}{randint(1,9)}"
guess = input("[keypad]> ")
guesses = 0
print(f"The code is actually {code}")
while guess != code and guesses < 10:
print("WRONG")
guesses += 1
guess = input("[keypad]> ")
if guess == code:
print("You got the code correct")
return 'the_bridge'
else:
print("you got the code wrong")
return 'death'
class TheBridge(Scene):
def enter(self):
n = input("You enter the bridge, throw bomb or place bomb")
if n == 'throw bomb':
print("You threw the bomb and died")
return 'death'
elif n == 'place bomb':
print("You place bomb and continue")
return 'escape_pod'
else:
print("does not compute")
return 'the_bridge'
class EscapePod(Scene):
def enter(self):
print("You enter the escape pod room")
x = randint(1, 3) #generate random number 1, 2, or 3
n = int(input("You choose a door from 1-3"))
if n == x:
print("You choose the correct door and escape")
return 'finished'
else:
print("You choose the wrong door...")
return 'death'
class Finished(Scene):
def enter(self):
print("You finish the game")
return 'finished'
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge' : TheBridge(),
'escape_pod' : EscapePod(),
'death' : Death(),
'finished':Finished(),
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
val = Map.scenes.get(scene_name) #return None if doesn't exist in dict
return val
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play() |
3ff0b5ab4f45e5763fcc28aef525111e513cd5e9 | maisuto/address | /takeaddress.py | 929 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python
from makeaddress import MakeAddress
class TakeAddress(MakeAddress):
def make_new_csv(self, csvdic):
newcsv = []
top_list = [
'name',
'phone',
'mobile_pyone',
'zip code',
'address'
]
newcsv.append(top_list)
for i in csvdic:
line = []
line.append(" ".join((i['lastname'], i['firstname'])))
line.append(":".join(("TEL", i['phone'])))
line.append(":".join(("MOBILE", i['mobilephone'])))
line.append(":".join(("〒", i['zip code'])))
line.append("".join((i['address1'], i['address2'], i['address3'])))
newcsv.append(line)
return newcsv
if __name__ == '__main__':
test = TakeAddress("addresslist.csv")
test.write_csv("takeaddress_new.csv")
|
edace158002f255b7bbfd8d5708575912ab065d9 | Varsha1230/python-programs | /ch4_list_and_tuples/ch4_lists_and_tuples.py | 352 | 4.1875 | 4 | #create a list using[]---------------------------
a=[1,2,4,56,6]
#print the list using print() function-----------
print(a)
#Access using index using a[0], a[1], a[2]
print(a[2])
#change the value of list using------------------------
a[0]=98
print(a)
#we can also create a list with items of diff. data types
c=[45, "Harry", False, 6.9]
print(c)
|
ccade5b4083c03f67193c304ed68f470f91ec980 | Varsha1230/python-programs | /ch11_inheritance.py/ch11_3_multiple_inheritance.py | 496 | 3.875 | 4 | class Employee:
company = "visa"
eCode = 120
class Freelancer:
company = "fiverr"
level = 0
def upgradeLevel(self):
self.level =self.level + 1
class Programmer(Employee, Freelancer): #multiple inheritance
name = "Rohit"
p = Programmer()
print(p.level)
p.upgradeLevel()
print(p.level)
print(p.company) #what will be printed... due to this line---> ans:--> "visa", bcoz when we define child class then, we inherit employee-class first then freelancer-class
|
a12737d07ea5a4ac4268d50070a09be8018fd499 | Varsha1230/python-programs | /ch2_variables_and_dataType/ch2_prob_04_comparision_operator.py | 138 | 3.796875 | 4 | # use comparision operator to find out whether a given variable 'a' is greater than 'b' or not... take a=34 and b=80
a=34
b=80
print(a>b) |
194b4560ae2532e13e65a0f4b3664149578c3293 | Varsha1230/python-programs | /ch13_advance_python2.py/ch13_3_format.py | 265 | 3.640625 | 4 | name = "Harry"
channel = "Code with harry"
type = "coding"
#a = f"this is {name}"
#a = "this is {}" .format(name)
# a = "this is {} and his channel is {}" .format(name, channel)
a = "this is {0} and his {2} channel is {1}".format(name, channel, type)
print(a) |
360ec7c1039125c324248437f72dc44eb56d59a5 | Varsha1230/python-programs | /ch8_functions_and_recursion.py/ch8_prob_04.py | 580 | 3.953125 | 4 | # n! = (n-1)! * n
# sum(n) = sum(n-1) + n
#-- there is no exit/stop statement in this loop------------------------------------------------
# def sum(n):
# return (sum(n-1) + n)
# num = int(input("please enter a no.: "))
# add = sum(num)
# print("the sum of n natural numbers is: " + str(add))
#--------------------------------------------------------------------
def sum(n):
if n==1 :
return 1
else :
return n + sum(n-1)
m=int(input("Enter a natural number : "))
x=sum(m)
print("The sum of first " + str(m)+ " natural number is "+ str(x)) |
2765a047df4e0eace928604f2d0dd53cafb7e36f | Varsha1230/python-programs | /ch6_conditional_expressions.py/ch6_prob_05.py | 181 | 3.984375 | 4 | l1 = ["varsha", "ankur", "namrata"]
name = input("please enter your name:\n")
if name in l1:
print("your name is in the list")
else:
print("your name is not in the list") |
e05e4075af111c11cfe2b2f55dfc46ae0c13aa3d | Varsha1230/python-programs | /ch11_inheritance.py/ch11_6_class_method.py | 508 | 3.703125 | 4 | class Employee:
company = "camel" # class-attribute
location = "Delhi" # class-attribute
salary = 100 # class-attribute
# def changeSalary(self, sal):
# self.__class__.salary = sal # dunder class (we can use this for same task,but it is related to object, here oue motive is just use the class method only)
@classmethod
def changeSalary(cls, sal):
cls.salary = sal
e = Employee()
print(e.salary)
e.changeSalary(455)
print(e.salary)
print(Employee.salary) |
5e8c0be79943cb840b77adfc98efbb1664d09972 | Varsha1230/python-programs | /ch6_conditional_expressions.py/ch6_5_logical_operator.py | 229 | 3.96875 | 4 | age=int(input("enter your age: "))
if(age>34 and age<56):
print("you can work with us")
else:
print("you can't work with us")
print("Done")
if(age>34 or age<56):
print("you can with us")
else:
print("djvbvjnd") |
c43b35b690a329f582683f9b406a66c826e5cabf | Varsha1230/python-programs | /ch3_strings/ch3_prob_01.py | 435 | 4.3125 | 4 | #display a user entered name followed by Good Afternoon using input() function--------------
greeting="Good Afternoon,"
a=input("enter a name to whom you want to wish:")
print(greeting+a)
# second way------------------------------------------------
name=input("enter your name:")
print("Good Afternoon," +name)
#-----------------------------------------------------
name=input("enter your name:\n")
print("Good Afternoon," +name) |
5b3ef497693bc27e3d5fee58a9a77867b8f18811 | Varsha1230/python-programs | /ch11_inheritance.py/ch11_1_inheritance.py | 731 | 4.125 | 4 | class Employee: #parent/base class
company = "Google"
def showDetails(self):
print("this is an employee")
class Programmer(Employee): #child/derived class
language = "python"
# company = "YouTube"
def getLanguage(self):
print("the language is {self.language}")
def showDetails(self): #overwrite showDetails()-fn of class "Employee"
print("this is an programmer")
e = Employee() # object-creation
e.showDetails() # fn-call by using object of class employee
p = Programmer() # object-creation
p.showDetails() # fn-call by using object of class programmer
print(p.company) # using claas-employee's attribute by using the object of class programmer
|
d6fd821221299ad77efb685c4c82b4b485bec16d | vivek-2000/DSA | /Array/K_sorted_array.py | 401 | 3.53125 | 4 | from heapq import heappop, heappush, heapify
def sort_k(arr,n,k):
heap=arr[:k+1]
heapify(heap)
tar_ind=0
for rem_elmnts_index in range(k+1,n):
arr[tar_ind]=heappop(heap)
heappush(heap, arr[rem_elmnts_index])
tar_ind+=1
while heap:
arr[tar_ind]=heappop(heap)
tar_ind+=1
k=3
arr=[2,6,3,12,56,8]
n=len(arr)
sort_k(arr,n,k)
print(arr)
#time complexity [nlogk] |
4d669245dc188f77447bac45eaa554bba7feab52 | BestNico/Leetcode_answer | /1431/1431.py | 288 | 3.625 | 4 | from typing import List
class Solution(object):
def kidWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
biggestEle = max(candies)
subList = [biggestEle - i for i in candies]
return [True if i <= extraCandies else False for i in subList] |
b4591e299bcaa0f177ab2da26aaa98dd3599321f | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no21reOrderOddEven.py | 1,064 | 3.640625 | 4 | def reOrderOddEven_1(str):
length = len(str)
if length == 0:
return
i = 0
j = length - 1
while i < j:
#前面的为奇数,遇到偶数停止
while i < j and (str[i] & 0x1) != 0:
i += 1
while i < j and (str[j] & 0x1) == 0:
j -= 1
if i < j:
temp = str[j]
str[j] = str[i]
str[i] = temp
return str
# 测试用例
def printArray(str,length):
if length <= 0 :
return
for i in range(0,length):
print(str[i],end='')
print("\t")
def Test(name,str,length):
if len(name) != 0:
print(name+"bagin")
printArray(str,length)
str = reOrderOddEven_1(str)
printArray(str,length)
if __name__ == '__main__':
str1 = [1, 2, 3, 4, 5, 6, 7]
str2 = [2, 4, 6, 1, 3, 5, 7]
str3 = [1, 3, 5, 7, 2, 4, 6]
str4 = [1]
str5 = [2]
str6 = []
Test("test1",str1,7)
Test("test2",str2,7)
Test("test3",str3,7)
Test("test4",str4,1)
Test("test5",str5,1)
Test("test6",str6,0)
|
dff95a393d887cc6f44d3480f02dc8064e71bdc0 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no40getLeastNumbers.py | 538 | 3.75 | 4 | import maxHeap
def getLeastNumbers(arr,k):
if not k or not arr or k < 1 or len(arr) < k :
return
heap = maxHeap.MaxHeap(arr[:k])
for item in arr[k:]:
if item < heap.data[0]:
heap.extractMax()
heap.insert(item)
for item in heap.data:
print(item)
if __name__ == "__main__":
# arr1 = [4, 5, 1, 6, 2, 7, 3, 8]
# getLeastNumbers(arr1,4)
arr2 = [4, 5, 1, 6, 2, 7, 3, 8]
getLeastNumbers(arr2,None)
# arr3=[4, 5, 1, 6, 2, 7, 2, 8]
# getLeastNumbers(arr2,2) |
40ceb70ecc8460fff034f6bbc53cc7cba2267938 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no42findGreatestSumOfSubArray.py | 400 | 3.640625 | 4 | def findSubarray(nums):
invalidInput = False
if not nums or len(nums) <= 0:
invalidInput = True
return 0
invalidInput = False
curSum = 0
greastestSum = float('-inf')
for i in nums:
if curSum < 0:
curSum = i
else:
curSum += i
if curSum > greastestSum:
greastestSum = curSum
return greastestSum |
fc39fba8f6f26ad7ed138dd93379482053578c20 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no53getFirstK.py | 1,411 | 4 | 4 | # 巧用二分查找在排序数组中找一个特定数字
def getNumberOfK(data,length,k):
number = 0
if data and length > 0:
first = getFirstK(data,length,k,0,length-1)
last = getLastK(data,length,k,0,length-1)
if first > -1 and last > -1:
number = last - first +1
return number
def getFirstK(data,length,k,start,end):
if start > end:
return -1
middleIndex = (start+end)//2
middleData = data[middleIndex]
if middleData == k:
if (middleIndex > 0 and data[middleIndex-1] != k) or middleIndex == 0:
return middleIndex
else:
end = middleIndex - 1
elif middleData > k:
end = middleIndex - 1
else:
start = middleIndex + 1
return getFirstK(data,length,k,start,end)
def getLastK(data,length,k,start,end):
if start > end:
return -1
middleIndex = (start+end)//2
middleData = data[middleIndex]
if middleData == k:
p = data[middleIndex+1]
if (middleIndex < length -1 and data[middleIndex+1]!=k) or middleIndex == length-1:
return middleIndex
else:
start = middleIndex + 1
elif middleData > k:
end = middleIndex - 1
else:
start = middleIndex + 1
middleIndex = getLastK(data,length,k,start,end)
return middleIndex
data = [3,3,3,3,4,5]
print(getNumberOfK(data,6,3))
|
29d80bdd038da385e916ebd1a02a0e200f9b7378 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no7reconstructBiTreev2.py | 4,501 | 3.75 | 4 | class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.rightChild = None
self.leftChild = None
def insertLeftChild(self,newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
def insertRightChild(self,newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild
def setRootVal(self,obj):
self.key = obj
def getRootVal(self):
if self == None:
return -1
return self.key
def printPreTree(self):
if self == None:return
print(self.key,end=' ')
if self.leftChild :
self.leftChild.printPreTree()
if self.rightChild:
self.rightChild.printPreTree()
def printInTree(self):
if self == None: return
if self.leftChild:
self.leftChild.printInTree()
print(self.key, end=' ')
if self.rightChild:
self.rightChild.printInTree()
# def construct(preorder:list,inorder:list,length:int):
# if preorder == None or inorder == None or length <= 0:
# return None
# stratPreorder = 0
# endPreorder = stratPreorder +length -1
# startInorder = 0
# endInorder = startInorder + length -1
# return constructCore(preorder,stratPreorder,endPreorder,inorder,startInorder,endInorder)
#
# def constructCore(preorderList,startPreorder,endPreorder,inorderList,startInorder,endInorder):
#
# #前序遍历的第一个数字是根结点的值
# rootValue = preorderList[startPreorder]
# root = BinaryTree(rootValue)
#
#
# if startPreorder == endPreorder:
# if startInorder == endInorder and preorderList[startPreorder] == inorderList[startInorder]:
# return root
# else:
# print("invalid input")
#
# #在中序遍历序列中找到根结点的值
# rootInorder = startInorder
# while rootInorder <= endInorder and inorderList[rootInorder] != rootValue:
# rootInorder += 1
#
# if rootInorder == endInorder and inorderList[rootInorder] != rootValue:
# print("invalid input")
#
# leftLength = rootInorder - startInorder
# leftPreorderEnd = startPreorder + leftLength
#
# if leftLength > 0:
# #构建左子树
# root.leftChild = constructCore(preorderList,startPreorder+1,leftPreorderEnd,
# inorderList,startInorder,rootInorder-1)
#
# if leftLength < endPreorder - startPreorder:
# #构建右子树
# root.rightChild = constructCore(preorderList,leftPreorderEnd+1,endPreorder,
# inorderList,rootInorder+1,endInorder)
# print('\ntest:')
# root.printPreTree()
# return root
def buildTree(preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if len(inorder) == 0:
return None
# 前序遍历第一个值为根节点
root = BinaryTree(preorder[0])
# 因为没有重复元素,所以可以直接根据值来查找根节点在中序遍历中的位置
mid = inorder.index(preorder[0])
# 构建左子树
root.leftChild = buildTree(preorder[1:mid + 1], inorder[:mid])
# 构建右子树
root.rightChild = buildTree(preorder[mid + 1:], inorder[mid + 1:])
print("\ntest:")
root.printPreTree()
return root
def test(testName:str,preorder:list,inorder:list,length:int):
print(testName +"begins:")
print("the preorder sequence is:")
for i in preorder:
print(i,end='')
print("\nthe inorder sequence is:")
for i in inorder:
print(i,end='')
#root = construct(preorder,inorder,length)
root = buildTree(preorder,inorder)
print("\npreorder:")
root.printInTree()
print("\ninorder:")
root.printPreTree()
def test1():
length = 8
preorder = [1, 2, 4, 7, 3, 5, 6, 8]
inorder = [4, 7, 2, 1, 5, 3, 8, 6]
test("test1",preorder,inorder,length)
if __name__=="__main__":
test1()
|
a806ec1eaa2bd542dda64e9dfee12847b32771c1 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no14cutstring.py | 1,020 | 3.609375 | 4 | #大问题->小问题->小问题最优解组合->大问题最优解----->可以用动态规划
def maxProductAfterCutting_DP(length):
if length <2:
return 0
if length == 2:
return 1
if length == 3:
return 2
products = [0,1,2,3]
max = 0
for i in range(4,length+1):
max = 0
products.append(0)
for j in range(1,i//2+1):
product = products[j] * products[i-j]
if max < product:
max = product
products[i] = max
max = products[length]
return max
def maxProductAfterCutting_TX(length):
if length <2:
return 0
if length == 2:
return 1
if length == 3:
return 2
timesOf3 = length//3
if (length - timesOf3 * 3 == 1):
# timesOf3 -= 1
timesOf2 = 2
# timesOf2 = (length - timesOf3 * 3)//2
timesOf2 = 1
return int(pow(3,timesOf3)) * int(pow(2,timesOf2))
print(maxProductAfterCutting_DP(8))
print(maxProductAfterCutting_TX(8)) |
b03562bddb37cc22ce4c2aba658d8c368becb2c0 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no39moreThanHalfNum_1.py | 499 | 3.546875 | 4 | def MoreThanHalfNum(numbers,length):
# 判断输入符合要求
if not numbers and length<=0:
return 0
result = numbers[0]
times = 1
for i in range(1,length):
if times == 0:
result = numbers[i]
times = 1
elif numbers[i] == result:
times += 1
else:
times -= 1
sum = 0
for item in numbers:
if item == result:
sum += 1
return result if sum*2 > length else 0
#21ms5752k |
266cab3b9773bbca24a1449cd305e27e3b82ab59 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no55isBalanced2.py | 531 | 3.78125 | 4 | def isBalanced(proot,depth):
if not proot:
depth = 0
return True
leftDepth = rightDepth = -1
# 递归,一步步往下判断左右是否是平衡树,不是就返回,是的话记录当前的深度
if isBalanced(proot.left,leftDepth) and isBalanced(proot.right,rightDepth):
diff = leftDepth - rightDepth
if diff <= 1 and diff >= -1:
depth = max(leftDepth,rightDepth)+1
return True
return False
def isBalanced(proot):
return isBalanced(proot,0)
|
4d834531037456b1cac14a8fb3d72df707764355 | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no17print_n_num_v2.py | 1,616 | 3.625 | 4 | def PrintToMAxDIgits(n):
if n <= 0:
return
number = [0]*(n)
while(not Increment(number)):
PrintNumber(number)
def Increment(number:[int]):
isOverflow = False
nTakeOver = 0
length = len(number)
#每一轮只计一个数,这个循环存在的意义仅在于判断是否有进位,如有进位,高位就可以加nTakeove
# 以isOverflow判断是否最高位进位,最高位进位则溢出,整个结束输出。
for i in range(length-1,-1,-1):
nSum = number[i] + nTakeOver
if i == length -1:
nSum += 1
if nSum >= 10:
if i == 0:
isOverflow = True
else:
nSum -= 10
nTakeOver = 1
number[i] = nSum
else:
number[i] = nSum
break
return isOverflow
def ifIncrement(number):
isOverflow = False
nTakeOver = 0
length = len(number)-1
for i in range(length,-1,-1):
nSum = number[i] + nTakeOver
if i == length:
nSum += 1
if nSum >= 10:
if i == 0:
isOverflow = True
else:
nSum -= 10
number[i] = nSum
nTakeOver = 1
else:
number[i] = nSum
break
return isOverflow
def PrintNumber(number:[int]):
isBegining = True
for i in range(0,len(number)):
if isBegining and number[i] != 0:
isBegining = False
if not isBegining:
print(number[i],end='')
print("\n")
PrintToMAxDIgits(2) |
a2dc98deb96601ebc3b9643d539a31d7835853cc | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no34findPath.py | 1,041 | 3.703125 | 4 | # 找到二叉树中某一值和的路径
def findPath(root,expectedSum):
if not root:
return []
result = []
def findPathCore(root,path,currentSum):
currentSum += root.val
path.append(root)
ifLeaf = not (root.left or root.right)
# 是叶子节点,且和为目标和
if ifLeaf and currentSum==expectedSum:
# result.append(path) 这里要加入节点的值,不能直接加入节点
tempPath = []
for node in path:
tempPath.append(node.val)
result.append(tempPath)
# 是叶子节点,和大于目标和,直接pop,不是叶子节点同理
# 不是叶子节点且和小于目标和,遍历其左右子树
if (not ifLeaf) and currentSum<expectedSum:
if root.left:
findPathCore(root.left,path,currentSum)
if root.right:
findPathCore(root.right,path,currentSum)
path.pop()
findPathCore(root,[],0)
return result
|
f1e92e70cfd8d1757967e5ff3d56883ac269227a | AprilLJX/LJX-also-needs-to-earn-big-money | /code-offer/no16pow.py | 1,535 | 3.796875 | 4 | class Solution:
g_Invalid_input = False
def power(self,base,exponent):
if base == 0 and exponent < 0:
self.g_Invalid_input = True
return 0
absExponent = exponent
if exponent < 0:
absExponent = -exponent
result = self.powerCal_2(base,absExponent)
if exponent < 0:
result = 1 / result
return result
def powerCal(self,base,exponent):
result = 1
for i in range(0,exponent):
result *= base
return result
def powerCal_2(self,base,exponent):
if exponent == 0:
return 1
if exponent == 1:
return base
result = self.powerCal_2(base,exponent>>1)
result *= result
#判断奇偶
if exponent & 0x1 == 1:
result *= base
return result
def Test(self,base,exponent,expected,inputerror):
if self.power(base,exponent) == expected and inputerror == self.g_Invalid_input:
print("passed")
else:
print("failed")
if __name__ == '__main__':
s = Solution()
# 底数、指数都为正数
s.Test(2, 3, 8, False)
#底数为负数、指数为正数
s.Test(-2, 3, -8, False)
#指数为负数
s.Test( 2, -3, 0.125, False)
#指数为0
s.Test(2, 0, 1, False)
#底数、指数都为0
s.Test(0, 0, 1, False)
#底数为0、指数为正数
s.Test(0, 4, 0, False)
#底数为0、指数为负数
s.Test(0, -4, 0, True)
|
1c424c81442732b5b5c2d7616919ac81bc4dfcd2 | mittgaurav/Pietone | /power_a_to_b.py | 637 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 3 13:57:40 2019
@author: gaurav
cache half power results. O(log n)
"""
def power(a, b):
"""power without pow() under O(b)"""
print("getting power of", a, "for", b)
if a == 0:
return 0
if b == 1:
return a
elif b == 0:
return 1
elif b < 0:
return 1 / power(a, -b)
else: # positive >1 integer
half_res = power(a, b // 2)
ret = half_res * half_res
if b % 2: # odd power
ret *= a
return ret
for A, B in [(4, 5), (2, 3), (2, -6), (12, 4)]:
print(A, B, ":", pow(A, B), power(A, B))
|
0042a3255312843743e1e257face5599acc063d8 | mittgaurav/Pietone | /skyline.py | 5,927 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 16 22:56:07 2019
@author: gaurav
"""
# NOT CORRECT
# NOT CORRECT
# NOT CORRECT
# NOT CORRECT
def skyline(arr):
"""A skyline for given
building dimensions"""
now = 0
while now < len(arr):
start, height, end = arr[now]
print(start, height)
nxt = now + 1
while nxt < len(arr): # ignore short and small
n_start, n_height, n_end = arr[nxt]
# next building is far away, so read
if n_start >= end:
break
# next building is big, so we take it
if n_height > height:
now = nxt
if end > n_end: # Add my remains
arr.insert(nxt, (n_end, height, end))
now -= 1
break
# next building is small but longer
# so keep what'll remain after this
if n_end > end:
arr[nxt] = (end, n_height, n_end)
break
nxt += 1
now += 1
now += 1
A = [(1, 10, 4),
(2, 5, 3),
(2.5, 5, 8),
(3, 15, 8),
(6, 9, 11),
(10, 12, 15),
(18, 12, 22),
(20, 8, 25)]
print("====", skyline.__name__)
skyline(A)
def rain_water(arr):
"""collect rain water in
different size building"""
if not arr:
return 0
# for i, max on right and left
left, right = [], []
# collect max on the left side
curr_max = 0
for i in arr:
left.append(curr_max)
curr_max = max(curr_max, i)
# collect max on the right side
curr_max = 0
for i in reversed(arr):
right.insert(0, curr_max)
curr_max = max(curr_max, i)
# for each i, get its difference to min of l/r
res = [max(0, min(_l, _r)-i) for _l, _r, i in
zip(left, right, arr)]
return sum(res)
print("====", rain_water.__name__)
print(rain_water([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]))
def merge_intervals(intervals):
"""merge overlap-
ping intervals"""
out = []
if not intervals:
return out
start, end = intervals[0]
for new_start, new_end in intervals[1:]:
if new_start <= end: # overlapping elements
end = max(end, new_end)
else: # New is after end. There's gap between
# current element end and next start; end
# right now and collect this into result
out.append((start, end))
start, end = new_start, new_end
out.append((start, end))
return out
print("====", merge_intervals.__name__)
print(merge_intervals([[1, 3], [2, 6], [4, 5], [8, 10], [15, 18]]))
print(merge_intervals([[1, 4], [4, 5]]))
def overlapping_intervals(intervals):
"""more than one running"""
out = []
if not intervals:
return out
prev_start, prev_end = 0, 0
for start, end in intervals:
# we have taken care of this later
# by considering all four cases.
start = max(start, prev_start)
if end < start:
# for shorter interval after
continue
if start < prev_end:
if end < prev_end:
out.append((start, end))
prev_start = end
else:
out.append((start, prev_end))
prev_start = prev_end
prev_end = end
else:
prev_start, prev_end = start, end
# we may have some overlapping intervals.
out = merge_intervals(out)
return out
print("====", overlapping_intervals.__name__)
print(overlapping_intervals([[1, 3], [2, 6], [4, 5], [8, 10]]))
print(overlapping_intervals([[1, 7], [2, 6], [4, 5], [8, 10]]))
print(overlapping_intervals([[1, 7], [2, 6], [6, 7], [8, 10]]))
print(overlapping_intervals([[1, 7], [2, 6], [5, 6], [6, 8]]))
print(overlapping_intervals([[1, 6], [2, 8], [3, 10], [5, 8]]))
print(overlapping_intervals([[1, 4], [4, 5]]))
def intersection_intervals(intervals):
"""simple: intersection of all"""
out = []
max_start = min([_[0] for _ in intervals])
min_end = max([_[1] for _ in intervals])
for start, end in intervals:
max_start = max(max_start, start)
min_end = min(min_end, end)
if min_end > max_start:
out.append((max_start, min_end))
return out
print("====", intersection_intervals.__name__)
print(intersection_intervals([[1, 3], [2, 6], [4, 5], [8, 10]]))
print(intersection_intervals([[1, 6], [2, 8], [3, 10], [5, 8]]))
def main(dict_bank_list_of_times):
"""
Bank hours problem
Given a list of banks opening hours, determine
the hours when there is at least one open bank
This is useful to determine when it's possible
to submit an order into a trading system.
Example
JPDL: 8-12 13-17
BARX: 9-13 14-18
Result: 8-18
"""
times = []
for bank_times in dict_bank_list_of_times.values():
times.extend(bank_times)
times.sort(key=lambda x: x[0])
print(merge_intervals(times))
print("==== bank_open_times")
main({"JPDL": [(8, 12), (13, 17)], "BARX": [(9, 13), (14, 18)]})
main({"JPDL": [(8, 12), (13, 17)], "BARX": [(9, 13), (19, 20)]})
main({"JPDL": [(8, 12), (13, 17), (19, 19)], "BARX": [(9, 13)]})
main({"JPDL": [(8, 12), (13, 17), (19, 19)], "BARX": []})
main({})
def total_time(arr):
"""tell total time that user
watched tv, given blocks"""
if not arr:
return 0
arr.sort(key=lambda x: x[0])
max_end = 0
time = 0
for start, end in arr:
assert start <= end
start = max(start, max_end) # start within max_end?
time += max(0, end - start) # end > start but is it > max_end
max_end = max(max_end, end) # for the next
return time
print("====", total_time.__name__)
print(total_time([[10, 20], [15, 25]]))
print(total_time([[10, 20], [22, 25]]))
print(total_time([[10, 20], [1, 25]]))
|
7d4cb2013282e283ff91dd0762490ff962b5eeec | mittgaurav/Pietone | /common_elem_n_arrays.py | 1,938 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 28 02:00:55 2019
@author: gaurav
"""
def common_elem_in_n_sorted_arrays(arrays):
"""find the common elements in
n sorted arrays without using
extra memory"""
if not arrays:
return []
result = []
first = arrays[0]
for i in first: # for each element
are_equal = True
# match first arr's elements
# with each arrays' elements
# and based on whether first
# element is ==, >, or <, we
# take appropriate step. And
# if all match, store elem.
for array in arrays[1:]:
if not array:
# any array has been consumed
return result
if i == array[0]:
array.pop(0)
elif i > array[0]:
# bring array up to level of first
while array and array[0] < i:
array.pop(0)
# somehow array does have that elem
if array and array[0] == i:
array.pop(0)
else:
are_equal = False
else: # first[i] < array[0]
# first is smaller, break
# and take the next first
are_equal = False
break
if are_equal:
result.append(i)
return result
ARR = [
[10, 160, 200, 500, 500],
[4, 150, 160, 170, 500],
[2, 160, 200, 202, 203],
[3, 150, 155, 160, 300],
[3, 150, 155, 160, 301]
]
print(common_elem_in_n_sorted_arrays(ARR))
ARR = [
[23, 24, 34, 67, 89, 123, 566, 1000, 1224],
[11, 22, 23, 24, 33, 37, 185, 566, 987, 1223, 1224, 1234],
[23, 24, 43, 67, 98, 566, 678, 1224],
[1, 4, 5, 23, 24, 34, 76, 87, 132, 566, 665, 1224],
[1, 2, 3, 23, 24, 344, 566, 1224]
]
print(common_elem_in_n_sorted_arrays(ARR))
|
7bad8a4482385e6b355d8cd9bd3e303c6c8e8ed5 | mittgaurav/Pietone | /sudoku.py | 2,787 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 10 02:12:35 2020
@author: gaurav
"""
import math
from functools import reduce
from operator import add
board = [
[4, 3, 0, 0],
[1, 2, 3, 0],
[0, 0, 2, 0],
[2, 1, 0, 0]
]
def _check(board, full=False):
N = len(board)
def _inner(r):
vals = [x for x in r if x != 0] # non-zero elements
if full:
# contain all elements up to N
if sorted(vals) != list(range(1, N + 1)):
return False
else:
# no value below 1 and no value above N
if [x for x in vals if x <= 0 or x > N]:
return False
# all unique
if len(vals) != len(set(vals)):
return False
return True
for i in range(N):
# row and column
for r in (board[i], [x[i] for x in board]):
if not _inner(r):
return False
# each sub-matrix is sqrt(N)
sqrt = int(math.sqrt(N))
for i in range(0, N, sqrt):
for j in range(0, N, sqrt):
cells = reduce(add,
[r[j:j+sqrt] for r in board[i:i+sqrt]], [])
if not _inner(cells):
return False
return True
def solve_sudoku(board):
N = len(board)
def _solve(cell):
"""choose - constraint - goal"""
if cell >= N * N: # goal
print('solution')
[print(_) for _ in board]
return True if _check(board, True) else False
r, c = cell // N, cell % N
if board[r][c] != 0:
# cell is already filled. go to next
return _solve(cell + 1)
for i in range(1, len(board) + 1):
# choose
board[r][c] = i
# constraint
if _check(board):
# recurse
_solve(cell + 1)
# undo
board[r][c] = 0
_solve(0)
[print(_) for _ in board]
solve_sudoku(board)
board = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]
]
solve_sudoku(board)
grid = []
grid.append([3, 0, 6, 5, 0, 8, 4, 0, 0])
grid.append([5, 2, 0, 0, 0, 0, 0, 0, 0])
grid.append([0, 8, 7, 0, 0, 0, 0, 3, 1])
grid.append([0, 0, 3, 0, 1, 0, 0, 8, 0])
grid.append([9, 0, 0, 8, 6, 3, 0, 0, 5])
grid.append([0, 5, 0, 0, 9, 0, 6, 0, 0])
grid.append([1, 3, 0, 0, 0, 0, 2, 5, 0])
grid.append([0, 0, 0, 0, 0, 0, 0, 7, 4])
grid.append([0, 0, 5, 2, 0, 6, 3, 0, 0])
solve_sudoku(grid)
|
853936e6f2e717da65ad845d1e7cfef1b52d630d | mittgaurav/Pietone | /wildcard_pattern_matching.py | 2,518 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 19:24:26 2018
@author: gaurav
"""
def wildcard_matching_no_dp(string, pat):
"""tell whether pattern represents
string as wildcard. '*' and '?'"""
if not pat:
return not string
if not string:
for i in pat:
if i is not '*':
return False
return True
# Either char matched or any char
if string[0] == pat[0] or pat[0] == '?':
return wildcard_matching_no_dp(string[1:], pat[1:])
# Not a wildcard, and no char match
if pat[0] != '*':
return False
# wildcard (*)
# remove current char or
# remove current char and * or
# remove *
return (wildcard_matching_no_dp(string[1:], pat) or
wildcard_matching_no_dp(string[1:], pat[1:]) or
wildcard_matching_no_dp(string, pat[1:]))
def get(matrix, i, j):
if i >= len(matrix) or i < 0:
return True
if j >= len(matrix[0]) or j < 0:
return True
return matrix[i][j]
def wildcard_matching_dp(string, pat):
"""memoization"""
if not pat:
return not string
if not string:
for i in pat:
if i is not '*':
return False
return True
# fill to prevent out of index
matrix = list()
for i in range(0, len(string)):
matrix.append(list())
for j in range(0, len(pat)):
matrix[i].append(False)
# Fill matrix from end.
for i in range(len(string)-1, -1, -1):
for j in range(len(pat)-1, -1, -1):
if string[i] == pat[j] or pat[j] == '?':
matrix[i][j] = get(matrix, i+1, j+1)
elif pat[j] != '*':
matrix[i][j] = False
else:
matrix[i][j] = (get(matrix, i+1, j) or
get(matrix, i+1, j+1) or
get(matrix, i, j+1))
return matrix[0][0]
wildcard_matching = wildcard_matching_dp
wildcard_matching = wildcard_matching_no_dp
print(wildcard_matching("", ""))
print(wildcard_matching("", "**"))
print(wildcard_matching("a", "")) # False
print(wildcard_matching("a", "a"))
string = "baaabab"
print(wildcard_matching(string, "***"))
print(wildcard_matching(string, "a*ab")) # False
print(wildcard_matching(string, "ba*a?"))
print(wildcard_matching(string, "baaa?ab"))
print(wildcard_matching(string, "*****ba*****ab"))
|
9119084ee6a7f510f481c56f72d6524edbaefe58 | mittgaurav/Pietone | /battleship.py | 1,820 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 13:05:37 2020
leetcode.com/discuss/interview-question/538068/
@author: gaurav
"""
def get_tuple(N, this):
"""given row digits and col char
returns the unique tuple number"""
row, col = get_row_col(this)
return get_tuple_2(N, row, col)
def get_row_col(this):
"""return tuple of row and col
from '12A', '1A', etc. strs"""
return int(this[:-1]), ord(this[-1]) - ord('A')
def get_tuple_2(N, row, col):
"""for everything figured out"""
return (N * (row - 1)) + col
def solution(N, S, T):
"""given battleship locations and
hits, get number of ships totally
sunk and only hit but not sunk"""
# determine ships
ships = S.split(',')
# determine hits - for each ship how many hit
hits = T.split(' ')
hits = set([get_tuple(N, h) for h in hits])
ships_sunk = 0
ships_hit = 0
for ship in ships:
# for each ship, figure out ends
this = ship.split(' ')
left_row, left_col = get_row_col(this[0])
right_row, right_col = get_row_col(this[1])
# determine all tuples for this ship
ship_locs = []
for row in range(left_row, right_row + 1):
for col in range(left_col, right_col + 1):
ship_locs.append(get_tuple_2(N, row, col))
# Now, determine if all
# locations in this hit
ship_locs = set(ship_locs)
ship_hits = ship_locs.intersection(hits)
if len(ship_hits) == len(ship_locs):
ships_sunk += 1
elif len(ship_hits) > 0:
ships_hit += 1
return f'{ships_sunk},{ships_hit}'
print(solution(4, '1B 2C,2D 4D', '2B 2D 3D 4D 4A') == '1,1')
print(solution(3, '1A 1B,2C 2C', '1B') == '0,1')
print(solution(12, '1A 2A,12A 12A', '12A') == '1,0')
|
51dcdbe9d528b1c4f5de18838e678b24ccff3a07 | mittgaurav/Pietone | /largest_square_submatrix.py | 4,727 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 9 01:26:49 2018
@author: gaurav
[False, True, False, False],
[True, True, True, True],
[False, True, True, False],
for each elem, collect four values:
* Continuous true horizontally
* Continuous true vertically
* Minimum of continuous true
horizontally, vertically, or
diagonally. This tells exact
size of square matrix that's
ending at this very element.
* The overall maximum square
matrix size till this point.
[[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1]]
[[1, 1, 1, 1], [2, 2, 1, 1], [1, 3, 1, 1], [1, 4, 1, 1]]
[[0, 0, 0, 1], [3, 1, 1, 1], [2, 2, 2, 2], [0, 0, 0, 2]]
Though, we can easily remove
4th elems. Instead, maintain
a global max.
"""
matrix = list()
def square_submatrix(input):
"""given a matrix, find the
largest square matrix with
all vals equal to true"""
for i in range(0, len(input) + 1):
matrix.insert(i, list())
matrix[i].insert(0, [0, 0, 0, 0])
for j in range(0, len(input[0]) + 1):
matrix[0].insert(j, [0, 0, 0, 0])
m = 0
for i in range(1, len(input) + 1):
for j in range(1, len(input[0]) + 1):
arr = list()
if input[i-1][j-1]:
"""True"""
# horizontal
arr.append(1 + matrix[i-1][j][0])
# vertical
arr.append(1 + matrix[i][j-1][1])
# Size of matrix
# at this point.
arr.append(min(arr[0], arr[1],
1 + matrix[i-1][j-1][2]))
else:
"""False"""
arr.append(0)
arr.append(0)
arr.append(0)
# The overall maximum size
# of matrix seen till now.
arr.append(max(arr[2], matrix[i-1][j-1][3],
matrix[i-1][j][3], matrix[i][j-1][3]))
# we can have running max
m = max(arr[3], m)
# or keep within memoizer
matrix[i].insert(j, arr)
# both should nonetheless be same
assert(m == matrix[len(input)][len(input[0])][3])
return m
def square_submatrix_short(input):
"""I don't need to keep so
many values. Instead keep
only the maximum.
Quite similar to finding
longest True series in an
array. You maintain local
size and a global max one
"""
matrix = [[0 for _ in range(len(input[0])+1)] for _ in
range(len(input) + 1)]
m = 0
for i in range(1, len(input) + 1):
for j in range(1, len(input[0]) + 1):
if input[i-1][j-1]:
# if current val is True
# then we can add on to
# existing size. Min of
# left, right, and diag
val = 1 + min(matrix[i-1][j],
matrix[i][j-1],
matrix[i-1][j-1])
else:
val = 0
matrix[i][j] = val
m = max(m, val)
return m
matrix = []
print(square_submatrix([
[False, True, False, False],
[True, True, True, True],
[False, True, True, False],
]))
matrix = []
print(square_submatrix_short([
[False, True, False, False],
[True, True, True, True],
[False, True, True, False],
]))
print("-----")
matrix = []
print(square_submatrix([
[True, True, True, True, True],
[True, True, True, True, False],
[True, True, True, True, False],
[True, True, True, True, False],
[True, False, False, False, False]
]))
matrix = []
print(square_submatrix_short([
[True, True, True, True, True],
[True, True, True, True, False],
[True, True, True, True, False],
[True, True, True, True, False],
[True, False, False, False, False]
]))
print("-----")
matrix = []
print(square_submatrix([
[True, True, True, True, True],
[True, True, True, True, False],
[True, False, True, True, False],
[True, True, True, True, False],
[True, False, False, False, False]
]))
matrix = []
print(square_submatrix_short([
[True, True, True, True, True],
[True, True, True, True, False],
[True, False, True, True, False],
[True, True, True, True, False],
[True, False, False, False, False]
]))
print("-----")
|
eb1bf679c48940bbc2bf157675287e9c71f14e7a | mittgaurav/Pietone | /tree.py | 6,327 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
tree.py
- Tree (Binary Tree)
- Bst
"""
class Tree():
"""Binary tree"""
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def max_level(self):
"""height of tree"""
return max(self.left.max_level() if self.left else 0,
self.right.max_level() if self.right else 0) + 1
@classmethod
def tree(cls):
"""return a demo binary tree"""
return Tree(1,
Tree(2, Tree(4), Tree(3)),
Tree(6, Tree(6, Tree(0), Tree(7))))
@classmethod
def tree2(cls):
"""return another demo binary tree"""
return Tree(2,
Tree(1, Tree(4), Tree(3)),
Tree(5, Tree(6, Tree(0), Tree(7))))
@classmethod
def str_node_internal(cls, nodes, level, levels):
"""internal of prints"""
ret = ''
if len([x for x in nodes if x is not None]) == 0:
return ret
floor = levels - level
endge_lines = int(pow(2, max(floor - 1, 0)))
first_spaces = int(pow(2, floor) - 1)
between_spaces = int(pow(2, floor + 1) - 1)
ret += first_spaces * ' '
new_nodes = list()
for node in nodes:
if node is not None:
ret += str(node.data)
new_nodes.append(node.left)
new_nodes.append(node.right)
else:
ret += ' '
new_nodes.append(None)
new_nodes.append(None)
ret += between_spaces * ' '
ret += '\n'
for i in range(1, endge_lines + 1):
for node in nodes:
ret += (first_spaces - i) * ' '
if node is None:
ret += ((endge_lines * 2) + i + 1) * ' '
continue
if node.left is not None:
ret += '/'
else:
ret += ' '
ret += (i + i - 1) * ' '
if node.right is not None:
ret += '\\'
else:
ret += ' '
ret += ((endge_lines * 2) - i) * ' '
ret += '\n'
ret += cls.str_node_internal(new_nodes, level + 1, levels)
return ret
def __str__(self):
levels = self.max_level()
return self.str_node_internal([self], 1, levels)
def __repr__(self):
return str(self.data)
def __len__(self):
"""num of nodes"""
return ((len(self.left) if self.left else 0) +
(len(self.right) if self.right else 0) + 1)
class Bst(Tree):
"""Binary Search Tree"""
def __init__(self, data=None, left=None, right=None):
Tree.__init__(self, data, left, right)
@classmethod
def bst(cls):
"""return demo BST"""
return Bst(4,
Bst(1, Bst(0), Bst(3)),
Bst(8, Bst(6, Bst(5), Bst(7))))
@classmethod
def bst2(cls):
"""another demo BST"""
return Tree(4,
Tree(3, Tree(0), Tree(3)),
Tree(5, None, Tree(7, Tree(6), Tree(9))))
tree = bst
tree2 = bst2
def insert(self, data):
"""insert into BST"""
if self.data is None:
self.data = data
return
if data > self.data:
if self.right is None:
self.right = Bst(data)
return
return self.right.insert(data)
if data <= self.data:
if self.left is None:
self.left = Bst(data)
return
return self.left.insert(data)
def find(self, data):
"""find node that
got data in BST"""
if self.data == data:
return self
elif self.data > data:
if self.left is not None:
return self.left.find(data)
elif self.data < data:
if self.right is not None:
return self.right.find(data)
return None
def find_node_and_parent(self, data, parent=None):
"""find node and
parent in bst"""
if self.data == data:
return self, parent
elif self.data > data:
if self.left:
return self.left.find_node_and_parent(data, self)
elif self.data < data:
if self.right:
return self.right.find_node_and_parent(data, self)
return None, None
def find_max_and_parent(self, parent=None):
"""max val in BST"""
if self.right:
return self.right.find_max_and_parent(self)
return self, parent
def find_min_and_parent(self, parent=None):
"""min val in BST"""
if self.left:
return self.left.find_min_and_parent(self)
return self, parent
def delete(self, data):
"""delete node from BST"""
node, parent = self.find_node_and_parent(data, None)
if node is None:
return
if node.left:
# replace with just smaller
can, par = node.left.find_max_and_parent(node)
new_data = can.data
if par:
# delete just smaller
par.delete(new_data)
else:
# left itself is just smaller
node.left = None
node.data = new_data
return
if node.right:
can, par = node.right.find_min_and_parent(node)
new_data = can.data
if par:
par.delete(new_data)
else:
node.right = None
node.data = new_data
return
# if no children
if parent is None:
# root. There is nothing
node.data = None
return
# which child exists?
if parent.left is node:
parent.left = None
else: # parent.right is node
parent.right = None
def inorder(self, result=[]):
"""in order traversal"""
self.left.inorder(result) if self.left else None
result.append(self.data)
self.right.inorder(result) if self.right else None
return result
|
e586a1f9e60722c8aa1949a9c1aa9f2404fa683e | PhirayaSripim/Python | /Week2/test2.6.py | 1,019 | 3.765625 | 4 | price=[[25,30,45,55,60],[45,45,75,90,100],[60,70,110,130,140]]
car = [" 4 ล้อ "," 6 ล้อ ","มากกว่า 6 ล้อ "]
print( " โปรแกรมคำนวณค่าผ่านทางมอเตอร์เวย์\n---------------")
print(" รถยนต์ 4 ล้อ กด 1\nรถยนต์ 6 ล้อ กด 2\nรถยนต์มากกว่า 6 ล้อ กด 3\n")
a=int(input("เลือกประเภทยานพหนะ : "))
print(car[a-1])
print("ลาดกระบัง----->บางบ่อ "+str(price[a-1][0])+" บาท")
print("ลาดกระบัง----->บางประกง "+str(price[a-1][1])+" บาท")
print("ลาดกระบัง----->พนัสนิคม "+str(price[a-1][2])+" บาท")
print("ลาดกระบัง----->บ้านบึง "+str(price[a-1][3])+" บาท")
print("ลาดกระบัง----->บางพระ "+str(price[a-1][4])+" บาท") |
2abbde87690a9670e0dd672daa22ae9e4c7afeb7 | PhirayaSripim/Python | /Week2/test2.3.py | 126 | 3.609375 | 4 | friend= ['jan','cream','phu','bam','orm','pee','bas','kong','da','james']
friend[9]="may"
friend[3]="boat"
print (friend[3:8]) |
184bc3285b8669680b305faafcb8099d2464b9cd | renatomayoral/ClickAutomation | /WAtest.py | 1,558 | 3.75 | 4 | #WhatApp Desktop App mensage sender
import pyautogui as pg
import time
print(pg.position())
screenWidth, screenHeight = pg.size() # Get the size of the primary monitor.
currentMouseX, currentMouseY = pg.position() # Get the XY position of the mouse.
pg.moveTo(471, 1063) # Move the mouse to XY coordinates.
pg.click() # Click the mouse.
time.sleep(10) # makes program execution pause for 10 sec
pg.moveTo(38, 244) # Move the mouse to XY coordinates.
pg.click(38, 244) # Move the mouse to XY coordinates and click it. """
time.sleep(3) # makes program execution pause for 3 sec
pg.write('Bom dia Lindinha!!', interval=0.20) # type with quarter-second pause in between each key
pg.press('enter') # Press the enter key. All key names are in pyautogui.KEY_NAMES
""" pyautogui.click('button.png') # Find where button.png appears on the screen and click it.
pyautogui.doubleClick() # Double click the mouse.
pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easeInOutQuad) # Use tweening/easing function to move mouse over 2 seconds.
pyautogui.press('esc') # Press the Esc key. All key names are in pyautogui.KEY_NAMES
pyautogui.keyDown('shift') # Press the Shift key down and hold it.
pyautogui.press(['left', 'left', 'left', 'left']) # Press the left arrow key 4 times.
pyautogui.keyUp('shift') # Let go of the Shift key.
pyautogui.hotkey('ctrl', 'c') # Press the Ctrl-C hotkey combination.
pyautogui.alert('This is the message to display.') # Make an alert box appear and pause the program until OK is clicked. """ |
e0e4e39fd90e6e7bb8024ff3636229043ae63b40 | eddylongshanks/repl-code | /Week 1 Example Code/_week1-program.py | 1,984 | 4.125 | 4 |
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def details(self):
return "Name: " + self.name + "\nAge: " + str(self.age) +"\n"
def __str__(self):
return "Name: " + self.name + "\nAge: " + str(self.age) +"\n"
def __repr__(self):
return "User(name, age)"
# Inherit from User
class Admin(User):
def details(self):
return "Name: " + self.name + " (Admin)\nAge: " + str(self.age) +"\n"
# __str__ will return this line when calling the class. eg: print(user1)
def __str__(self):
return "Name: " + self.name + " (Admin)\nAge: " + str(self.age) +"\n"
def __repr__(self):
return "Admin(User)"
class Users:
def __init__(self):
self.users = []
def AddUser(self, user):
# Check for the type of the object to determine admin status
if user is type(Admin):
user = Admin(user.name, user.age)
elif user is type(User):
user = User(user.name, user.age)
self.users.append(user)
def GetUsers(self):
print("There are {0} users\n".format(str(len(self.users))))
for user in self.users:
print(user.details())
def __str__(self):
return "There are {0} users\n".format(str(len(self.users)))
def __repr__(self):
return "Users()"
users = Users()
numberOfUsers = int(input("How many users do you want to add?: "))
userCount = 1
while userCount <= numberOfUsers:
name = input("What is the name of user " + str(userCount) + "?: ")
age = input("What is the age of user " + str(userCount) + "?: ")
# Create a new user with the accepted information
currentUser = User(name, age)
# Add new user to the list
users.AddUser(currentUser)
userCount += 1
# Create an admin user and add to the list
admin = Admin("Chris", 30)
users.AddUser(admin)
# List the current users
users.GetUsers()
|
40f6f3affe328fbe149f7766be75a7774acbf709 | careywalker/networkanalysis | /CommunityEvaluation/utilities/calculate_modularity.py | 1,118 | 3.984375 | 4 | """This uses Newman-Girwan method for calculating modularity"""
import math
import networkx as nx
def calculate_modularity(graph, communities):
"""
Loops through each community in the graph
and calculate the modularity using Newman-Girwan method
modularity: identify the set of nodes that intersect with each
other more frequently than expected by random chance
"""
modularity = 0
sum_of_degrees_in_community = 0
number_of_edges_in_community = 0
number_of_edges_in_network = nx.number_of_edges(graph)
for community in communities:
number_of_edges_in_community = len(nx.edges(nx.subgraph(graph, community)))
for key, value in nx.subgraph(graph, community).degree().items():
sum_of_degrees_in_community += value
community_modularity = (
number_of_edges_in_community / number_of_edges_in_network
) - math.pow((sum_of_degrees_in_community/(2*number_of_edges_in_network)), 2)
modularity += community_modularity
sum_of_degrees_in_community = 0
return modularity
|
c174f8baea2ae06e4772c33599bc0de062bef842 | robertvari/pycore-210612-alapok-1 | /07_lists.py | 620 | 4 | 4 | my_name = "Tom"
my_age = 34
# indexes: 0 1 2 3
my_numbers = [23, 56, 12, 46]
# mixed list
my_list = [
"Robert",
"Csaba",
"Christina",
32,
3.14,
my_name,
my_age,
my_numbers
]
# print(my_list[7][-1])
# print(my_list[0])
# add items to list
my_numbers.append("Csilla")
print(my_numbers)
my_numbers.insert(2, "Laci")
print(my_numbers)
# remove item from list
my_numbers.remove(56)
print(my_numbers)
del my_numbers[2]
print(my_numbers)
del my_numbers[my_numbers.index("Csilla")]
print(my_numbers)
print("Csilla" in my_numbers)
# clear
my_numbers.clear()
print(my_numbers) |
c5b88df5ed908065732058806f386d7b9f723d7e | robertvari/pycore-210612-alapok-1 | /12_list_comprehension.py | 190 | 3.5 | 4 | number_list = [1, 2, 3, 4, 5]
# result_list = []
#
# for i in number_list:
# result_list.append(i+100)
result_list = [ i*i for i in number_list ]
print(number_list)
print(result_list) |
2fc3dc75d5a35af8a8890e8b2f7613ef00bcefbd | robertvari/pycore-210612-alapok-1 | /08_sets.py | 405 | 3.828125 | 4 | # cast list into a set
my_list = [1, 2, 3, "csaba", 4, "csaba", 2, 1]
my_set = set(my_list)
# print(my_set)
# add items to set
new_set = {1, 2, 3}
# print(new_set)
new_set.add(4)
# print(new_set)
# add more items to set
new_set.update([5, 6, 7, 8])
# print(new_set)
new_set.remove(5)
new_set.discard(7)
# print(new_set)
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B)
print(A & B)
print(A - B) |
d0bad2d90258f1654b588b956d926a2203ea59a3 | dinoivusic/Python-Challenges | /day17.py | 351 | 3.515625 | 4 | class Solution:
def longestCommonPrefix(self, strs):
longest = ""
if len(strs) < 1:
return longest
for index, value in enumerate(strs[0]):
longest += value
for s in strs[1:]:
if not s.startswith(longest):
return longest[:index]
return longest
|
a9f01e9a879b0b939d1a8ec99915cc0ec7999fb9 | dinoivusic/Python-Challenges | /day55.py | 275 | 3.515625 | 4 | def longestCommonPrefix(self, strs: List[str]) -> str:
ans = ""
if len(strs) == 0:
return ans
for i in range(len(min(strs))):
can = [s[i] for s in strs]
if (len(set(can)) != 1):
return ans
ans += can[0]
return ans
|
2d3f6ad78b0fccadc9cb575780e9268d9fa94680 | dinoivusic/Python-Challenges | /day24.py | 597 | 3.578125 | 4 | #One line solution
def cakes(recipe, available):
return min(available.get(k, 0)/recipe[k] for k in recipe)
#Longer way of solving it
def cakes(recipe, available):
new = []
shared = set(recipe.keys() & set(available.keys()))
if not len(shared) == len(recipe.keys()) and len(shared) == len(available.keys()):
print('Not all keys are shared')
if len(recipe.keys()) > len(available.keys()):
return 0
for key in available.keys():
if key in recipe.keys():
res = available[key]//recipe[key]
new.append(res)
return sorted(new)[0] |
03e81f455a5d2bab66078ff4c210da966c8958de | dinoivusic/Python-Challenges | /day35.py | 222 | 3.609375 | 4 | def overlap(arr,num):
count = 0
for i in range(len(arr)):
if arr[i][0] == num or arr[i][1] == num:
count+=1
if num > arr[i][0] and num < arr[i][1]:
count+=1
return count
|
b220260f33cd97cb8f1216bdad813af73adc0137 | dinoivusic/Python-Challenges | /day64.py | 527 | 4.03125 | 4 | #Create a function that return the output of letters multiplied by the int following them
import re
def multi(arr):
chars = re.findall('[A-Z]', arr)
digits = re.findall('[0-9]+', arr)
final= ''.join([chars[i]* int(digits[i]) for i in range(0,len(chars)-1)]) + chars[-1]
return final
print(multi('A4B5C2'))
def chars(arr):
extra =''
for char in arr:
if char.isdigit():
extra += extra[-1]* (int(char)-1)
else:
extra += char
return extra
print(chars('A4B5C2'))
|
1ccb257f02a30bb948940670626b3a713e863934 | dinoivusic/Python-Challenges | /day18.py | 173 | 3.515625 | 4 | class Solution:
def isPalindrome(self, strs):
s = [c.lower() for c in strs if c.isalnum()]
if s == s[::-1]:
return True
return False
|
dd054af1ca07948f20cc5e126da501ad227da02e | aqueed-shaikh/submissions | /7/islam_yaseen/app.py | 741 | 3.5 | 4 |
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return """<h1>This is the home page </h1>
<p><a href="/about">about</a> page</p>
<p><a href="/who">who</a> page</p>
<p><a href="http://www.youtube.com/watch?v=unVQT_AB0mY">something</a> to watch</p>
"""
@app.route("/who")
@app.route("/who/<name>")
def name(name="default"):
page = """
<h1> the page name </h1>
This is a page with someone's name
<hr>
The name is:
"""
page=page+name+"<hr>"
return page
@app.route("/about")
def about():
return """<h1>This is the about page</h1>
<p> go <a href="/who/YASEEN!">here!</a></p>
"""
if __name__=="__main__":
app.debug=True
app.run(host="0.0.0.0",port=5005)
|
c12604df95e476146dd984c1b6ddf7ae3453492d | aqueed-shaikh/submissions | /7/han_jason/HW1.py | 1,130 | 3.53125 | 4 | #!/usr/bin/python
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "<h1>Hello World.</h1>\n<h2>More headings</h2>\n<b>Bold stuff</b>"
@app.route("/about")
def about():
return "<h1>I am cookie monster. Nom nom nom nom.</h1>"
@app.route("/color")
def color():
return """
<body style='background-color:blue;'>
<h1 style='background-color:white;'>White and blue.</h1>
</body>
"""
@app.route("/table")
def table():
return """<table border='2'>
<tr>
<td>Yo this is the story</td>
<td>All about how</td>
<td>My life got flip turned</td>
<td>Upside down</td>
</tr>
<tr>
<td>I forget the rest of this song</td>
<td>Oh well</td>
<td>This is a table</td>
<td>wee</td>
</tr>
</table>"""
@app.route("/link")
def link():
return """<a href="http://www.google.com"></a>"""
@app.route("/list")
def list():
return """The difference between ul and ol\n
<ul>
<li>This is an unordered list</li>
<li>Stuff</li>
<li>more stuff</li>
<li>even more stuff</li>
<li>aight that's about it</li>
</ul>
<ol>
<li>This list has order.</li>
<li>wee</li>
"""
if __name__ == "__main__":
app.run()
|
bdeab1439c982ce0a142980a1bd868a00caac17f | aqueed-shaikh/submissions | /6/lin_jing/HW1.py | 449 | 4.0625 | 4 | #!/usr/bin/python
#Factorization of Input Number
def main():
try:
a = int(raw_input("Enter a number: "))
except ValueError:
print("That is not a number!")
return 0
String = "The Factors of %d are " % (a)
Counter = int(a**.5)
for i in range(2, Counter):
if(a == (a / i) * i):
a = a / i
String += "%d %d" % (a, i)
print(String)
if __name__ == "__main__":
main()
|
362923f31d00353c0ddd2640101ae9d80e427e77 | aqueed-shaikh/submissions | /6/kozak_severyn/3_madlibs/app.py | 871 | 3.609375 | 4 | #!/usr/bin/python
"""
Team: Severyn Kozak (only)
app, a Python Flask application, populates a template .html
file's empty fields with a randomized selection of words.
Think madlibs.
"""
from flask import Flask, render_template
from random import sample
app = Flask(__name__)
#dictionary of word arrays, by type
wordPool = {'Object' : ['greatsword', 'chalice', 'stacks'],
'Verb' : ['pilfer', 'hike', 'dungeoneer'],
'Place' : ['barrio', 'The Wall', 'Sao Tome'],
'Adjective' : ['black', 'svelte', 'gaunt']}
@app.route("/")
#populates template with a shuffled copy of wordPool
def madlib():
words = {'O': sample(wordPool['Object'], 3),
'V': sample(wordPool['Verb'], 3),
'P': sample(wordPool['Place'], 3),
'A': sample(wordPool['Adjective'], 3)}
return render_template("template.html", words = words)
if __name__ == "__main__":
app.run(debug = True)
|
865e77608165c48b254aa4fbbfbcee48e65c79c2 | aqueed-shaikh/submissions | /6/kurtovic_benjamin/stuff.py | 2,061 | 3.9375 | 4 | #! /usr/bin/env python
# I'm not sure how to demonstrate my knowledge best, so here's an example of
# some really esoteric concepts in the form of metaclasses (because I can).
import sys
import time
class CacheMeta(type):
"""Caches the return values of every function in the child class."""
def __new__(cls, name, bases, values):
def use_cache(func):
"""Wraps a function to use the caching system."""
def wrapper(self, *args):
key = (func, args)
if key in self._cache:
return self._cache[key]
result = func(self, *args)
self._cache[key] = result
return result
return wrapper
for key, func in values.iteritems():
if callable(func):
values[key] = use_cache(func)
values["_cache"] = {}
return super(CacheMeta, cls).__new__(cls, name, bases, values)
class WithoutCache(object):
"""Some time-consuming methods that don't use a cache."""
def fib(self, n):
"""Calculates the nth Fibonacci number inefficiently."""
if n <= 2:
return 1
return self.fib(n - 1) + self.fib(n - 2)
class WithCache(object):
"""Some time-consuming methods that use a cache."""
__metaclass__ = CacheMeta
def fib(self, n):
"""Calculates the nth Fibonacci number efficiently."""
if n <= 2:
return 1
return self.fib(n - 1) + self.fib(n - 2)
def test():
n = 35
classes = [(WithoutCache(), "without"), (WithCache(), "with")]
for obj, desc in classes:
print "First %i Fibonacci numbers %s cache:\n\t" % (n, desc),
for i in xrange(1, n + 1):
if i == n:
t1 = time.time()
sys.stdout.write(str(obj.fib(i)) + (" "))
sys.stdout.flush()
if i == n:
t2 = time.time()
print "\n\t%.8f seconds to find %ith number" % (t2 - t1, n)
print
if __name__ == "__main__":
test()
|
66d0e4aed34979127e18bf88bd2010461028acc4 | aqueed-shaikh/submissions | /7/herman_hunter/hermanroar.py | 433 | 3.71875 | 4 | import random
<<<<<<< HEAD
for x in range(0, random.randrange(0, 999)):
print "I AM HERMAN HEAR ME ROAR"
print "meow"
=======
total_fear = 0
for x in range(0, random.randrange(1, 999)):
print "I AM HERMAN NUMBER %i HEAR ME ROAR"%(x*x)
num = random.randrange(100, 450)
print "fear level: %i"%num
total_fear += num
print "meow. total fear: %i"%total_fear
>>>>>>> 995de77d830fc93d8ab5ff0588b1f4956391aa3c
|
2ca884ecd48eb25176d5f0a315371e9464710f89 | aqueed-shaikh/submissions | /7/chung_victoria/test.py | 576 | 3.625 | 4 | #!/usr/bin/python
def problemOne():
sum = 0
i = 1
while i < 1000:
if i % 3 == 0 or i % 5 == 0:
sum += i
i+=1
print sum
def problemTwo():
sum = 2
a = 1
b = 2
term = 2
while term <= 4000000:
term = a + b
a = b
b = term
if term % 2 == 0:
sum += term
print sum
def problemThree():
answer = 0;
for first in range (100, 999):
for second in range (100, 999):
product = first * second
if str(product) == str(product)[::-1]:
if product > answer:
answer = product
print answer
# problemOne()
# problemTwo()
problemThree()
|
34067bf118ee70d6f07d4499db7015d3b4dee808 | aqueed-shaikh/submissions | /6/Luo_Jason/Hello.py | 414 | 3.890625 | 4 | #!/usr/bin/python
def fact (n):
if n == 0:
return 1
else:
return n * fact(n-1)
print fact (5)
def fib (n):
count = 0
if n == 1:
return count + 0
elif n == 2:
return count + 1
else:
return count + fib(n-1) + fib(n-2)
print fib(10)
def isPrime(n):
last = False
if n % 2 == 0:
return not last
return last
print isPrime(3)
|
c25ee297552465456ca50c12ce5df934c9d399bf | IsaacMarovitz/ComputerSciencePython | /MontyHall.py | 2,224 | 4.28125 | 4 | # Python Homework 11/01/20
# In the Monty Hall Problem it is benefical to switch your choice
# This is because, if you switch, you have a rougly 2/3 chance of
# Choosing a door, becuase you know for sure that one of the doors is
# The wrong one, otherwise if you didnt switch you would still have the
# same 1/3 chance you had when you made your inital guess
# On my honour, I have neither given nor received unauthorised aid
# Isaac Marovitz
import random
num_simulations = 5000
no_of_wins_no_switching = 0
no_of_wins_switching = 0
# Runs Monty Hall simulation
def run_sim(switching):
games_won = 0
for _ in range(num_simulations):
# Declare an array of three doors each with a tuple as follows (Has the car, has been selected)
doors = [(False, False), (False, False), (False, False)]
# Get the guess of the user by choosing at random one of the doors
guess = random.randint(0, 2)
# Select a door at random to put the car behind
door_with_car_index = random.randint(0, 2)
# Change the tuple of that door to add the car
doors[door_with_car_index] = (True, False)
# Open the door the user didn't chose that doesn't have the car behind it
for x in range(2):
if x != door_with_car_index and x != guess:
doors[x] = (False, True)
# If switching, get the other door that hasn't been revealed at open it, otherwise check if
# the current door is the correct one
if switching:
for x in range(2):
if x != guess and doors[x][1] != True:
games_won += 1
else:
if guess == door_with_car_index:
games_won += 1
return games_won
# Run sim without switching for first run
no_of_wins_no_switching = run_sim(False)
# Run sim with switching for the next run
no_of_wins_switching = run_sim(True)
print(f"Ran {num_simulations} Simulations")
print(f"Won games with switching: {no_of_wins_switching} ({round((no_of_wins_switching / num_simulations) * 100)}%)")
print(f"Won games without switching: {no_of_wins_no_switching} ({round((no_of_wins_no_switching / num_simulations) * 100)}%)")
|
d5abb3795766226e51caba8f079af04c9c5cb7cf | IsaacMarovitz/ComputerSciencePython | /IfStatements2.py | 1,219 | 3.921875 | 4 | # Python Homework 09/16/2020
import sys
try:
float(sys.argv[1])
except IndexError:
sys.exit("Error: No system arguments given\nProgram exiting")
except ValueError:
sys.exit("Error: First system argument must be a float\nProgram exiting")
user_score = float(sys.argv[1])
if user_score < 0 or user_score > 5:
sys.exit("Error: First system argument must be greater than 0 or less than 5\nProgram exiting")
def get_user_score(user_score):
if user_score <= 1:
return "F"
elif user_score <= 1.33:
return "D-"
elif user_score <= 1.67:
return "D"
elif user_score <= 2:
return "D+"
elif user_score <= 2.33:
return "C-"
elif user_score <= 2.67:
return "C"
elif user_score <= 3:
return "C+"
elif user_score <= 3.33:
return "B-"
elif user_score <= 3.67:
return "B"
elif user_score <= 4:
return "B+"
elif user_score <= 4.33:
return "A-"
elif user_score <= 4.67:
return "A"
else:
return "A+"
print(f"Your score is {get_user_score(user_score)}")
input("Press ENTER to exit")
# On my honour, I have neither given nor received unauthorised aid
# Isaac Marovitz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.