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 |
|---|---|---|---|---|---|---|
bcd6ddba72d2fe2c22112c11f6dbea95fe536d37 | shamim-ahmed/udemy-python-masterclass | /section-12/examples/example_kwargs.py | 323 | 4.3125 | 4 | #!/usr/bin/env python
def print_keyworded_arguments(arg1, **kwargs):
print("arg1 = {}".format(arg1))
for key, value in kwargs.items():
print("{} = {}".format(key, value))
# you can mix keyworded args with non-keyworded args
print_keyworded_arguments("Hello", fruit="Apple", number=10, planet="Jupiter")
|
43836b3fe753f9a651cd9f6cbc636c462cd63c81 | shamim-ahmed/udemy-python-masterclass | /section-4/examples/guessinggame4.py | 416 | 4.0625 | 4 | #!/usr/bin/env python
import random
done = False
while done == False:
answer = random.randrange(1, 11)
guess = int(input("Please enter a number between 1 and 10: "))
if guess == answer:
print("Your guess is correct. The answer is {}".format(answer))
done = True
else:
print("Sorry, your guess was not correct. Please try again")
print()
print("Have a nice day!")
|
f6008700b5aafa0c7f732e3d5e701832554017a7 | alihaiderrizvi/Leetcode-Practice | /all/29-Divide Two Integers/solution.py | 634 | 3.5625 | 4 | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
if dividend > 0:
div_sign = 0
else:
div_sign = 1
if divisor > 0:
dvs_sign = 0
else:
dvs_sign = 1
dividend = abs(dividend)
divisor = abs(divisor)
ans = dividend // divisor
if (div_sign == 1 and dvs_sign == 1) or (div_sign == 0 and dvs_sign == 0):
if ans > 2**31 -1:
ans = 2**31 -1
return ans
else:
if ans < -2**31:
ans = -2**31
return -ans
|
4ec2bd94203ef8db68cd0039227d84bc4ea4c62e | alihaiderrizvi/Leetcode-Practice | /all/20-Valid Parenthesis/solution.py | 457 | 3.828125 | 4 | class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 != 0:
return False
stk = []
for i in s:
if i == "(" or i == "[" or i == "{":
stk.append(i)
elif stk and ((i == ")" and stk[-1] == "(") or (i == "]" and stk[-1] == "[") or (i == "}" and stk[-1] == "{")):
stk.pop()
else:
return False
return not stk
|
7cae510cb7d7080ad784927bf19c07b3220aa64e | alihaiderrizvi/Leetcode-Practice | /all/720- Longest Word in Dictionary/720- Longest Word in Dictionary.py | 728 | 3.515625 | 4 | class Solution:
def longestWord(self, words: List[str]) -> str:
s = set(words)
good = set()
for word in words:
n = len(word)
flag = True
while n >= 1:
if word[:n] not in s:
flag = False
n -= 1
if flag:
good.add(word)
good = list(good)
d = {}
for i in good:
if len(i) not in d:
d[len(i)] = [i]
else:
d[len(i)].append(i)
max_count = max(list(d.keys()))
main_ans = d[max_count]
main_ans.sort()
return main_ans[0]
|
ffb117397ed8532cd62567473b9fea61de0e3ee6 | Frankyyoung24/SequencingDataScientist | /Algrithms/week2/bm_algorithm.py | 1,283 | 3.5 | 4 | def boyer_moore(p, p_bm, t):
"""
Do Boyer-Moore matching.
p = pattern, t = text, p_bm = Boyer-Moore object for p (index)
"""
i = 0 # track where we are in the text
occurrences = [] # the index that p match t
while i < len(t) - len(p) + 1:
# loop though all the positions in t where p should start
shift = 1
mismatched = False
for j in range(len(p) - 1, -1, -1):
# the 3rd word '-1' means we're going backwards
if not p[j] == t[i + j]: # when we have a mismatch
# calculate the bad character rule and good suffix rule to see
# how many bases we can skip
skip_bc = p_bm.bad_character_rule(j, t[i + j])
skip_gs = p_bm.good_suffix_rule(j)
# calculate the max shift bases.
shift = max(shift, skip_bc, skip_gs)
mismatched = True
break
if not mismatched: # if there is no mismatch.
occurrences.append(i)
# if there is no mismatch we don't need to use the
# bad_character_rule
skip_gs = p_bm.match_skip()
shift = max(shift, skip_gs)
i += shift # add the value of shift to i
return occurrences
|
617cd19401efd048959af80295b6a2fef88a15b6 | Amo123456/Assignment-submission | /project assignment/Project 1.py | 755 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Develop a cryptography app using python?
# In[9]:
from cryptography.fernet import Fernet
def generate_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("Secret.key","wb")as key_file:
key_file.write(key)
def load_key():
"""
Load the previously generated key
"""
return open("Secret.key","rb").read()
def encrypt_message(message):
"""
Encrypts a message
"""
key = load_key()
encoded_message = message.encode()
f = Fernet(key)
encrypted_message = f.encrypt(encoded_mmessage)
print(encrypted_mmessage)
if __name__ == "__main__":
encrypt_message("encrypt this message")
# In[ ]:
|
e6f7d7097cd80230a9374bfa5067e0759030ba45 | setu-parekh/Interactive-Programming-in-Python-Coursera | /Project 4: Arcade game - Pong/pong_game.py | 4,341 | 3.84375 | 4 | # Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_HEIGHT = HEIGHT / 2
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
ball_pos = [WIDTH / 2, HEIGHT /2 ]
ball_vel = [(random.randrange(120, 240)/60.0),-(random.randrange(60, 180)/60.0)]
right_dir = 'True'
paddle1_pos = float(HEIGHT/2)
paddle2_pos = float(HEIGHT/2)
paddle1_vel = 0.0
paddle2_vel = 0.0
score1 = 0
score2 = 0
# helper function that spawns a ball by updating the
# ball's position vector and velocity vector
# if right is True, the ball's velocity is upper right, else upper left
def ball_init(right_dir):
global ball_pos, ball_vel # these are vectors stored as lists
ball_pos = [WIDTH / 2, HEIGHT /2 ]
ball_vel[1] = -(random.randrange(60, 180)/60.0)
if right_dir:
ball_vel[0] = -(random.randrange(120, 240)/60.0)
else:
ball_vel[0] = (random.randrange(120, 240)/60.0)
# define event handlers
def new_game():
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are floats
global score1, score2 # these are ints
right_dir = 'True'
paddle1_pos = float(HEIGHT/2)
paddle2_pos = float(HEIGHT/2)
paddle1_vel = 0.0
paddle2_vel = 0.0
score1 = 0
score2 = 0
ball_init(right_dir)
def draw(c):
global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel
a = -1.1
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]
# update ball
if ball_pos[1] <= BALL_RADIUS:
ball_vel[1] = - ball_vel[1]
elif (HEIGHT - ball_pos[1])<= BALL_RADIUS:
ball_vel[1] = - ball_vel[1]
right_dir = (ball_vel[0] > 0)
if (ball_pos[0]-PAD_WIDTH <= BALL_RADIUS):
if ((paddle1_pos-HALF_PAD_HEIGHT)<= ball_pos[1]<=(paddle1_pos+HALF_PAD_HEIGHT)):
ball_vel[0] = a * ball_vel[0]
else:
score2 += 1
ball_init(right_dir)
elif ((WIDTH - ball_pos[0]) <= BALL_RADIUS + PAD_WIDTH):
if ((paddle2_pos- HALF_PAD_HEIGHT)<= ball_pos[1]<=(paddle2_pos+HALF_PAD_HEIGHT)):
ball_vel[0] = a * ball_vel[0]
else:
score1 += 1
ball_init(right_dir)
score1_s = str(score1)
score2_s = str(score2)
# update paddle's vertical position, keep paddle on the screen
if ((paddle1_pos + paddle1_vel >= HALF_PAD_HEIGHT) and ((paddle1_pos + paddle1_vel + HALF_PAD_HEIGHT) <= HEIGHT)):
paddle1_pos += paddle1_vel
if ((paddle2_pos+paddle2_vel >= HALF_PAD_HEIGHT) and ((paddle2_pos+paddle2_vel + HALF_PAD_HEIGHT) <= HEIGHT)):
paddle2_pos += paddle2_vel
# draw mid line and gutters
c.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
c.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
c.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
# draw paddles
c.draw_line([HALF_PAD_WIDTH,(paddle1_pos-HALF_PAD_HEIGHT)],[HALF_PAD_WIDTH,(paddle1_pos + HALF_PAD_HEIGHT)],PAD_WIDTH, "White")
c.draw_line([WIDTH - HALF_PAD_WIDTH,(paddle2_pos- HALF_PAD_HEIGHT)],[WIDTH - HALF_PAD_WIDTH,(paddle2_pos + HALF_PAD_HEIGHT)],PAD_WIDTH, "White")
# draw ball and scores
c.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")
c.draw_text(score1_s,[150,100], 50, "Yellow")
c.draw_text(score2_s,[400,100], 50, "Yellow")
def keydown(key):
global paddle1_vel, paddle2_vel
if key == simplegui.KEY_MAP['w']:
paddle1_vel = -2.0
elif key == simplegui.KEY_MAP['s']:
paddle1_vel = 2.0
elif key == simplegui.KEY_MAP['up']:
paddle2_vel = -2.0
elif key == simplegui.KEY_MAP['down']:
paddle2_vel = 2.0
def keyup(key):
global paddle1_vel, paddle2_vel
if key == simplegui.KEY_MAP['w']:
paddle1_vel = 0.0
elif key == simplegui.KEY_MAP['s']:
paddle1_vel = 0.0
elif key == simplegui.KEY_MAP['up']:
paddle2_vel = 0.0
elif key == simplegui.KEY_MAP['down']:
paddle2_vel = 0.0
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.add_button("Restart", new_game, 100)
# start frame
frame.start()
|
94dea85884bca08feccbf1c68e3bcc3388af668e | JosephLimWeiJie/algoExpert | /prompt/medium/MinHeightBST.py | 2,135 | 3.59375 | 4 | import unittest
def minHeightBst(array):
return constructMinHeightBST(array, 0, len(array) - 1)
def constructMinHeightBST(array, startIdx, endIdx):
if (startIdx > endIdx):
return None
midIdx = (startIdx + endIdx) // 2
bst = BST(array[midIdx])
bst.left = constructMinHeightBST(array, startIdx, midIdx - 1)
bst.right = constructMinHeightBST(array, midIdx + 1, endIdx)
return bst
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if value < self.value:
if self.left is None:
self.left = BST(value)
else:
self.left.insert(value)
else:
if self.right is None:
self.right = BST(value)
else:
self.right.insert(value)
def inOrderTraverse(tree, array):
if tree is not None:
inOrderTraverse(tree.left, array)
array.append(tree.value)
inOrderTraverse(tree.right, array)
return array
def validateBst(tree):
return validateBstHelper(tree, float("-inf"), float("inf"))
def validateBstHelper(tree, minValue, maxValue):
if tree is None:
return True
if tree.value < minValue or tree.value >= maxValue:
return False
leftIsValid = validateBstHelper(tree.left, minValue, tree.value)
return leftIsValid and validateBstHelper(tree.right, tree.value, maxValue)
def getTreeHeight(tree, height=0):
if tree is None:
return height
leftTreeHeight = getTreeHeight(tree.left, height + 1)
rightTreeHeight = getTreeHeight(tree.right, height + 1)
return max(leftTreeHeight, rightTreeHeight)
class TestProgram(unittest.TestCase):
def test_case_1(self):
array = [1, 2, 5, 7, 10, 13, 14, 15, 22]
tree = minHeightBst(array)
self.assertTrue(validateBst(tree))
self.assertEqual(getTreeHeight(tree), 4)
inOrder = inOrderTraverse(tree, [])
self.assertEqual(inOrder, [1, 2, 5, 7, 10, 13, 14, 15, 22])
if __name__ == '__main__':
unittest.main() |
047b6808f400db0906409e22fb7e3897f9bda51a | kirillrssu/pythonintask | /PMIa/2014/Samovarov/task_3_17.py | 810 | 4.1875 | 4 | #Задача №3, Вариант 7
#Напишите программу, которая выводит имя "Симона Руссель", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
#Samovarov K.
#25.05.2016
print("Герой нашей сегодняшней программы - Симона Руссель")
psev=input("Под каким же именем мы знаем этого человека? Ваш ответ:")
if (psev)==("Мишель Морган"):
print ("Все верно: Симона Руссель - "+psev)
else:
print("Вы ошиблись, это не его псевдоним.")
input(" Нажмите Enter для выхода") |
b40e51de38b2a5a3721f823e707b4bf526e1aefc | tioguil/LingProg | /-Primeira Entrega/Exercicio01 2018_08_14/atv1.py | 208 | 4.0625 | 4 | # 1 Faça um Programa que peça o raio de um círculo, calcule e
# mostre sua área.
raio = 0
print("Digite o Raio do circulo")
raio = int(input())
area = 3.14 * raio**2
print("Área do circulo: %s" %(area)) |
34a43cd286f6018aee4d23a683ee1e6211db43f1 | tioguil/LingProg | /-Primeira Entrega/Exercicio03 2018_08_28/atv18.py | 268 | 3.65625 | 4 | # 18. A série de Fibonacci é formada pela seqüência
# 1,1,2,3,5,8,13,21,34,55,... Faça um programa capaz de gerar a série
# até o n−ésimo termo.
a = 0
b = 1
n = int(input("Quantidade: "))
for i in range(n):
print(a)
aux = b
b = a + b
a = aux |
6820cd52316dc5bca7f89c75c7e7a1a6972981dd | tioguil/LingProg | /-Primeira Entrega/Exercicio03 2018_08_28/atv12.py | 1,154 | 4.09375 | 4 | # 12. Uma fruteira está vendendo frutas com a seguinte tabela de
# # preços:
# # Até 5 Kg Acima de 5 Kg
# # Morango R$ 2,50 por Kg R$ 2,20 por Kg
# # Maçã R$ 1,80 por Kg R$ 1,50 por Kg
# # Se o cliente comprar mais de 8 Kg em frutas ou o valor total da
# # compra ultrapassar R$ 25,00, receberá ainda um desconto de 10%
# # sobre este total. Escreva um algoritmo para ler a quantidade (em
# # Kg) de morangos e a quantidade (em Kg) de maças adquiridas e
# # escreva o valor a ser pago pelo cliente.
list = {"morango":[2.50,2.20], "maca": [1.80, 1.50]}
morango = float(input("qunatidade em kg de morando: "))
maca = float(input("qunatidade em kg de maça: "))
if morango <= 5:
valor_morando = list["morango"][0]
else:
valor_morando = list["morango"][1]
if maca <=5:
valor_maca = list["maca"][0]
else:
valor_maca = list["maca"][1]
total_kg = morango + maca
total_valor = (morango * valor_morando) + (maca * valor_maca)
if total_kg > 8 or total_valor > 25:
desconto = total_valor * 0.10
print("valor da total da compra com desconto: ",( total_valor -desconto))
else:
print("valor total da compra: ", total_valor) |
5b577b07f4542809d54f9b64631cf258fcfcce8a | tioguil/LingProg | /-Primeira Entrega/Exercicio01 2018_08_14/atv7.py | 961 | 3.65625 | 4 | # João Papo-de-Pescador, homem de bem, comprou um
# microcomputador para controlar o rendimento diário de seu
# trabalho. Toda vez que ele traz um peso de peixes maior que o
# estabelecido pelo regulamento de pesca do estado de São Paulo (50
# quilos8 deve pagar uma multa de R$ 4,00 por quilo excedente. João
# precisa que você faça um programa que leia a variável peso (peso
# de peixes8 e verifque se há excesso. Se houver, gravar na variável
# excesso e na variável multa o valor da multa que João deverá pagar.
# Caso contrário mostrar tais variáveis com o conteúdo ZERO.
excesso =0
multa = 0.0
print("digitar peso do Peixe")
peso = float(input())
if peso > 50:
excesso = peso - 50
multa = excesso*4
print("peso excedido: %s KG - valor da multa: %s R$" %(excesso, multa))
print("peso informado: ",peso, "KG")
else:
print("Não houve excesso de peso - peso excedido: ",excesso,"KG")
print("Peso: %s KG- Multa %s R$" %(peso, multa)) |
33377065d8e963885d95fa94d891b11720bb44e9 | tioguil/LingProg | /-Primeira Entrega/Exercicio02 2018_08_21/atv05.py | 321 | 4.0625 | 4 | # 5 Escreva um programa que conta a quantidade de vogais em uma
# string e armazena tal quantidade em um dicionário, onde a chave é
# a vogal considerada.
print("entre com a frase")
frase = input()
frase = frase.lower()
vogais = 'aeiou'
dicionario = {i: frase.count(i) for i in vogais if i in frase}
print(dicionario) |
5d35beb083b9d0eff0c68ee9d8575431b5d6fb70 | tioguil/LingProg | /-Primeira Entrega/Exercicio01 2018_08_14/atv11.py | 574 | 3.78125 | 4 | # 11 Faça um programa que solicite a data de nascimento
# (dd/mm/aaaa8 do usuário e imprima a data com o nome do mês por
# extenso.
# Data de Nascimento: 29/10/1973
# Você nasceu em 29 de Outubro de 1973.
# Obs.: Não use desvio condicional nem loops.
import datetime
print("Informe sua data de nascimento ex: 01/01/2018")
nascimento = input()
ano,mes,dia = map(int, nascimento.split('/'))
tipo_date = datetime.date(dia, mes, ano)
data = tipo_date.strftime('%d/%B/%Y')
dia, mes,ano = map(str, data.split('/'))
print ("Você nasceu em %s de %s de %s" %(dia, mes,ano)) |
b16820e8981e0acd4bb8d117ee31925e97f29dc2 | tioguil/LingProg | /-Primeira Entrega/Exercicio03 2018_08_28/atv11.py | 1,018 | 4.09375 | 4 | # 11. Faça um programa que faça 5 perguntas para uma pessoa
# sobre um crime. As perguntas são:
# "Telefonou para a vítima?"
# "Esteve no local do crime?"
# "Mora perto da vítima?"
# "Devia para a vítima?"
# "Já trabalhou com a vítima?"
# O programa deve no fnal emitir uma classifcação sobre a
# participação da pessoa no crime. Se a pessoa responder
# positivamente a 2 questões ela deve ser classifcada como
# "Suspeita", entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso
# contrário, ele será classifcado como "Inocente".
list = []
list.append(input("Telefonou para a vítima? (s/n): "))
list.append(input("Esteve no local do crime? (s/n): "))
list.append(input("Mora perto da vítima? (s/n): "))
list.append(input("Devia para a vítima? (s/n): "))
list.append(input("Já trabalhou com a vítima? (s/n): "))
total = list.count("s")
if total == 2:
print("Suspeita")
elif total == 3 or total == 4:
print("Cúmplice")
elif total == 5:
print("Assassino")
else:
print("Inocente") |
9f73c064597a294823c10d6e511d4ddaacb55790 | dcassells/Rumour-Animation | /animated_rumour.py | 4,940 | 3.6875 | 4 | """
==================
Animated histogram
==================
Use a path patch to draw a bunch of rectangles for an animated histogram.
from terminal write:
python animated_rumour.py #number_of_nodes #number_of_initial_infective
"""
import sys
#import argparse
#parser = argparse.ArgumentParser(
# description = 'Simulation of rumour model in Maki and Thompson (1973) to show proportion of population never hearing a rumour\n\n'+
# 'usage is: python animated_rumour.py #number_of_nodes #number_of_initial_infective',
# epilog = 'Should converge to 0.203 - A. Sudbury (1985)')
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import matplotlib.animation as animation
# Fixing random state for reproducibility
#np.random.seed(19680801)
# initialise number of nodes and number of initial infective
if len(sys.argv) < 2:
# number of nodes
num = 100
# number of initial infective
i_0 = 10
elif len(sys.argv) < 3:
# number of nodes
num = int(sys.argv[1])
# number of initial infective
i_0 = 10
else:
# number of nodes
num = int(sys.argv[1])
# number of initial infective
i_0 = int(sys.argv[2])
# define spread function
def spread():
# count of infective
I = i_0
# count of susceptible
S = num - i_0
# initial state of nodes
nodes = ['s']*num
for i in range(i_0):
nodes[i] = 'i'
# run until no infective
while I != 0 and S != 0:
# caller
u = np.random.randint(num)
# receiver
v = np.random.randint(num)
# is u infective
if nodes[u] == 'i':
# is v suscpetible
if nodes[v] == 's':
# change v from susceptible to infected
nodes[v] = 'i'
# one more infective
I += 1
# one less susceptible
S -= 1
# else v is infective or removed
else:
# change u from infective to removed
nodes[u] = 'r'
# one less infective
I -= 1
return S/num
# histogram our data with numpy
initial = [1]*100
n, bins = np.histogram(initial, 100, density=True, range=(0,1))
data = [spread()]
# get the corners of the rectangles for the histogram
left = np.array(bins[:-1])
right = np.array(bins[1:])
bottom = np.zeros(len(left))
top = bottom + n
nrects = len(left)
###############################################################################
# Here comes the tricky part -- we have to set up the vertex and path codes
# arrays using ``plt.Path.MOVETO``, ``plt.Path.LINETO`` and
# ``plt.Path.CLOSEPOLY`` for each rect.
#
# * We need 1 ``MOVETO`` per rectangle, which sets the initial point.
# * We need 3 ``LINETO``'s, which tell Matplotlib to draw lines from
# vertex 1 to vertex 2, v2 to v3, and v3 to v4.
# * We then need one ``CLOSEPOLY`` which tells Matplotlib to draw a line from
# the v4 to our initial vertex (the ``MOVETO`` vertex), in order to close the
# polygon.
#
# .. note::
#
# The vertex for ``CLOSEPOLY`` is ignored, but we still need a placeholder
# in the ``verts`` array to keep the codes aligned with the vertices.
nverts = nrects * (1 + 3 + 1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5, 0] = left
verts[0::5, 1] = bottom
verts[1::5, 0] = left
verts[1::5, 1] = top
verts[2::5, 0] = right
verts[2::5, 1] = top
verts[3::5, 0] = right
verts[3::5, 1] = bottom
###############################################################################
# To animate the histogram, we need an ``animate`` function, which runs the
# spread() function and updates the locations of the vertices for the
# histogram (in this case, only the heights of each rectangle). ``patch`` will
# eventually be a ``Patch`` object.
patch = None
def animate(i):
# simulate new data coming in
data.append(spread())
n, bins = np.histogram(data, 100, density=True, range=(0,1))
top = bottom + n
verts[1::5, 1] = top
verts[2::5, 1] = top
print(str(i)+': ',np.mean(data))
return [patch, ]
###############################################################################
# And now we build the `Path` and `Patch` instances for the histogram using
# our vertices and codes. We add the patch to the `Axes` instance, and setup
# the `FuncAnimation` with our animate function.
fig, ax = plt.subplots()
barpath = path.Path(verts, codes)
patch = patches.PathPatch(
barpath, facecolor='green', edgecolor='yellow', alpha=0.5)
ax.add_patch(patch)
ax.set_xlim(0, 0.5)
ax.set_ylim(bottom.min(), top.max())
ax.set_xlabel('$S/n$')
ax.set_ylabel('Density')
ax.set_title('Distribution of the proportion never hearing the rumour\n for '+str(num)+' nodes and $i_0$ = '+str(i_0))
ani = animation.FuncAnimation(fig, animate, 200, repeat=False, blit=True)
# use .save() to save
#ani.save('rumour.mp4',dpi=250)
# use plt.show() to display
plt.show()
|
7e848517d2ba88ba39d23220858eb341a601d66d | Sullivannichols/classes | /csc321/hw/hw4/parse.py | 2,055 | 3.59375 | 4 | #!/usr/bin/env python3
import csv
import socket
import pygraphviz as pgv
def domains():
''' This function extracts domain names from a .tsv file, performs a
forward DNS lookup on each domain, performs a reverse DNS lookup on
each returned IP, then adds all of the info to a graph.
'''
g = pgv.AGraph()
with open('domains.tsv', newline='') as tsvfile:
tsvin = csv.DictReader(tsvfile, delimiter='\t')
print("domains.tsv loaded into dictionary")
for line in tsvin:
# Forward Lookup
domain = line['domain']
g.add_node(domain)
print("node added for " + domain)
try:
ips = socket.gethostbyname_ex(domain)
except socket.gaierror:
print("socket.gaierror: nodename nor servname provided")
continue
# Reverse Lookup
for item in ips[2]:
noerror = True
try:
result = socket.gethostbyaddr(item)
result = result[0]
result = result.split(".")
result = ".".join(len(result[-2]) < 4 and\
result[-3:] or result[-2:])
except IndexError:
print('IndexError')
noerror = False
continue
except socket.herror:
print('socket.herror')
noerror = False
continue
except:
print('REVERSE DNS ERROR for ' + result)
noerror = False
continue
if noerror:
# add nodes
g.add_node(result)
g.add_edge(domain, result)
print("node added for " + result)
print("edge added between " + domain + " and " + result)
g.layout(args='-Goverlap=false')
g.draw('simple.png')
if __name__ == '__main__':
domains()
|
e53f2538cd20c70b5a7a04de4f714f2077194c65 | cyrusv/Birthday-Problems | /puzzle2.py | 386 | 3.53125 | 4 | # Puzzle 2
# Do Men or Women take longer Hubway rides in Boston?
# By how many seconds? Round the answer DOWN to the nearest integer.
# Use the Hubway data from 2001-2013 at http://hubwaydatachallenge.org/
import pandas as pd
df = pd.DataFrame(pd.read_csv('hubway_trips.csv'))
mean = df.groupby('gender')['duration'].mean()
print df
print mean
print round(abs(mean[1] - mean[0]), 0)
|
8eddcd6f8233db0f57f508f7dc69dc7acc870aea | yubaoliu/PythonFromScratch | /basics/directory.py | 1,518 | 3.890625 | 4 | import os
import tempfile
# define the access rights
access_rights = 0o755
print("===========================")
print("Creating a Directory ")
# define the name of the directory to be created
path = "/tmp/year"
print("Create directory: %s" % path)
try:
os.mkdir(path, access_rights)
except OSError as error:
print(error)
print("Creation of the directory %s failed" % path)
else:
print("Successfully created the directory %s" % path)
print("===========================")
print("Creating a Directory with Subdirectories")
path = "/tmp/year/month/week/day"
print("Create directory (mkdir -p): %s" % path)
try:
os.makedirs(path, access_rights)
except OSError as error:
print(error)
print("Creation of the directory %s failed" % path)
else:
print("Successfully created the directory %s" % path)
# print("===========================")
# print("create a temporary directory")
# with tempfile.TemporaryFile() as directory:
# print('The created temporary directory is %s' % directory)
print("===========================")
path = "/tmp/year"
print("Delete directory: %s" % path)
try:
if os.path.exists(path):
os.rmdir(path)
except OSError as error:
print(error)
print("Deletion of the directory %s failed" % path)
else:
print("Successfully deleted the directory %s" % path)
print("===========================")
path = "/tmp/year"
print("Simple method: %s" % path)
print("Delete directory: %s" % path)
if os.path.exists(path):
os.system("rm -r /tmp/year")
|
753239b3b82d38acc5ef487a3c2b29a0344a7584 | SarcoImp682/Zookeeper | /Topics/Program with numbers/Difference of times/main.py | 391 | 3.953125 | 4 | # put your python code here
# start time
hour_start = int(input())
minutes_start = int(input())
seconds_start = int(input())
# stop time
hour_stop = int(input())
minutes_stop = int(input())
seconds_stop = int(input())
# conversion
start = hour_start * 3600 + minutes_start * 60 + seconds_start
stop = hour_stop * 3600 + minutes_stop * 60 + seconds_stop
# result
print(abs(start - stop))
|
9ad802d0eac6567184e459e7ce6f4e82bf8110c0 | agupta7/COMP6700 | /softwareprocess/test/AngleTest.py | 4,471 | 3.875 | 4 | import unittest
import softwareprocess.Angle as A
class AngleTest(unittest.TestCase):
def setUp(self):
self.strDegreesFormatError = "String should in format XdY.Y where X is degrees and Y.Y is floating point minutes"
# ---------
# ----Acceptance tests
# ----100 Constructor
# ----Boundary value confidence
# ----input : string containing the degrees and minutes in the form XdY.Y for X is degrees Y.Y is minutes
# ----output : an instance of Angle
# ----Happy path analysis:
# degreeMinutesStr -> nominal value = 50d30.9
# degreeMinutesStr -> low value = -10d0.0
# degreeMinutesStr -> high value = 999d59.9
# ---Sad path analysis
# degreeMinutesStr -> None / not specified
# degreeMinutesStr -> '' empty string
# degreeMinutesStr -> '0d60.0' minutes is too high
# degreeMinutesStr -> '0d-0.1' minutes is too low
# degreeMintuesStr -> '0.5d10.0' degrees is non integer
# degreeMinutesStr -> '1ad10.0' wrong format
# degreeMintuesStr -> '12d1' minutes must have decimal
# degreeMinutesStr -> '12d12.0m' minutes in the wrong format
def test100_010_ShouldConstructAngle(self):
angle = A.Angle('50d30.9')
self.assertIsInstance(angle, A.Angle)
self.assertEquals(angle.getDegreeMinuteString(), '50d30.9')
self.assertAlmostEquals(angle.getDegreesFloat(), 50.515, 3)
def test100_020_ShouldConstructAngleLow(self):
angle = A.Angle('-10d0.0')
self.assertIsInstance(angle, A.Angle)
self.assertEquals(angle.getDegreeMinuteString(), '-10d0.0')
self.assertAlmostEquals(angle.getDegreesFloat(), -10, 3)
def test100_030_ShouldConstructAngleHigh(self):
angle = A.Angle('999d59.9')
self.assertIsInstance(angle, A.Angle)
self.assertEquals(angle.getDegreeMinuteString(), '999d59.9')
self.assertAlmostEquals(angle.getDegreesFloat(), 999.99833, 3)
def test100_040_ShouldConstructAngleInteger(self):
angle = A.Angle(12.5)
self.assertIsInstance(angle, A.Angle)
self.assertEquals(angle.getDegreeMinuteString(), '12d30.0')
self.assertEquals(angle.getDegreesFloat(), 12.5)
def test100_050_ShouldConstructAngleNegative(self):
angle = A.Angle('-0d03.0')
self.assertIsInstance(angle, A.Angle)
self.assertEquals(angle.getDegreeMinuteString(), '-0d3.0')
self.assertAlmostEquals(angle.getDegreesFloat(), -(3.0/60), 3)
def test100_060_ShouldCOnstructAngleOverflow(self):
angle = A.Angle(13.999999999)
self.assertIsInstance(angle, A.Angle)
self.assertEquals(angle.getDegreeMinuteString(), '14d0.0')
self.assertAlmostEquals(angle.getDegreesFloat(), 13.999999999, 3)
def test900_010_ShouldErrorNoneAngle(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle(None)
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_030_ExceptionBlankAngle(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_040_ExceptionMinutesHigh(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('0d60.0')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_050_ExceptionMinutesLow(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('0d-0.1')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_060_ExceptionNonIntegerDegree(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('0.5d10.0')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_070_ExceptionDegreeInvalidFormat(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('1ad10.0')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_080_ExceptionMinutesInvalidFormat(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('12d1')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError)
def test900_090_ExceptionMinutesWrongFormat(self):
with self.assertRaises(ValueError) as ctx:
angle = A.Angle('12d12.0m')
self.assertEquals(ctx.exception.args[0], self.strDegreesFormatError) |
6093dccc4f5ed895fb8f69572589deb55c086102 | talivaro/Generadores-aleatorios | /CongruCombinado.py | 417 | 3.8125 | 4 | __author__ = 'Talivaro'
xo1=int(input("Ingrese el valor de xo1: "))
xo2=int(input("Ingrese el valor de xo2: "))
xo3=int(input("Ingrese el valor de xo3: "))
repe=int(input("Numero de valores: "))
for i in range(repe):
xn1=float((171*xo1)%30269)
xn2=float((172*xo2)%30307)
xn3=float((173*xo3)%30323)
ui=float(((xn1/30269)+(xn2/30307)+(xn3/30323))%1)
print(ui)
xo1=xn1;
xo2=xn2;
xo3=xn3;
|
a6b2127082c3e3eccf8098d8e370d701c5a876db | BlackMetall/trash | /lesson 9 (practice1).py | 959 | 4.1875 | 4 | #Задача 1. Курьер
#Вам известен номер квартиры, этажность дома и количество квартир на этаже.
#Задача: написать функцию, которая по заданным параметрам напишет вам,
#в какой подъезд и на какой этаж подняться, чтобы найти искомую квартиру.
room = int(input('Введите номер квартиры ')) # кол-во квартир
floor = int(5) # кол-во этажей
roomfloor = int(3) # кол-во квартир на этаже
c = floor * roomfloor # кол-во квартир в подъезде
x = room // c
y = (x + 1) # узнаём в каком подъезде квартира
z = room % c
d = z // roomfloor
s = (d + 1) # узнаём на каком этаже
print(str(y) + ' Подъезд')
print(str(s) + ' Этаж') |
a40410c97ef48d989ce91b6d23262720f60138dc | rajeshberwal/dsalib | /dsalib/Stack/Stack.py | 1,232 | 4.25 | 4 | class Stack:
def __init__(self):
self._top = -1
self.stack = []
def __len__(self):
return self._top + 1
def is_empty(self):
"""Returns True is stack is empty otherwise returns False
Returns:
bool: True if stack is empty otherwise returns False
"""
return self._top == -1
def push(self, data):
"""Add data at the end of the stack.
Args:
data (Any): element that we want to add
"""
self.stack.append(data)
self._top += 1
def pop(self):
"""Remove the last element from stack and returns it's value.
Raises:
IndexError: If stack is empty raise an Index error
Returns:
Any: element that we have removed from stack"""
if self.is_empty():
raise IndexError("stack is empty")
self._top += 1
return self.stack.pop()
def peek(self):
"""returns the current top element of the stack."""
if self.is_empty():
raise IndexError("stack is empty")
return self.stack[self._top]
def __str__(self):
return ''.join([str(elem) for elem in self.arr])
|
04d70de92bfca1f7b293f344884ec1e23489b7e4 | rajeshberwal/dsalib | /dsalib/Sorting/insertion_sort.py | 547 | 4.375 | 4 | def insertion_sort(array: list) -> None:
"""Sort given list using Merge Sort Technique.
Time Complexity:
Best Case: O(n),
Average Case: O(n ^ 2)
Worst Case: O(n ^ 2)
Args:
array (list): list of elements
"""
for i in range(1, len(array)):
current_num = array[i]
for j in range(i - 1, -1, -1):
if array[j] > current_num:
array[j], array[j + 1] = array[j + 1], array[j]
else:
array[j + 1] = current_num
break |
a0f2d86b20acd3f19756667801f081902827b8d7 | Manoj-sahu/datastructre | /Stack/StackUsingList.py | 414 | 3.875 | 4 | class StackUsingList():
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def peek(self):
return self.stack[-1]
def pop(self):
self.stack.pop()
if __name__ == '__main__':
stack = StackUsingList()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.peek())
stack.pop()
print(stack.peek()) |
8c7ab2d2161d94f612f7102e05c04c8e4e888a71 | Manoj-sahu/datastructre | /LinkedList/1.1.py | 1,083 | 3.53125 | 4 | """for finding duplicate first approach iterate to loop and maintain count in dictionary
and if you find then remove the refrence of that loop. brute force approcah could be take head item and keep checking for all the items"""
#import IP.LinkedList.10
#from IP.LinkedList.L import LinkedList
import L
newLinkedList = L.LinkedList()
newLinkedList.insertAtStart(1)
newLinkedList.insertAtEnd(2)
newLinkedList.insertAtEnd(2)
def removeDup(n):
dupList = []
previous = None
while(n is not None):
if n.data in dupList:
previous.next = n.next
else:
dupList.append(n.data)
previous = n
n = n.next
def removeDupWT(n):
current = n
while current is not None:
runner = current
while( runner.next is not None):
if runner.next.data == current.data:
runner.next = runner.next.next
else:
runner = runner.next
current = current.next
#removeDup(newLinkedList.head)
removeDupWT(newLinkedList.head)
newLinkedList.traverseList()
|
7d1221ec5c9cdbb8435ecaf0be51a6daa11ae3d2 | nishthagoel712/DSA | /Graph/TopologicalSorting.py | 575 | 3.828125 | 4 | from collections import defaultdict
visited=defaultdict(bool)
stack=[]
def topological_sort_util(adj,vertex):
visited[vertex]=True
for node in adj[vertex]:
if not visited[node]:
topological_sort_util(adj,node)
stack.append(vertex)
def topological_sort(adj):
for vertex in adj:
if not visited[vertex]:
topological_sort_util(adj,vertex)
return stack[::-1]
adj=defaultdict(list)
m=int(input())
for _ in range(m):
a,b=input().split()
adj[a].append(b)
print(*topological_sort(adj)) |
3009a3a33a23b282111c2fc0fba9cf050e0fe599 | nishthagoel712/DSA | /Dynamic Programming/Maximum size reactangle of all 1's.py | 1,543 | 3.59375 | 4 | # arr represent given 2D matrix of 0's and 1's
# n is the number of rows in a matrix
# m is the number of columns in each row of a matrix
def rectangle(arr, n, m):
maxi = float("-inf")
temp = [0] * m
for i in range(n):
for j in range(m):
if arr[i][j] == 0:
temp[j] = 0
else:
temp[j] += arr[i][j]
w = histogram(temp)
if w > maxi:
maxi = w
return maxi
def histogram(a):
s = []
maxarea = float("-inf")
for j in range(len(a)):
if len(s) < 1:
s.append(j)
elif a[j] >= a[s[-1]]:
s.append(j)
else:
while len(s) > 0 and a[s[-1]] > a[j]:
b = s.pop()
if len(s) < 1:
area = a[b] * j
if area > maxarea:
maxarea = area
else:
area = a[b] * (j - s[-1] - 1)
if area > maxarea:
maxarea = area
s.append(j)
j = j + 1
while len(s) > 0:
b = s.pop()
if len(s) < 1:
area = a[b] * j
if area > maxarea:
maxarea = area
else:
area = a[b] * (j - s[-1] - 1)
if area > maxarea:
maxarea = area
return maxarea
n = 4
m = 6
arr = [[1, 0, 0, 1, 1, 1], [1, 0, 1, 1, 0, 1], [0, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1]]
print(rectangle(arr, n, m)) |
fc89a46754b7a31c7335517bc4b639aa5eab6e12 | darksinge/rmb-search-engine | /bill_files/clean_empty_bills.py | 471 | 3.6875 | 4 | import glob, os
"""
Simple script to detect and remove files that have no information on them in this folder
"""
"""
files = glob.glob('*.txt')
for file in files:
f = open(file, 'r')
contents = f.read()
should_delete = False
if 'The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.' in\
contents:
should_delete = True
f.close()
if should_delete:
os.remove(file)
"""
|
93a955fcd9477724d916877075fac5b29227857a | darksinge/rmb-search-engine | /create_sparse_matrix.py | 3,142 | 3.703125 | 4 | """
Creates a sparse inverse dictionary for tf-idf searches. The CSV file produced by bill_data_analysis.py is so large
that this file is needed to produce something much smaller to be used for the searches
"""
import pandas as pd
import os
import json
import pickle
import sys
from default_path import default_path
def make_matrix(matrix_file=None):
"""
Takes an already saved dense matrix (csv format) and creates a dictionary with each word as a key and a dictionary
of docs and tf_idf values as the value.
Parameters:
matrix_file: a path string for a csv dense matrix file. The first column must include the name of the documents
and the rest be for terms, otherwise an error will be thrown.
Returns:
dictionary: A sparse matrix dictionary for each term in the dense matrix.
"""
if matrix_file:
dense_matrix = pd.read_csv(matrix_file)
else:
dense_matrix = pd.read_csv(os.path.join(default_path, "analysis", "dense_matrix.csv"))
terms = dense_matrix.columns
dense_matrix = dense_matrix.rename(columns = {terms[0]: "doc"})
sparse_matrix = {}
for term in terms[1:]:
doc_matches = dense_matrix[dense_matrix[term] > 0]
just_docs_and_values = doc_matches[["doc", term]]
just_docs_and_values.set_index("doc", inplace=True)
just_docs_and_values.reset_index()
transposed = just_docs_and_values.transpose()
doc_dictionary = transposed.to_dict("list")
if len(doc_dictionary) > 0:
sparse_matrix[term] = doc_dictionary
return sparse_matrix
def make_matrix_json(matrix_file=None):
"""
Takes the file name of a csv for the dense matrix, and creates and saves a json with a sparse matrix.
Parameters:
matrix_file: a path string for a csv dense matrix file. The first column must include the name of the documents
and the rest be for terms, otherwise an error will be thrown.
Returns:
None
"""
full_matrix = make_matrix(matrix_file)
# TODO: still save a pre-built matrix, load that up, rebuild the new data
matrix_json = json.dumps(full_matrix)
file = open(os.path.join(default_path, "analysis", "sparse.json"), 'w')
file.write(matrix_json)
file.close()
def reverse_matrix(matrix):
from collections import OrderedDict
"""
Takes a sparse matrix, reverses the inner dictionary into OrderedDictionary objects
:param matrix:
:return:
"""
new_matrix = {}
for term, outer_dict in matrix.items():
sorted_inner = OrderedDict(sorted(outer_dict.items(), key=lambda t: t[1]), reverse=True)
new_matrix[term] = sorted_inner
return new_matrix
def make_pickle(matrix_file=None):
"""
Reads the dense_matrix.csv file (or a file given as an argument) and creates a matrix
Returns:
None
"""
matrix = make_matrix(matrix_file)
pickle.dump(matrix, open(os.path.join(default_path, "analysis", "sparse_p.pickle"), 'wb'))
if __name__ == '__main__':
#make_matrix_json()
make_pickle()
#data = reverse_matrix(data)
#make_pickle(data)
|
22e56d8ab2a43434aac7d3c8c5aa589a3af5b2c5 | kori07/prak_asd_b | /UAS_044_047_053/aplikasi.py | 20,086 | 3.828125 | 4 | #Program by Kelompok Susi Triana Wati,Program Pencarian Serta Pengurutan dengan Bubble Sort.
from Tkinter import Tk,Frame,Menu
from Tkinter import*
import tkMessageBox as psn
import ttk
import tkFileDialog as bk
from tkMessageBox import *
import Tkinter as tk
from winsound import *
import platform
os = platform.system()
class MouseWheel(object): # Kelas untuk mengatur scroolbar
def __init__(self, root, factor = 2):
global os
self.activeArea = None
if type(factor) == int:
self.factor = factor
else:
raise Exception("Factor must be an integer.")
if os == "Linux" :
root.bind_all('<4>', self.onMouseWheel, add='+')
root.bind_all('<5>', self.onMouseWheel, add='+')
else:
# Windows and MacOS
root.bind_all("<MouseWheel>", self.onMouseWheel, add='+')
def onMouseWheel(self,event):
if self.activeArea:
self.activeArea.onMouseWheel(event)
def mouseWheel_bind(self, widget):
self.activeArea = widget
def mouseWheel_unbind(self):
self.activeArea = None
@staticmethod
def build_function_onMouseWheel(widget, orient, factor = 1):
view_command = getattr(widget, orient+'view')
if os == 'Linux':
def onMouseWheel(event):
if event.num == 4:
view_command("scroll",(-1)*factor,"units" )
elif event.num == 5:
view_command("scroll",factor,"units" )
elif os == 'Windows':
def onMouseWheel(event):
view_command("scroll",(-1)*int((event.delta/120)*factor),"units" )
elif os == 'Darwin':
def onMouseWheel(event):
view_command("scroll",event.delta,"units" )
return onMouseWheel
def add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None):
scrollingArea.bind('<Enter>',lambda event: self.mouseWheel_bind(scrollingArea))
scrollingArea.bind('<Leave>', lambda event: self.mouseWheel_unbind())
if xscrollbar and not hasattr(xscrollbar, 'onMouseWheel'):
setattr(xscrollbar, 'onMouseWheel', self.build_function_onMouseWheel(scrollingArea,'x', self.factor) )
if yscrollbar and not hasattr(yscrollbar, 'onMouseWheel'):
setattr(yscrollbar, 'onMouseWheel', self.build_function_onMouseWheel(scrollingArea,'y', self.factor) )
active_scrollbar_on_mouse_wheel = yscrollbar or xscrollbar
if active_scrollbar_on_mouse_wheel:
setattr(scrollingArea, 'onMouseWheel', active_scrollbar_on_mouse_wheel.onMouseWheel)
for scrollbar in (xscrollbar, yscrollbar):
if scrollbar:
scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self.mouseWheel_bind(scrollbar) )
scrollbar.bind('<Leave>', lambda event: self.mouseWheel_unbind())
class simpul():
'''Membuat kelas simpul'''
def __init__(self, data=None):
self.data = data
self.link = None
class Tugas_GUI(Frame):
'''Membuat kelas GUI'''
def __init__(self,parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
self.list = None
# membuat canvas pada frame utama
self.canvas = Canvas(parent, background="grey")
self.frame = Frame(self.canvas, background="purple")
# mengedit style untuk scrollbar
s = ttk.Style()
s.theme_use('classic')
s.configure("coba.Vertical.TScrollbar", foreground = 'pink',background='teal')
# membuat scrollbar pada canvas
self.vsb = ttk.Scrollbar(parent, style="coba.Vertical.TScrollbar", orient="vertical", command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.vsb.set)
self.vsb.pack(side="right", fill="y")
self.canvas.pack(side="left", fill="both", expand=True)
self.canvas.create_window((0,0), window=self.frame, anchor="nw",
tags="self.frame")
self.frame.bind("<Configure>", self.OnFrameConfigure)
# agar scrool bar dapat di scroll
MouseWheel(root).add_scrolling(self.canvas, yscrollbar=self.vsb)
def OnFrameConfigure(self, event):
'''Reset the scroll region to encompass the inner frame'''
self.canvas.configure(scrollregion=self.canvas.bbox("all"),width=400)
def initUI(self):
self.parent.title("Tabel Data Item Di Toko Alat Tulis Kampus")
menubar = Menu(self.parent)
self.parent.config(menu = menubar, bg = 'purple')
# Membuat dan mengatur Button dan frame
self.btnKeluar = Button(self.parent,cursor = 'pirate',text="\n\n\n\nK\n\nE\n\nL\n\nU\n\nA\n\nR\n\n\n\n",
relief=RIDGE, bd=5, bg='burlywood',
fg='red',command=self.onExit)
self.btnKeluar.pack(side=RIGHT, fill=X)
self.btnimpor = Button(self.parent,text="\n\n\n\nI\n\nM\n\nP\n\nO\n\nR\n\nT\n\n\n\n",
relief=RIDGE, bd=5, bg='burlywood',
fg='red',command=self.impor)
self.btnimpor.pack(side=LEFT, fill=X)
fr_atas = Frame(self.parent)
fr_atas.pack(fill = BOTH)
self.btnnomor = Button(fr_atas,text="NO",
bd=1, bg='brown', width=14,
fg='green',command=self.nomor)
self.btnnomor.pack(side=LEFT, fill=BOTH)
self.btnnomor.configure(state=DISABLED)
self.btntanggal = Button(fr_atas,text="TANGGAL CEK",
bd=1, bg='brown',width=14,
fg='green',command=self.nomor)
self.btntanggal.pack(side=LEFT, fill=BOTH)
self.btntanggal.configure(state=DISABLED)
self.btnnama = Button(fr_atas,text="NAMA BARANG",
bd=1, bg='brown',width=14,
fg='green',command=self.nama)
self.btnnama.pack(side=LEFT, fill=BOTH)
self.btnnama.configure(state=DISABLED)
self.btnjumlah = Button(fr_atas,text="JUMLAH BARANG",
bd=1, bg='brown',width=14,
fg='green',command=self.jumlah)
self.btnjumlah.pack(side=LEFT, fill=BOTH)
self.btnjumlah.configure(state=DISABLED)
self.btnharga = Button(fr_atas,text="HARGA BARANG",
bd=1, bg='brown',width=14,
fg='green',command=self.harga)
self.btnharga.pack(side=LEFT, fill=BOTH)
self.btnharga.configure(state=DISABLED)
self.btnmodal = Button(fr_atas,text="MODAL",
bd=1, bg='brown',width=14,
fg='green',command=self.modal)
self.btnmodal.pack(side=LEFT, fill=BOTH)
self.btnmodal.configure(state=DISABLED)
self.btnsales = Button(fr_atas,text="SALES",
bd=1, bg='brown',width=14,
fg='green',command=self.sales)
self.btnsales.pack(side=LEFT, fill=BOTH)
self.btnsales.configure(state=DISABLED)
self.btncari = Button(self.parent,cursor = 'target',text="CARI",
bd=5, bg='burlywood',
fg='red',command=self.carisemua)
self.btncari.pack(side=BOTTOM, fill=X)
self.btncari.configure(state=DISABLED)
self.lblStatus = Button(self.parent,
text='TAMPILKAN',
bd=5,fg='red',bg='pink',command=self.tampilkan)
self.lblStatus.pack(side=BOTTOM, fill=X)
self.lblStatus.configure(state=DISABLED)
def kejadian(self): # Fungsi Mengubah Button menjadi aktif
self.btncari.configure(state=NORMAL)
self.btnnomor.configure(state=NORMAL)
self.btntanggal.configure(state=NORMAL)
self.btnnama.configure(state=NORMAL)
self.btnjumlah.configure(state=NORMAL)
self.btnharga.configure(state=NORMAL)
self.btnmodal.configure(state=NORMAL)
self.btnsales.configure(state=NORMAL)
def carisemua(self): # Fungsi untuk pencarian data
## p=self.list
def show_entry_fields():
coba = []
cek = False
p=self.list
while p.link is not None:
p=p.link
if p.data.no == target.get()or \
p.data.tanggal[:2] == target.get() or p.data.tanggal[3:5] == target.get() or p.data.tanggal[6:] == target.get() or \
p.data.nama == target.get() or \
p.data.jumlah == target.get() or \
p.data.harga == target.get() or \
p.data.modal == target.get() or \
p.data.sales == target.get():
data = (p.data.no,p.data.tanggal,p.data.nama,p.data.jumlah,p.data.harga,p.data.modal,p.data.sales.rstrip('\n'))
coba.append(data)
cek=True
p=self.list
while p.link is not None:
p=p.link
if p.data.no != target.get()and \
p.data.tanggal[:2] != target.get() and p.data.tanggal[3:5] != target.get() and p.data.tanggal[6:] != target.get() and \
p.data.nama != target.get() and \
p.data.jumlah != target.get() and \
p.data.harga != target.get() and \
p.data.modal != target.get() and \
p.data.sales != target.get():
coba.append(('','','','','','',''))
if cek == False:
psn.showwarning("Peringatan !", "Data Tidak Sesuai")
data_tampil = coba
for bariske in range(len(coba)):
baris = data_tampil[bariske]
for kolomke in range(len(coba[0])):
nilai = baris[kolomke]
widget = self._widgets[bariske][kolomke]
widget.configure(text=nilai)
cari = Tk()
cari.title('PENCARIAN DATA')
cari.config(bg='grey')
Label(cari, text="Masukan Data Yang Ingin Di Cari",fg='dark blue',bg='light blue').grid(row=0)
target = Entry(cari)
target.grid(row=0, column=1)
Button(cari, text='batal', command=cari.destroy,bg='#ff0000',fg='white').grid(row=3, column=1, sticky=W, padx=20,ipadx=30,pady=4)
Button(cari, text=' cari ', command=show_entry_fields,bg='red',fg='white').grid(ipadx=30,row=3, column=0, sticky=W, padx=15)
mainloop( )
def diam(self):
pass
def tampilsortir(self): # Fungsi untuk menampilkan hasil sortiran
data_tampil = self.data_mhs
for row in range(self.rows):
baris = data_tampil[row]
for column in range(self.columns):
nilai = baris[column]
widget = self._widgets[row][column]
widget.configure(text=nilai)
############################## pengurutan data menggunakan Bubble Sort ####################################
def bubbleSort(self,Data,indeks):
'''fungsi untuk mengurutkan data dengan Bubble Sort
input berupa list bernama Data'''
n = len(Data) # n adalah jumlah data
#mengurutkan berdasarkan atribut nomor
if indeks == 'nomor':
for k in range(1,n): # ulangi sebanyak n-1 kali
for i in range(n-1): # lakukan dari posisi paling kiri hingga ke kanan
if int(Data[i].data.no) > int(Data[i+1].data.no): # bandingkan dua data yang berdekatan
Data[i], Data[i+1] = Data[i+1], Data[i] # menukar posisi data
#mengurutkan berdasarkan atribut nama
elif indeks == 'nama':
for k in range(1,n):
for i in range(n-1):
if (Data[i].data.nama) > (Data[i+1].data.nama):
Data[i], Data[i+1] = Data[i+1], Data[i]
#mengurutkan berdasarkan atribut jumlah
elif indeks == 'jumlah':
for k in range(1,n):
for i in range(n-1):
if int(Data[i].data.jumlah) > int(Data[i+1].data.jumlah):
Data[i], Data[i+1] = Data[i+1], Data[i]
#mengurutkan berdasarkan atribut harga
elif indeks == 'harga':
for k in range(1,n):
for i in range(n-1):
if int(Data[i].data.harga) > int(Data[i+1].data.harga):
Data[i], Data[i+1] = Data[i+1], Data[i]
#mengurutkan berdasarkan atribut modal
elif indeks == 'modal':
for k in range(1,n):
for i in range(n-1):
if int(Data[i].data.modal) > int(Data[i+1].data.modal):
Data[i], Data[i+1] = Data[i+1], Data[i]
#mengurutkan berdasarkan atribut sales
elif indeks == 'sales':
for k in range(1,n):
for i in range(n-1):
if (Data[i].data.sales) > (Data[i+1].data.sales):
Data[i], Data[i+1] = Data[i+1], Data[i]
def bubble(self,LL,indeks):
'''mengurutkan linked list dengan Bubble Sort
Tricky: dengan mengkonversi linked menjadi array, bubble sort lalu
dikembalikan menjadi array'''
# konversi dari Linked List ke python list
li = []
p = LL.link
while p != None:
li.append(p)
p = p.link
# memanggil fungsi bubble sort
self.bubbleSort(li,indeks)
# konversi dari python list ke Linked List
p = LL
for simpul in li:
p.link = simpul
simpul.link = None
p = p.link
p=LL.link
self.data_mhs = []
while p is not None:
data=(p.data.no,p.data.tanggal,p.data.nama,p.data.jumlah,p.data.harga,p.data.modal,p.data.sales.rstrip('\n'))
self.data_mhs.append(data)
p=p.link
def nomor(self): # Fungsi untuk mengurutkan nomor
data = self.list_tampil
self.bubble(data,'nomor')
self.tampilsortir()
def nama(self): # Fungsi untuk mengurutkan nama barang
data=self.list_tampil
self.bubble(data,'nama')
self.tampilsortir()
def jumlah(self): # Fungsi untuk mengurutkan jumlah barang
data=self.list_tampil
self.bubble(data,'jumlah')
self.tampilsortir()
def harga(self): # Fungsi untuk mengurutkan harga barang
data=self.list_tampil
self.bubble(data,'harga')
self.tampilsortir()
def modal(self): # Fungsi untuk mengurutkan modal
data=self.list_tampil
self.bubble(data,'modal')
self.tampilsortir()
def sales(self): # Fungsi untuk mengurutkan sales
data=self.list_tampil
self.bubble(data,'sales')
self.tampilsortir()
def impor(self): # Funsi untuk mengimport file csv
try :
File = bk.askopenfilename()
x=open(File) # membuka file csv
x.readline() # membaca file csv dengan mengabaikan baris pertama
baca=x.readlines() #membaca semua data file csv dan menjadikannya sebuah list didalam variabel 'baca'
self.list = simpul() #self.list adalah kepala dari linked list yang akan dibuat ==> berisi None
p=self.list
for k in range (len(baca)): #
z=baca[k].split(';') #
L=data_transaksi(z[0],z[1],z[2],z[3],z[4],z[5],z[6]) # membuat isi linked list
p.link=simpul(L) #
p=p.link #
psn.showinfo("Pemberitahuan","import berhasil")
x.close()
self.list_tampil = self.list # membuat duplikat self.list
self.lblStatus.configure(state=NORMAL) # mengaktifkan button tampilkan
except IOError :
psn.showwarning("Pemberitahuan","Import dibatalkan")
except IndexError :
psn.showwarning("Peringatan !","file anda tidak sesuai")
def tampilkan(self): # Fungsi untuk menampilkan data
try :
p=self.list
self.data_mhs = []
while p.link is not None:
data=(p.link.data.no,p.link.data.tanggal,p.link.data.nama,p.link.data.jumlah,p.link.data.harga,p.link.data.modal,p.link.data.sales.rstrip('\n'))
self.data_mhs.append(data)
p=p.link
# bagian yang ditambahkan untuk menampilkan data
self.rows = len(self.data_mhs) # jumlah baris
self.columns = len(self.data_mhs[0]) # jumlah kolom
self._widgets = list()
for row in range(self.rows):
self.current_row = list()
for column in range(self.columns):
tampil = ''
label = Label(self.frame, text="%s" % tampil, width=14, bg = 'black',fg = 'aqua')
label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
self.current_row.append(label)
self._widgets.append(self.current_row)
for column in range(self.columns):
self.grid_columnconfigure(column, weight=1)
self.pack(side="top", fill="x")
# akhir bagian yang ditambahkan untuk menampilkan data
data_tampil = self.data_mhs
for row in range(self.rows):
baris = data_tampil[row]
for column in range(self.columns):
nilai = baris[column]
widget = self._widgets[row][column]
widget.configure(text=nilai)
self.kejadian()
psn.showinfo("pemberitahuan","Berhasil Ditampilkan")
## self.lblStatus.configure(state=DISABLED) # ini bisa di gunakan untuk maximize dan minimize
except :
psn.showwarning("Peringatan !", "Tidak ada file yang terbaca")
def onExit(self): # Fungsi untuk keluar dari program
if askyesno('Peringatan!', 'Anda ingin keluar?'):
play1 = PlaySound('ahem_x.wav', SND_FILENAME)
self.parent.destroy()
else:
showinfo('Pemberitahuan', 'Keluar dibatalkan')
class data_transaksi():
'''Membuat kelas data transaksi'''
def __init__(self,no=None,tanggal=None,nama=None,jumlah=None,harga=None,modal=None,sales=None):
self.no = no
self.tanggal = tanggal
self.nama = nama
self.jumlah = jumlah
self.harga = harga
self.modal = modal
self.sales = sales
if __name__ =='__main__': # Untuk menjalankan Tkinter atau GUI
root = Tk()
root.geometry("813x294+400+400")
root.resizable(False,False)
app = Tugas_GUI(root)
root.mainloop()
|
6705bd7dfa677bd27dbcf200aaa3f7dc6cd6cb55 | laurenc176/PythonCrashCourse | /Lists/simple_lists_cars.py | 938 | 4.5 | 4 | #organizing a list
#sorting a list permanently with the sort() method, can never revert
#to original order
cars = ['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
#can also do reverse
cars.sort(reverse=True)
print(cars)
# sorted() function sorts a list temporarily
cars = ['bmw','audi','toyota','subaru']
print("Here is the orginal list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
# Can print a list in reverse order using reverse() method, changes it permanently
# doesnt sort backward alphabetically, simply reverses order of the list
cars = ['bmw','audi','toyota','subaru']
print(cars)
cars.reverse()
print(cars)
#other methods I already know:
len(cars) # length of the list
cars[-1] # using -1 as an index will always return the last item in a list unless list is empty, then will get an error
|
68654f6011396a2f0337ba2d591a7939d609b3ed | laurenc176/PythonCrashCourse | /Files and Exceptions/exceptions.py | 2,711 | 4.125 | 4 | #Handling exceptions
#ZeroDivisionError Exception, use try-except blocks
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
#Using Exceptions to Prevent Crashes
print("Give me two numbers, and I'll divide them")
print("Enter 'q' to quit.")
#This will crash if second number is 0
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("\nSecond number: ")
if second_number == 'q':
break
answer = int(first_number) / int(second_number)
#Prevent crash:
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("\nSecond number: ")
if second_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(answer)
#FileNotFoundError Exception
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist")
#Analyzing Text
#Many classic lit are available as simple text files because they are in public domain
#Texts in this section come from Project Gutenberg(http://gutenberg.org/)
title = "Alice in Wonderland"
title.split()
filename = 'alice.txt'
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist")
else:
#Count the approx number of words in the file.
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.")
#Working with Multiple files, create a function
def count_words(filename):
"""Count the approx number of words in the file."""
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist")
else:
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.")
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)
#Fail silently - you don't need to report every exception
#write a block as usual, but tell Python to do nothing in the except block:
def count_words(filename):
"""Count the approx number of words in the file."""
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
pass #will fail silently, acts as a placeholder
else:
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.") |
b52ad63f303e4160d7a942cad8481f2f77edf1f0 | laurenc176/PythonCrashCourse | /Testing your code/testing_a_class.py | 3,250 | 4.40625 | 4 | # Six commonly used assert methods from the unittest.TestCase class:
#assertEqual(a, b) Verify a==b
#assertNotEqual(a, b) Verify a != b
#assertTrue(x) Verify x is True
#assertFalse(x) Verify x is False
#assertIn(item, list) Verify that item is in list
#assertNotIn(item, list) Verify that item is not in list
# Testing a class is very similar to testing a function but with a few differences
class AnonymousSurvey():
"""Collect anonymous answers to a survey question."""
def __init__(self, question):
"""Store a question, and prepare to store responses"""
self.question = question
self.responses = []
def show_question(self):
print(self.question)
def store_response(self, new_response):
self.responses.append(new_response)
def show_results(self):
"""Show all responses that have been given"""
print("Survey results:")
for response in self.responses:
print(f"- {response}")
# Define a question, and make a survey
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.show_question()
print("Enter 'q' at any time to quit")
while True:
response = input("Language: ")
if response == 'q':
break
my_survey.store_response(response)
my_survey.show_results()
#Testing the AnonomousSurvey class
import unittest
class TestAnonymousSurvey(unittest.TestCase):
def test_store_single_response(self):
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
def test_store_three_responses(self):
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
responses = ['English', 'Spanish', 'Mandarin']
for response in responses:
my_survey.store_response(response)
for response in responses:
self.assertIn(response, my_survey.responses)
if __name__ == '__main__':
unittest.main()
# Above testing are a bit repetitive - can be made more efficient:
-------------------------------------------------------------------------
# The setUp() Method
# unittest.TestCase has a setUp() method - allows you to create these objects once and then use
# them in each of your test methods
# when included, Python runs the setUp() method before running each methos starting with test_
# any objects created in the setUp() method are then available in each test method you write
import unittest
class TestAnonymousSurvey(unittest.TestCase):
def setUp(self):
"""
Create a survey and a set of responses for use in all test methods.
"""
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
responses = ['English', 'Spanish', 'Mandarin']
def test_store_single_response(self):
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_responses(self):
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
if __name__ == '__main__':
unittest.main() |
4ec62e344d96dbd9db5860338526bb608a702a99 | honzaKovar/docker_unittest | /prime_numbers.py | 423 | 3.90625 | 4 | import math
from random import randint
def is_prime(number):
if number < 2:
return False
for i in range(2, int(math.sqrt(number) + 1)):
if number % i == 0:
return False
return True
if __name__ == '__main__':
MIN_VALUE = 0
MAX_VALUE = 999
random_number = randint(MIN_VALUE, MAX_VALUE)
print(f'Is number \'{random_number}\' a prime? - {is_prime(random_number)}')
|
fbc01f2c549fae60235064d839c55d98939ae775 | martinskillings/tempConverter | /tempConverter.py | 2,231 | 4.3125 | 4 |
#Write a program that converts Celsius to Fahrenheit or Kelvin
continueLoop = 'f'
while continueLoop == 'f':
celsius = eval(input("Enter a degree in Celsius: "))
fahrenheit = (9 / 5 * celsius + 32)
print(celsius, "Celsius is", format(fahrenheit, ".2f"), "Fahrenheit")
#User prompt to switch to different temperature setting or terminate program
continueLoop = input("Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: ")
if continueLoop == 'k':
celsius = eval(input("Enter a degree in Celsius: "))
kelvin = celsius + 273.15
print(celsius, "Celsius is", format(kelvin, ".2f"), "Kelvin")
continueLoop = input("Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: ")
if continueLoop == 'q':
print ("Good-Bye")
'''
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
RESTART: C:/Users/marti/AppData/Local/Programs/Python/Python36-32/tempConverter.py
Enter a degree in Celsius: 43
43 Celsius is 109.40 Fahrenheit
Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k
Enter a degree in Celsius: 43
43 Celsius is 316.15 Kelvin
Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: f
Enter a degree in Celsius: 0
0 Celsius is 32.00 Fahrenheit
Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k
Enter a degree in Celsius: 0
0 Celsius is 273.15 Kelvin
Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: f
Enter a degree in Celsius: 100
100 Celsius is 212.00 Fahrenheit
Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k
Enter a degree in Celsius: 100
100 Celsius is 373.15 Kelvin
Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: f
Enter a degree in Celsius: 37
37 Celsius is 98.60 Fahrenheit
Enter f to continue in Fahrenheit, k to change to Kelvin, or q to quit: k
Enter a degree in Celsius: 37
37 Celsius is 310.15 Kelvin
Enter f to go back to Fahrenheit, k to stay in Kelvin, or q to quit: q
Good-Bye
>>>
'''
|
3f6b3832e8c1b33cb1e03ae6a026236f1d82a171 | StarryLeo/learnpython | /day0/do_if.py | 286 | 4 | 4 | height = 1.75
weight = 80.5
bmi = weight/height * height
if bmi < 18.5:
print('过轻')
elif bmi >= 18.5 and bmi < 25:
print('正常')
elif bmi >= 25 and bmi < 28:
print('过重')
elif bmi >= 28 and bmi < 32:
print('肥胖')
else:
print('严重肥胖')
|
6d9c2f166469c4767ad6815edccc79f5306ae3c1 | est/snippets | /sort_coroutine/mergesort.py | 1,417 | 4.03125 | 4 | import random
def merge1(left, right):
result = []
left_idx, right_idx = 0, 0
while left_idx < len(left) and right_idx < len(right):
# change the direction of this comparison to change the direction of the sort
if left[left_idx] <= right[right_idx]:
result.append(left[left_idx])
left_idx += 1
else:
result.append(right[right_idx])
right_idx += 1
if left:
result.extend(left[left_idx:])
if right:
result.extend(right[right_idx:])
return result
from heapq import merge as merge2
def merge3(left,right):
if not left or not right:
return left + right
elif left[0] <= right[0]:
return [left[0]] + merge3(left[1:], right)
else:
return merge3(right,left)
def merge_sort(l):
# Assuming l is a list, returns an
# iterator on a sorted version of
# the list.
L = len(l)
if L <= 1:
return l
else:
m = L/2
left = merge_sort(l[0:m])
right = merge_sort(l[m:])
return merge(left, right)
if '__main__' == __name__:
l = [random.randint(0, 5) for x in range(10)]
s0 = sorted(l)
merge = merge1
s1 = merge_sort(l)
merge = merge2
s2 = list(merge_sort(l))
merge = merge3
s3 = merge_sort(l)
print s0==s1==s2==s3, s0, s1, s2, s3 |
fae09bb082a160bfc2cf1c165250c551d6f70387 | cdpruitt/CribbageAI | /GameActions.py | 5,135 | 3.5625 | 4 | from Card import *
from itertools import *
class History():
def __init__(self, playerToLead):
self.rounds = [RoundTo31(playerToLead)]
def isTerminal(self):
totalCardsPlayed = 0
for roundTo31 in self.rounds:
for play in roundTo31.board:
if(play=="PASS"):
break
else:
totalCardsPlayed += 1
if(totalCardsPlayed==8):
return True
else:
return False
def __repr__(self):
historyRepr = "Rounds:"
for roundTo31 in self.rounds:
historyRepr += " " + str(roundTo31)
return historyRepr
class RoundTo31():
def __init__(self, playerToLead):
self.playerToLead = playerToLead
self.board = []
def __repr__(self):
roundTo31Repr = "Cards played:"
for card in self.board:
roundTo31Repr += " " + str(card)
return roundTo31Repr
# Create a new deck at the start of the game
def createDeck():
RANKS = [1,2,3,4,5,6,7,8,9,10,11,12,13]
SUITS = ["spades","hearts","diamonds","clubs"]
return list(Card(rank, suit) for rank, suit in product(RANKS,
SUITS))
# Create a new deck at the start of a hand
def createSuitlessDeck():
RANKS = [1,2,3,4,5,6,7,8,9,10,11,12,13]
SUITS = ["spades","hearts","diamonds","clubs"]
deck = list(SuitlessCard(rank) for rank, suit in product(RANKS, SUITS))
return deck
# Score a given hand, provided the identity of the flip card and whether the
# hand is a crib or not
def scoreHand(hand,isCrib,flipCard):
score = 0
# check for His Nobs
for card in hand:
if (card.rank=="11")&(card.suit==flipCard.suit):
score += 1
# check for flush
if all(card.suit==flipCard.suit for card in hand):
score += 5
elif all(card.suit==hand[0].suit for card in hand):
score += 4
hand.append(flipCard)
hand = sorted(hand)
# check for 15s
for i in range(1,len(hand)+1):
for subHand in combinations(hand,i):
sum = 0
for card in subHand:
sum += card.value
if sum==15:
score += 2
# check for pairs
for cardPair in combinations(hand,2):
if cardPair[0].rank==cardPair[1].rank:
score += 2
# check for runs
foundRuns = False
for i in range(len(hand),2,-1):
if foundRuns == False:
for subHand in combinations(hand,i):
it = (card.rank for card in subHand)
first = next(it)
if all(a==b for a, b in enumerate(it, first+1)):
score += i
foundRuns = True
return score
# Count up the total points showing on the board
def totalTheBoard(board):
boardValue = 0
for card in board:
boardValue += card.value
return boardValue
def score(roundTo31, newCard):
currentBoard = roundTo31.board
if(roundTo31.playerToLead==0):
# first player's turn
total = scoreTheBoard(currentBoard, newCard)
else:
# second player's turn
total = -scoreTheBoard(currentBoard, newCard)
#print "For " + str(currentBoard) + " " + str(newCard) + ", total = " + str(total)
return total
def consecutive(runCards):
sortedCards = runCards[:]
sortedCards.sort(key=lambda x: x.rank)
for i, card in enumerate(sortedCards):
if(card.rank==(sortedCards[0].rank+i)):
continue
else:
return False
return True
# Compute the play points if newCard is played on the current board
def scoreTheBoard(b, newCard):
board = b[:]
board.append(newCard)
#print board
score = 0
# check for 31s and 15s
boardValue = totalTheBoard(board)
if (boardValue==15 or boardValue==31):
#print "31 or 15 for 2"
score += 2
reversedBoard = board[::-1]
# check for pairs
pairCards = []
for card in reversedBoard:
if reversedBoard[0].rank==card.rank:
pairCards.append(card)
else:
break
for x in combinations(pairCards,2):
#print "pairs for 2"
score += 2
# check for runs
runs = 0
while(len(reversedBoard)>2):
#print reversedBoard
if(consecutive(reversedBoard)):
runs = len(reversedBoard)
#print "runs for " + str(runs)
break
reversedBoard.pop()
score += runs
#if(score>0):
# print score
return score
def evaluateTerminalState(cards, roundTo31):
total = 0
playerToLead = roundTo31.playerToLead
if(playerToLead==0):
total += score(roundTo31,cards[playerToLead][0])
else:
total -= score(roundTo31,cards[playerToLead][0])
roundTo31.board.append(cards[playerToLead][0])
roundTo31.playerToLead = 1-playerToLead
if(len(cards[1-playerToLead])>0):
if(1-playerToLead==0):
total -= score(roundTo31,cards[1-playerToLead][0])
else:
total += score(roundTo31,cards[1-playerToLead][0])
return total
|
22c396d0cb06c25ea3162191dfa536672be1bd7c | GiPyoK/Sprint-Challenge--Data-Structures-Python | /names/binary_search_tree.py | 4,965 | 3.828125 | 4 | from dll_queue import Queue
from dll_stack import Stack
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
# This would be only needed if there was deleted method to BST
# because BST is always initialized with the root.
# check for empty root (base case)
if self == None:
# create a new tree with given value
self = BinarySearchTree(value)
return
# compare with root
# less than the root, move left
if value < self.value:
# check left
# if left exists, move left
if self.left:
self.left.insert(value)
# else, create new value and connect left to it
else:
self.left = BinarySearchTree(value)
return
# greater or equal to the root, move right
else:
# check right
# if right extist, move right
if self.right:
self.right.insert(value)
# else, create new value and connect right to it
else:
self.right = BinarySearchTree(value)
return
# Return True if the tree contains the value
# False if it does not
def contains(self, target):
# check for empty root
if self == None:
return False
# if the value is the target, return true
if target == self.value:
return True
# else if the value is less than the target, move left
elif target < self.value:
if self.left:
return self.left.contains(target)
# else if the value is greater than the target, move right
else:
if self.right:
return self.right.contains(target)
return False
# Return the maximum value found in the tree
def get_max(self):
# go to very right of the tree
while self.right:
self = self.right
return self.value
# Call the function `cb` on the value of each node
# You may use a recursive or iterative approach
def for_each(self, cb):
if self == None:
return
# call the function
cb(self.value)
# if left is not None, go to left
if self.left:
self.left.for_each(cb)
# if right is not None, go to right
if self.right:
self.right.for_each(cb)
# DAY 2 Project -----------------------
# Print all the values in order from low to high
# Hint: Use a recursive, depth first traversal
def in_order_print(self, node):
# left -> root -> right
if node.left:
self.in_order_print(node.left)
print(node.value)
if node.right:
self.in_order_print(node.right)
# Print the value of every node, starting with the given node,
# in an iterative breadth first traversal
def bft_print(self, root):
# create queue and enqueue the root of the BST
q = Queue()
q.enqueue(root)
# loop until the queue is empty
while q.len() > 0:
# grab the first item of the queue
node = q.dequeue()
# print the first item and enqueue any children
print(node.value)
if node.left:
q.enqueue(node.left)
if node.right:
q.enqueue(node.right)
# Print the value of every node, starting with the given node,
# in an iterative depth first traversal
def dft_print(self, root):
# create stack and push the root
stack = Stack()
stack.push(root)
# loop until the stack is empty
while stack.len() > 0:
node = stack.pop()
# print the last item and push and children
print(node.value)
if node.left:
stack.push(node.left)
if node.right:
stack.push(node.right)
# STRETCH Goals -------------------------
# Note: Research may be required
# Print Pre-order recursive DFT
def pre_order_dft(self, node):
if node:
print(node.value)
if node.left:
self.pre_order_dft(node.left)
if node.right:
self.pre_order_dft(node.right)
# Print Post-order recursive DFT
def post_order_dft(self, node):
if node.left:
self.post_order_dft(node.left)
if node.right:
self.post_order_dft(node.right)
print(node.value)
# # test
# bst = BinarySearchTree(1)
# bst.insert(8)
# bst.insert(5)
# bst.insert(7)
# bst.insert(6)
# bst.insert(3)
# bst.insert(4)
# bst.insert(2)
# bst.post_order_dft(bst) |
39a26f9febc2acc3ce0e3291c1dbe45801418275 | deep-compute/deeputil | /deeputil/keep_running.py | 5,090 | 3.84375 | 4 | """Keeps running a function running even on error
"""
import time
import inspect
class KeepRunningTerminate(Exception):
pass
def keeprunning(
wait_secs=0, exit_on_success=False, on_success=None, on_error=None, on_done=None
):
"""
Example 1: dosomething needs to run until completion condition
without needing to have a loop in its code. Also, when error
happens, we should NOT terminate execution
>>> from deeputil import AttrDict
>>> @keeprunning(wait_secs=1)
... def dosomething(state):
... state.i += 1
... print (state)
... if state.i % 2 == 0:
... print("Error happened")
... 1 / 0 # create an error condition
... if state.i >= 7:
... print ("Done")
... raise keeprunning.terminate
...
>>> state = AttrDict(i=0)
>>> dosomething(state)
AttrDict({'i': 1})
AttrDict({'i': 2})
Error happened
AttrDict({'i': 3})
AttrDict({'i': 4})
Error happened
AttrDict({'i': 5})
AttrDict({'i': 6})
Error happened
AttrDict({'i': 7})
Done
Example 2: In case you want to log exceptions while
dosomething keeps running, or perform any other action
when an exceptions arise
>>> def some_error(__exc__):
... print (__exc__)
...
>>> @keeprunning(on_error=some_error)
... def dosomething(state):
... state.i += 1
... print (state)
... if state.i % 2 == 0:
... print("Error happened")
... 1 / 0 # create an error condition
... if state.i >= 7:
... print ("Done")
... raise keeprunning.terminate
...
>>> state = AttrDict(i=0)
>>> dosomething(state)
AttrDict({'i': 1})
AttrDict({'i': 2})
Error happened
division by zero
AttrDict({'i': 3})
AttrDict({'i': 4})
Error happened
division by zero
AttrDict({'i': 5})
AttrDict({'i': 6})
Error happened
division by zero
AttrDict({'i': 7})
Done
Example 3: Full set of arguments that can be passed in @keeprunning()
with class implementations
>>> # Class that has some class variables
... class Demo(object):
... SUCCESS_MSG = 'Yay!!'
... DONE_MSG = 'STOPPED AT NOTHING!'
... ERROR_MSG = 'Error'
...
... # Functions to be called by @keeprunning
... def success(self):
... print((self.SUCCESS_MSG))
...
... def failure(self, __exc__):
... print((self.ERROR_MSG, __exc__))
...
... def task_done(self):
... print((self.DONE_MSG))
...
... #Actual use of keeprunning with all arguments passed
... @keeprunning(wait_secs=1, exit_on_success=False,
... on_success=success, on_error=failure, on_done=task_done)
... def dosomething(self, state):
... state.i += 1
... print (state)
... if state.i % 2 == 0:
... print("Error happened")
... # create an error condition
... 1 / 0
... if state.i >= 7:
... print ("Done")
... raise keeprunning.terminate
...
>>> demo = Demo()
>>> state = AttrDict(i=0)
>>> demo.dosomething(state)
AttrDict({'i': 1})
Yay!!
AttrDict({'i': 2})
Error happened
('Error', ZeroDivisionError('division by zero'))
AttrDict({'i': 3})
Yay!!
AttrDict({'i': 4})
Error happened
('Error', ZeroDivisionError('division by zero'))
AttrDict({'i': 5})
Yay!!
AttrDict({'i': 6})
Error happened
('Error', ZeroDivisionError('division by zero'))
AttrDict({'i': 7})
Done
STOPPED AT NOTHING!
"""
def decfn(fn):
def _call_callback(cb, fargs):
if not cb:
return
# get the getargspec fn in inspect module (python 2/3 support)
G = getattr(inspect, "getfullargspec", getattr(inspect, "getargspec"))
cb_args = G(cb).args
cb_args = dict([(a, fargs.get(a, None)) for a in cb_args])
cb(**cb_args)
def _fn(*args, **kwargs):
fargs = inspect.getcallargs(fn, *args, **kwargs)
fargs.update(dict(__fn__=fn, __exc__=None))
while 1:
try:
fn(*args, **kwargs)
if exit_on_success:
break
except (SystemExit, KeyboardInterrupt):
raise
except KeepRunningTerminate:
break
except Exception as exc:
fargs.update(dict(__exc__=exc))
_call_callback(on_error, fargs)
fargs.update(dict(__exc__=None))
if wait_secs:
time.sleep(wait_secs)
continue
_call_callback(on_success, fargs)
_call_callback(on_done, fargs)
return _fn
return decfn
keeprunning.terminate = KeepRunningTerminate
|
7011bfd3326ccb843859999aaf89c71a3137cdd4 | skylway/leetcode | /python/0344. 反转字符串/solution.py | 472 | 3.71875 | 4 | #!/usr/bin/python
from typing import List
class Solution:
def reverseString(self, s: List[str]) -> None:
# s.reverse()
# s[:] = s[::-1]
i = 0
len_list = len(s)
while i < len_list/2:
s[i], s[len_list-i-1] = s[len_list-i-1], s[i]
i += 1
"""
Do not return anything, modify s in-place instead.
"""
solution = Solution()
l = ['Google', 'Runoob']
solution.reverseString(l)
print(l)
|
79723bc580e8f7ccd63a8b86c182c783a56d3329 | SuzanneRioue/programmering1python | /Lärobok/kap 8/kap. 8, sid. 103 - list comprehensions.py | 1,297 | 4.34375 | 4 | #!/usr/local/bin/python3.9
# Filnamn: kap. kap. 8, sid. 103 - list comprehensions.py
# Kapitel 8 - Listor och tipplar
# Programmering 1 med Python - Lärobok
# Exempeldata
listaEtt = [9, 3, 7]
# Med listomfattningar (list comprehensions) menas att man skapar en ny lista
# där varje element är resultatet av någon operation på en annan
# itererbar variabel eventuella villkor måste också uppfyllas
# Här skapar vi en ny lista med uppräkning av t, talen finns ej från början
listaTvå = [t for t in range(10)]
print(listaTvå)
# Skapar en ny lista med utgångspunkt av t i range-inställningarna
listaTre = [t for t in range(3, 10, 3)]
print('listaTre:', listaTre)
# Skapar en ny lista med utgångspunkt av att kvadrera t utifrån
# range-inställningarna
listaFyra = [t**2 for t in range(3, 10, 3)]
print('listaFyra:', listaFyra)
# Skapa en ny lista där villkoret att inte ta med tal som är jämt delbara med 5
listaFem = [t for t in range(1, 26) if t % 5 != 0]
print('listaFem:', listaFem)
# Slå samman listor (konkatenera)
listaEtt = listaEtt + listaFyra
print('Efter sammanslagning med listaFyra är listaEtt:', listaEtt)
# Med metoden append så skapar du en lista i en lista
listaEtt.append(listaTre)
print('Efter sammanslagning med listaTre är listaEtt:', listaEtt) |
417e9bbc0a001695bc2cd7586b71b5a8b89832ee | SuzanneRioue/programmering1python | /Arbetsbok/kap 14/övn 14.1, sid. 36 - söka tal.py | 1,443 | 3.921875 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 14.1, sid. 36 - söka tal.py
# Sökning
# Programmeringsövningar till kapitel 14
# Programmet slumpar först fram 20 tal mellan 1 och 100 och lagrar alla talen i
# en lista och sedan skrivs listan ut på skärmen. Därefter frågar programmet
# användaren efter ett tal som ska eftersökas. Slutligen undersöker programmet
# om talet finns i listan och om det finns, skriva ut på indexet det finns på.
# Om inte talet finns så ska användaren informeras om att det inte finns.
# Sökmetod: Linjär sökning
# Import av modul
from random import randint
# Funktionsdefinitioner
# Huvudprogram
def main():
lista = []
# Slumpa 20 st heltal mellan 1 och 100 och lägg dem eftervarandra i listan
for c in range(20):
lista.append(randint(1,100))
# Skriv ut listan
print(lista)
# Fråga användaren efte tal som eftersöks
tal = int(input('Anget tal som eftersöks: '))
# Utför en linjär sökning i hela listan
# Utgå ifrån att talet inte finns
index = -1
for i in range(len(lista)):
if tal == lista[i]:
# Om talet hittas sätt index till det och avbryt loopen
index = i
break
if index >= 0:
print('Talet ' + str(tal) + ' finns på index ' + str(index) + ' i listan.')
else:
print('Talet ' + str(tal) + ' finns inte i listan.')
## Huvudprogram anropas
main() |
f38757087bf31b61d8238f3e98798a8799f1b6f8 | SuzanneRioue/programmering1python | /Lärobok/kap 8/kap. 8, sid. 104 - sammanfattning med exempel.py | 2,712 | 4.1875 | 4 | #!/usr/local/bin/python3.9
# Filnamn: kap. 8, sid. 104 - sammanfattning med exempel.py
# Kapitel 8 - Listor och tipplar
# Programmering 1 med Python - Lärobok
# Exempeldata
lista = [7, 21, 3, 12]
listaLäggTill = [35, 42]
listaSortera = [6, 2, 9, 1]
listaNamn = ['Kalle', 'Ada', 'Pelle', 'Lisa']
# len(x) Ta reda på antal element i en lista samt vilket nr sista index är
antalElement = len(lista)
sistaIndex = antalElement - 1
print('lista: ', lista, 'består av', antalElement, ' element och sista indexposten är',sistaIndex)
# sorted() Skapar en ny lista som är sorterad
print('listaSortera:', listaSortera)
nySorteradLista = sorted(listaSortera)
print('nySorteradLista baserad på en sorterad listaSortera:', nySorteradLista)
# sort() returnerar en sorterad lista
print('En numrerad lista för sortering:', lista)
lista.sort()
print('En numrerad lista efter sortering:', lista)
print('En alfabetisk lista för sortering:', listaNamn)
listaNamn.sort()
print('En alfabetisk lista efter sortering:', listaNamn)
# append(x) lägg till element i slutet av befintlig lista
print('lista före tillägg:', lista)
lista.append(28)
print('lista efter tillägg:', lista)
# extend(lista) sammanfoga/konkatenera två listor, går med +
print('lista före sammanfogning:', lista)
print('med listaLäggTill:', listaLäggTill)
# lista.extend(listaLäggTill) ¤ Krånglig metod
lista = lista + listaLäggTill # Bättre och enklare metod
print('lista efter sammanfogning:', lista)
# insert(x) infoga elemet på indexposition x
print('listaNamn före infogandet av ett namn till:', listaNamn)
listaNamn.insert(1, 'Agnes')
print('listaNamn efter infogandet av ett namn till:', listaNamn)
# remove(x) tar bort första elementet i en lista med värdet/strängen x
print('listaNamn före borttagande av namnet Kalle:', listaNamn)
listaNamn.remove('Kalle')
print('listaNamn efter borttagande av namnet Kalle:', listaNamn)
# pop(x) ta bort element med index x, utelämnas x tas sista elemnt bort
print('lista före borttag av index 0 och sista index:', lista)
lista.pop(0)
lista.pop()
print('lista efter bottag av index 0 och sista index:', lista)
# index(x) tar reda på index nummer för element x
print('listaNamn:', listaNamn)
finnsPåIndex = listaNamn.index('Lisa')
print('Lisa finns på indexposition:', finnsPåIndex)
# count(x) räkna antal förekomster av element x
lista.append(7) # Vi lägger till en 7:a till lista
antal7or = lista.count(7)
print('lista ser nu ut så här:', lista)
print('Det finns', antal7or, 'st 7:or i lista')
# reversed() Vänder listan bak och fram
print('lista ser nu ut så här:', lista)
lista.reverse()
print('efter att vi vänt på listan så ser den ut så här:', lista)
|
d5448c074c4419908d4c5246e1d87f792fd28731 | SuzanneRioue/programmering1python | /Arbetsbok/kap 14/övn 14.3, sid. 37 - gissa ett tal.py | 1,650 | 3.921875 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 14.2, sid. 36 - söka tal med funktion.py
# Sökning
# Programmeringsövningar till kapitel 14
# Programmet slumpar först fram ett tal mellan 1 och 99 och lagrar det talet.
# Därefter frågar datorn användaren vilke tal datorn tänker på och användaren
# får gissa tills han/hon gissat rätt och då får man även reda på hur många
# gissningar man gjort. Om användaren gissar ett för lågt tal så sägger datorn
# att det är för lågt och för högt om det är tvärs om.
# Import av modul
from random import randint
# Funktionsdefinitioner
# Huvudprogram
def main():
# Variabeldeklarationer och initieringar
# Talet som datorn tänker på
talDator = randint(1,100)
# Antal gissningar som användaren gjort
gissningar = 1
# Skriv ut en programrubrik
print('Gissa vilket tal jag tänker på')
print('==============================\n')
# Fråga användaren vilket tal datorn tänker på
talAnvändare = int(input('Vilket tal tänker jag på? '))
while talDator != talAnvändare:
# Beroende på om användarens gissade tal är för högt eller lågt
# i förhållande till vad datorn tänker på för tal,skriv ut en ledtråd
if talAnvändare > talDator:
print('För högt!')
else:
print('För lågt!')
# Öka antal gissningar
gissningar += 1
# Låt användaren gissa på ett nytt tal
talAnvändare = int(input('Vilket tal tänker jag på? '))
print('Rätt gissat på ' + str(gissningar) + ' försök.')
## Huvudprogram anropas
main() |
60febc4082a4c46d7a0da215bc70e5531777ad75 | SuzanneRioue/programmering1python | /Arbetsbok/kap 3/övn 3.4 - ange valfri rabatt på vara - kap 3, sid. 5.py | 1,098 | 4.09375 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 3.4 - ange valfri rabatt på vara - kap 3, sid. 5.py
# Skapa program eller skript
# Programmeringsövningar till kapitel 3 - Arbetsbok
# Programmet frågar först efter ordinarie pris på en vara. Därefter frågar det
# efter en godtycklig rabattprocent
# Till sist skriver det ut ett extrapris som ger den inmatade rabatten på
# ordinariepris
# Skriv ut programmets rubrik
print('Extrapris')
print('=========\n')
# Fråga efter ordinarie pris och rabattprocent. Därefter omvandla siffrorna från sträng till decimaltal
ordinariePris = float(input('Ange ordinarie pris: '))
rabattProcent = float(input('Ange rabattprocenten: '))
decimalRabattProcent = rabattProcent / 100 # Omvandlar procenttalet till ett decimaltal för senare beräkning
# Beräkna extrapriset 100% - rabattProcent * ordinarie pris
extraPris = (1 - decimalRabattProcent) * ordinariePris
# Skriv ut rabattprocenten med noll decimaler och extrapriset med två decimalers noggranhet
print('Extrapriset blir med {0:.0f} % rabatt: {1:.2f} kr.'.format(rabattProcent, extraPris))
|
4ceb64bae252b6c7acd59332297c3ccc02023694 | SuzanneRioue/programmering1python | /Arbetsbok/kap 10/övn 10.1 - lottorad.py | 1,306 | 3.546875 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 10.1 - lottorad.py
# Slumptal i programmering
# Programmeringsövningar till kapitel 10
# Programmet slumpar fram en lottorad, 7 tal i intervallet 1 - 35 där samma
# nummer inte får uppkomma 2 gånger
from random import randrange
# Funktionsdefinitioner
def lottorad(): # Funktionshuvud
# Variabeldeklarationer
tal = 0 # Lagrar ett slumptal temporärt
lottorad = [0, 0, 0, 0, 0, 0, 0] # Lottorad som ska returneras senare
i = 0
# Slumpa fram 7 tal mellan 1-35 och lagra i listan lottorad
# talen som lagras måste vara olika
while i < 7:
tal = randrange(1,36)
lottorad[i] = tal
i += 1
# Kontroll om tal finns som dublett
for c in range(i):
# om tal och listans tal c är lika och c samt i-1 är skilda från
# varandra då är det en dublett
if tal == lottorad[c] and c != (i-1):
# Vi ska fixa ett nytt slumptal på samma index
# då det gamla var en dublett därav i -1 och break
i -= 1
break
# Återgå till anropande program med en sorterad lista
return sorted(lottorad)
# Huvudprogram
def main():
print(lottorad())
## Huvudprogram anropas
main() |
a969e3ff963ef2ed1980e8ff48bf4c048dfefde9 | SuzanneRioue/programmering1python | /Lärobok/kap 6/kap. 6, sid. 76 - kontrollera innehåll och tomma strängar.py | 842 | 3.703125 | 4 | #!/usr/local/bin/python3.9
# Filnamn: kap. 6, sid. 76 - kontrollera innehåll och tomma strängar.py
# Kapitel 6 - Mer om teckensträngar i Python
# Programmering 1 med Python - Lärobok
# Kontrollera innehåll i en sträng med operatorn in
if 'r' in 'Räven raskar över isen': # Kontroll av enstaka tecken
print('Bokstaven r finns!')
if 'rask' in 'Räven raskar över isen': # Kontroll av fras/ord/orddel
print('Frasen/ordet eller orddelen finns!')
'''
Exempel på tom sträng
En tom sträng tolkas alltid som falsk (False) vid villkorstestning
och undertrycker alltid en radframmatning i print-satser
Övriga strängar tolkas som sanna (True)
'''
s = ''
if s:
print('Strängen är inte tom')
else:
print('Strängen är tom')
s = 'Nisse'
if s:
print('Strängen är inte tom')
else:
print('Strängen är tom') |
e415fc6296d368d63a75ef1a8a50e7182820a49c | SuzanneRioue/programmering1python | /Arbetsbok/kap 3/övn 3.7 - Additionsövning med formaterad utskrift med flyttal - kap 3, sid. 6.py | 759 | 3.90625 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 3.7 - Additionsövning med formaterad utskrift med flyttal - kap 3
# sid. 6.py
# Skapa program eller skript
# Programmeringsövningar till kapitel 3 - Arbetsbok
# Additionsövning med formaterad utskrift
# Programmet skriver ut tal i en snygg additionsuppställning
# Skriv ut programmets rubrik
print('Enkel addition med tre siffror i decimalform')
print('============================================\n')
# Deklaration och initiering av 3 tal
tal1 = 123.45
tal2 = 6.7
tal3 = 89.01
# Beräkna summan av de tre talen
summa = tal1 + tal2 + tal3
# Skriv ut ett kvitto
print('{:>8.2f}'.format(tal1))
print('{:>8.2f}'.format(tal2))
print('+{:>7.2f}'.format(tal3))
print('========')
print('{:>8.2f}'.format(summa))
|
1a6cf574b1498ca03608892dcfe185605b909bd5 | SuzanneRioue/programmering1python | /Lärobok/kap 16/kap. 16, sid. 186 - omvandla dictionary till olika listor.py | 929 | 3.609375 | 4 | #!/usr/local/bin/python3.9
# Filnamn: kap. 16, sid. 186 - omvandla dictionary till olika listor.py
# Kapitel 16 - Mer om listor samt dictionaries
# Programmering 1 med Python - Lärobok
# Kodexempel från boken med förklaringar
# Skapa en associativ array (dictionary) med namn som nycklar och anknytningsnr
# som värde
anknytning = {'Eva':4530, 'Ola':4839, 'Niklas':6386, 'Agnes':4823}
# Skriv ut dictionaryn
print(anknytning)
# Skapa en ny lista med tipplar utav dictionaryn och skriv ut den
listaMedTipplar = list(anknytning.items())
print(listaMedTipplar)
# Skriv ut tippel 1
print(listaMedTipplar[1])
enTippel = listaMedTipplar[1]
# Skriv ut första indexet i tippeln
print(enTippel[0])
# Skapa en ny lista av listor utav dictionaryn och skriv ut den
listaMedListor = [[namn, ankn] for namn, ankn in anknytning.items()]
print(listaMedListor)
# Skriv ut endast ut ett av namnen i listan
print(listaMedListor[2][0]) |
38bfae3b5387684afe8dc8b4787087bdd786d2c0 | SuzanneRioue/programmering1python | /Arbetsbok/kap 8/övn 8.3 - beräkna summa och medelvärde av lista - kap. 8, sid. 21.py | 1,289 | 4.03125 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 8.3 - beräkna summa och medelvärde av lista - kap. 8, sid. 21.py
# Listor och tipplar
# Programmeringsövningar till kapitel 8
# Programmet frågar efter hur många tal du vill mata in, låter dig sedan mata
# in dessa en i taget. Efter varje inmatning läggs det inmatade talet till
# listan. Därefter beräknar programmet summan och medelvärdet av listans tal.
# Slutligen skrivs listans summa och medelvärdet ut på konsolen
listaTal = [] # Tom lista som lagrar antTal element innehållande tal
# Fråga användaren hur många tal som ska matas in
antTal = int(input('Hur många tal vill du mata in? '))
# Be användaren mata in antTal st tal och lagra dem som varsit nytt element i
# listan listaTal
for i in range(antTal):
listaTal.append(float(input('Ange tal ' + str(i+1) + ': ')))
# Beräkna summan av alla inmatade tal
summa = 0 # Måste inieras denna annars tror systemet att summa också är en lista
for i in range(antTal):
summa += listaTal[i] # Här är det viktigt att summa initierats innan
# Beräkna medelvärdet av listan alla tal
medel = summa / antTal
# Skriv ut summan och medelvärdet på konsolen
print('Summan av alla inmatade tal blev ' + str(summa) + ' och medelvärdet blev ' + str(medel)) |
43b89ba2d0757f49a5d86da45c98930f65d600d4 | SuzanneRioue/programmering1python | /Arbetsbok/kap 14/övn 14.6, sid. 38 - datorn gissar ett tal.py | 2,362 | 3.78125 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 14.6, sid. 38 - datorn gissar ett tal.py
# Sökning
# Programmeringsövningar till kapitel 14
# Programmet låter dig tänka på ett tal mellan 1 och 99.
# Första gången gissar datorn på talet i mitten utifrån det givna intervallet 1
# till 99. Dvs. talet 50. Svarar användaren at det är för högt
# gissar dator på nedre halvans mitt, dvs 25, sedan tillfrågas användaren igen.
#
# Import av modul
from random import randint
# Funktionsdefinitioner
def binGissning(ngräns, ögräns):
return (ögräns - ngräns) // 2
# Huvudprogram
def main():
# Variabeldeklarationer och initieringar
# Talet som datorn tror människan tänker på
talMänniska = 0
# Antal gissningar som datorn gjort
gissningar = 1
# Talgränser
nedre = 1
övre = 100
# Svar som ska anges av användaren
svar = ''
# Skriv ut en programrubrik
print('Jag gissar vilket tal du tänker på')
print('==================================\n')
print('Får jag be dig att tänka på ett tal mellan 1 och 100.')
# Gissa i mitten av talgränserna
talMänniska = binGissning(nedre, övre)
# Skriv ut gissningen
print('Jag gissar att du tänker på talet ' + str(talMänniska) + '.')
# Fråga användaren om det är rätt, för högt eller lågt
svar = input('Är det [r]ätt, för [h]ögt eller [l]ågt: ')
while svar not in ['r', 'rätt']:
if svar in ['h', 'högt']:
övre = talMänniska - 1
oldtal = talMänniska
talMänniska -= binGissning(nedre, övre)
if oldtal == talMänniska:
talMänniska -= 1
if svar in ['l', 'lågt']:
nedre = talMänniska + 1
oldtal = talMänniska
talMänniska += binGissning(nedre, övre)
if oldtal == talMänniska:
talMänniska += 1
# Öka antal gissningar
gissningar += 1
# Skriv ut gissningen
print('Jag gissar att du tänker på talet ' + str(talMänniska) + '.')
# Och fråga användaren återigen om det är rätt, för högt eller lågt
svar = input('Är det [r]ätt, för [h]ögt eller [l]ågt: ')
print('Jag gissat rätt efter ' + str(gissningar) + ' försök.')
# Huvudprogram anropas
main() |
c183615f347834216b4f3f12cd97e6e22a07d472 | SuzanneRioue/programmering1python | /Arbetsbok/kap 4/övn 4.4 - priskoll på bensin - kap 4, sid. 7.py | 831 | 3.671875 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 4.4 - priskoll på bensin - kap 4, sid. 7.py
# Skapa program eller skript
# Programmeringsövningar till kapitel 4 - Arbetsbok
# Programmet frågar efter bensinpris och som sedan med villkor talar om
# om det är billigt eller inte.
# Skriv ut programmets rubrik
print('Priskoll på bensin')
print('==================\n')
# Fråga efter bensinpriset och omvandla siffrorna från sträng till decimaltal
bensinPris = float(input('Vad kostar bensinen per liter: '))
# Utifrån bensinpriset, testa med villkor och berätta för användaren om det är
# billigt eller dyrt
if bensinPris > 20:
print('Nu säljer jag bilen och cyklar istället')
elif bensinPris > 15:
print('Tanka tio liter')
elif bensinPris > 10:
print('Tanka full tank')
else:
print('Det var billigt')
|
281e7f4dd1ef0495d3213f59afd0007d0426134a | SuzanneRioue/programmering1python | /Arbetsbok/kap 6/övn 6.4 - vänder på meningen - kap. 6, sid. 15.py | 313 | 3.5 | 4 | #!/usr/local/bin/python3.9
# Filnamn: övn 6.4 - vänder på meningen - kap. 6, sid. 15.py
# Mer om teckensträngar i Python
# Programmeringsövningar till kapitel 6
# Programmet ber användaren mata in en meninig och skriver sedan ut den
# baklänges
mening = input('Skriv en mening: ')
print(mening[::-1])
|
e691e8b4c3ad89fdc107b6b9bb2a37f4ba34091d | AmishiBisht/PythonProject | /Calculator.py | 6,120 | 4.1875 | 4 | from tkinter import *
from math import *
win = Tk()
win.title("Calculator") # this title will be displayed on the top of the app
#win.geometry("300x400") # this defines the size of the app of window
input_box = StringVar() # It gets the contents of the entry box
e = Entry(win,width = 50, borderwidth = 5, textvariable = input_box) # this defines the size of the entry box for user input
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10) # this displays the entry box on the top
expression = "" # Initiate the variable expression
def button_click(num): # this function generates expression when any button is clicked
global expression
expression = expression + str(num)
input_box.set(expression)
return
def Button_Clear(): # clears the contents of the entry box
global expression
expression = ""
input_box.set(expression)
return
def Button_Equal(): # evaluates the expression in the entr box and displays the result
global expression
result = str(eval(expression))
round(result,2)
expression = result
input_box.set(expression)
return
def Button_Factor():
result = str(eval(expression))
a=int(result)
Factors=[]
for i in range(1,a+1):
if a% i==0:
Factors.append(i)
Factors.append(',')
e.insert(0,Factors)
return
def Button_Fctrl():
global expression
result = str(eval(expression))
num =int(result)
factorial = 1
if num == 0:
e.insert(0,1)
else:
for i in range(1,num + 1):
factorial = factorial*i
e.delete(0,END)
e.insert(0,factorial)
expression = str(factorial)
return
def Button_PrimeOrComposite():
a = int(eval(e.get()))
Button_Clear()
factors = []
for i in range(1,a+1):
if a % i== 0:
factors.append(a)
if len(factors)==2:
input_box.set("Is prime.")
else:
input_box.set("Is composite.")
return
def Button_Abs():
result = abs(eval(e.get()))
e.delete(0,END)
global expression
expression = result
input_box.set(expression)
return
#Defining Buttons (what they should display and what they should do)
button_1 = Button(win, text="1", padx=40, pady=20, font=("Courier",11), fg='turquoise', bg='white', command = lambda: button_click(1))
button_2 = Button(win, text="2", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click(2))
button_3 = Button(win, text="3", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: button_click(3))
button_4 = Button(win, text="4", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click(4))
button_5 = Button(win, text="5", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: button_click(5))
button_6 = Button(win, text="6", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click(6))
button_7 = Button(win, text="7", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: button_click(7))
button_8 = Button(win, text="8", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click(8))
button_9 = Button(win, text="9", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: button_click(9))
button_0 = Button(win, text="0", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click(0))
button_sum = Button(win, text="+", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click('+'))
button_diff = Button(win, text="-", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: button_click('-'))
button_equal = Button(win, text="=", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: Button_Equal())
button_clear = Button(win, text="AC", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: Button_Clear())
button_mul = Button(win, text="*", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click('*'))
button_div = Button(win, text="/", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: button_click('/'))
button_fac = Button(win, text=" factor", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: Button_Factor())
button_fctrl = Button(win, text="fctrl", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: Button_Fctrl())
button_bracket = Button(win, text="(", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click("("))
button_bracket1 = Button(win, text=")", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: button_click(')'))
button_primeorcomp = Button(win, text="CheckPrime", padx=40, pady=20, font=("Arial",11), fg='turquoise', bg='white', command = lambda: Button_PrimeOrComposite())
button_abs = Button(win, text="Abs", padx=40, pady=20, font=("Arial",11), fg='purple', bg='white', command = lambda: Button_Abs())
#To display buttons
#The following code displays the buttons created
button_1.grid(row=1, column=0)
button_2.grid(row=1, column=1)
button_3.grid(row=1, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=3, column=0)
button_8.grid(row=3, column=1)
button_9.grid(row=3, column=2)
button_0.grid(row=4, column=0)
button_sum.grid(row=2, column=3)
button_diff.grid(row=3, column=3)
button_equal.grid(row=4, column=2)
button_clear.grid(row=4, column=1)
button_mul.grid(row=1, column=3)
button_div.grid(row=4, column=3)
button_fac.grid(row=5, column=2)
button_bracket.grid(row=5, column=0)
button_bracket1.grid(row=5, column=1)
button_fctrl.grid(row=5, column=3)
button_primeorcomp.grid(row=6, column=0)
button_abs.grid(row=6, column=1)
win.mainloop()
|
3a96ab91401def3cb21863b4eeb3d0f082d07811 | zhenya-paitash/course-python-ormedia | /lesson__6_homework.py | 4,806 | 4.34375 | 4 | from math import pi # число ПИ для 2ого задания
import random as R # для генерации рандомных чисел в решении заданий
# 1. Определите класс Apple с четырьмя переменными экземпляра, представляющими четыре свойства яблока
class Apple:
def __init__(self, c, w, s, v):
self.color = c
self.weight = w
self.size = s
self.view = v
print("1: ")
# 2. Создайте класс Circle с методом area, подсчитывающим и возвращающим площадь круга. Затем создайте объект Circle,
# вызовите в нем метод area и выведите результат. Воспользуйтесь функцией pi из встроенного в Python модуля math
class Circle:
def __init__(self, n):
self.number = n
self.square = 0
def area(self, r): # s = pi*r^2
self.square = pi * (r ** 2)
crcl = Circle(1)
radius = R.randint(5, 30)
crcl.area(radius)
print(f"2: Радиус круга: {radius} Площадь круга: {round(crcl.square, 3)}") # площадь округляю до 3х знаков после точки
# 3. Есть класс Person, конструктор которого принимает три параметра (не учитывая self) – имя, фамилию и квалификацию
# специалиста. Квалификация имеет значение заданное по умолчанию, равное единице.
class Person:
def __init__(self, n, srn, q=1):
self.name = n
self.surname = srn
self.qualification = q
# 3(2) У класса Person есть метод, который возвращает строку, включающую в себя всю информацию о сотруднике
def pers(self, person):
print(f" Сотрудник {person.surname} {person.name} имеет квалификацию {person.qualification}.")
prs1, prs2 = Person('Евгений', 'Пайташ', 'Junior'), Person('Вейдер', 'Дарт', 'Space Lord')
print("3: ")
prs1.pers(prs1)
prs2.pers(prs2)
# 4. Создайте класс Triangle с методом area, подсчитывающим и возвращающим площадь треугольника. Затем создайте
# объект Triangle, вызовите в нем area и выведите результат
class Triangle:
def __init__(self, n):
self.number = n
self.thr = 0
def area(self, a, h):
self.thr = 0.5 * a * h
tr1 = Triangle(1)
base, height = R.randint(5, 30), R.randint(10, 20)
tr1.area(base, height)
print(f"4: При основании {base} см и высоте {height} см, площадь треугольника {tr1.thr} см²")
# 5. Создайте классы Rectangle и Square с методом calculate_perimeter, вычисляющим периметр фигур, которые эти классы
# представляют. Создайте объекты Rectangle и Square вызовите в них этот метод
class Rectangle():
def __init__(self, one, two):
self.one_side, self.two_side = one, two
self.perimeter = 0
def calculate_perimeter(self):
self.perimeter = (self.one_side + self.two_side) * 2
class Square():
def __init__(self, side):
self.side = side
def calculate_perimeter(self):
self.perimeter = 4 * self.side
def change_size(self, inp):
self.side += inp
rect, squ = Rectangle(R.randint(5, 100), R.randint(5, 100)), Square(R.randint(5, 50))
rect.calculate_perimeter(), squ.calculate_perimeter()
print(f"5: Периметр прямоугольника со сторонами {rect.one_side} cm и {rect.two_side} cm равен {rect.perimeter} cm,\n "
f" периметр квадрата со стороной {squ.side} cm равен {squ.perimeter} cm.")
# 6. В классе Square определите метод change_size, позволяющий передавать ему число, которое увеличивает или уменьшает
# (если оно отрицательное) каждую сторону объекта Square на соответствующее значение
squ.change_size(int(input('6: Введите число, на которе хотите изменить грань квадрата :')))
squ.calculate_perimeter()
print(f" Новый периметр квадрата со стороной {squ.side}cm равен {squ.perimeter} cm.")
|
faa30b2222bde8849d6d452736f025f0bd80ecdb | HelloYuiYui/Fun-with-PyTurtle | /Dots.py | 759 | 3.796875 | 4 |
from turtle import *
import random
#setting up the environment.
bgcolor("#ffebc6")
color("blue", "yellow")
speed(10)
def dots():
#hiding turtle and pen to avoid creating unwanted lines between dots.
penup()
hideturtle()
dotnum = 0
limit = 200 #change number to create more or less dots.
while dotnum <= limit:
#random coordinates for dots.
dotx = random.randint(-300, 300)
doty = random.randint(-300, 300)
#random size for dots.
dotsize = random.randint(1, 200)
dotsize = dotsize/10
goto(dotx, doty)
dot(dotsize, "black")
dotnum += 1
#to stop program when reached to the limit.
if dotnum > limit:
done()
break
dots() |
aefe923d857f9ab74c65429ebfae3d539b7fb007 | Snowerest/leetcodeQuestion-Python | /stack.py | 399 | 3.8125 | 4 | class Stack(object):
def __init__(self):
self.__v = []
def is_empty(self) -> bool:
return self.__v == []
def push(self, value: object) -> None:
self.__v.append(value)
def pop(self) -> object:
if self.is_empty():
return None
value = self.__v[-1]
self.__v = self.__v[:-1]
return value
|
968c16becdcdaaea847617224ea4fb776865d839 | Snowerest/leetcodeQuestion-Python | /ball_sort.py | 291 | 3.609375 | 4 | def ball_sort(nums: list) -> list:
ln = len(nums)
if ln <= 1:
return nums
i = 0
while i < ln:
j = i
while j < ln:
if nums[j] <= nums[i]:
nums[j], nums[i] = nums[i], nums[j]
j += 1
i += 1
return nums
|
78ed8e3e2072193899cc73f9224cbec04e10e593 | kushagrasurana/Minuet-server | /app/responses.py | 1,429 | 3.546875 | 4 | from flask import jsonify
from . import app
def make_response(code, message):
"""Creates an HTTP response
Creates an HTTP response to be sent to client with status code as 'code'
and data - message
:param code: the http status code
:param message: the main message to be sent to client
:return: returns the HTTP response
"""
if code == 400:
return bad_request(message)
elif code == 401:
return unauthorized(message)
elif code == 403:
return forbidden(message)
elif code == 500:
return internal_server_handler(message)
else:
return ok(message)
@app.errorhandler(400)
def bad_request(message):
response = jsonify({'error': 'bad request', 'message': message})
response.status_code = 400
return response
@app.errorhandler(401)
def unauthorized(message):
response = jsonify({'error': 'unauthorized', 'message': message})
response.status_code = 401
return response
@app.errorhandler(403)
def forbidden(message):
response = jsonify({'error': 'forbidden', 'message': message})
response.status_code = 403
return response
@app.errorhandler(500)
def internal_server_handler(message):
response = jsonify({'error': 'server error', 'message': message})
response.status_code = 500
return response
def ok(message):
response = jsonify(message)
response.status_code = 200
return response |
17aa9df4e57e711c87f41b3e101d894ce19c50ba | DrakeVorndran/Tweet-Generator | /Code/reaarrange.py | 602 | 3.84375 | 4 | import sys
import random
def reaarrange(words):
for i in reversed(range(1,len(words))):
pos = random.randint(0,i-1)
words[i], words[pos] = words[pos], words[i]
return(words)
def reverseString(string, seperator=""):
if(seperator == ""):
return_string = list(string)
else:
return_string = string.split(seperator)
return_string.reverse()
return return_string
def anagram(word):
return "".join(reaarrange(list(word)))
if __name__ == '__main__':
l = sys.argv[1:]
print(*reaarrange(l))
# print(reverseString("hello my name is bob", " "))
# print(anagram("anagram")) |
be6b2ac375fb83d117835be397d7aa411afb94a8 | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/005闰年判断.py | 425 | 3.890625 | 4 | print('------------酸饺子学Python------------')
#判断一个年份是否是闰年
#Coding 酸饺子
temp = input('输入一个年份吧:\n')
while not temp.isdigit():
print('这个不是年份吧……')
year = int(temp)
if year/400 == int(year/400):
print('闰年!')
else:
if (year/4 == int(year/4)) and (year/100 != int(year/100)):
print('闰年!')
else:
print('平年!')
|
5eadae3b9e4e99640a7ec52cf0483eaf9c2fbf4b | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/030搜索文件.py | 667 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-06-16 23:11:30
# @Author : 酸饺子 (changzheng300@foxmail.com)
# @Link : http://bbs.fishc.com/space-uid-437297.html
# @Version : $Id$
import os
content = input('请输入待查找的目录:')
file_name = input('请输入待查找的目标文件:')
def Search(path, file_name):
path_list = os.listdir(path)
os.chdir(path)
for each in path_list:
if os.path.isdir(each):
Search(os.path.join(path, each), file_name)
os.chdir(path)
else:
if each == file_name:
print(os.path.join(path, each))
return
Search(content, file_name)
|
2feef38d5f8ce0751dbecbb098d0936c5df0cf17 | SourDumplings/CodeSolutions | /OJ practices/PAT甲级真题练习/1039. Course List for Student-超时.py | 1,188 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-12-06 16:05:13
# @Author : 酸饺子 (changzheng300@foxmail.com)
# @Link : https://github.com/SourDumplings
# @Version : $Id$
'''
https://www.patest.cn/contests/pat-a-practise/1039
'''
def main():
temp = input().split(' ')
N = int(temp[0])
K = int(temp[1])
students = {}
for i in range(K):
c_info = input().split(' ')
c = int(c_info[0])
n = int(c_info[1])
if n:
namelist = input().split(' ')
for each_name in namelist:
if each_name in students.keys():
students[each_name].append(c)
else:
students[each_name] = [c]
if N:
query = input().split(' ')
for each_name in query:
if each_name not in students.keys():
print("%s 0" % each_name)
continue
print("%s %d" % (each_name, len(students[each_name])), end='')
students[each_name].sort()
for each_course in students[each_name]:
print(" %d" % each_course, end='')
print()
if __name__ == '__main__':
main()
|
e33f3ad1ed5312c6c2e9726f243b005719f02ee4 | SourDumplings/CodeSolutions | /Book practices/《简单粗暴 TensorFlow 2.0》练习代码/1.基础/2.自动求导机制.py | 929 | 3.53125 | 4 | import tensorflow as tf
# 计算函数 y = x^2 在 x = 3 处的导数
# x = tf.Variable(initial_value=3.)
# with tf.GradientTape() as tape: # 在 tf.GradientTape() 的上下文内,所有计算步骤都会被记录以用于求导
# y = tf.square(x)
# y_grad = tape.gradient(y, x) # 计算y关于x的导数
# print([y, y_grad])
# 多元函数,对向量的求导
X = tf.constant([[1., 2.], [3., 4.]])
y = tf.constant([[1.], [2.]])
w = tf.Variable(initial_value=[[1.], [2.]])
b = tf.Variable(initial_value=1.)
temp0 = tf.matmul(X, w)
print(temp0)
temp1 = temp0 + b
print(temp1)
temp2 = temp1 - y
print(temp2)
temp3 = tf.square(temp2)
print(temp3)
temp4 = tf.reduce_sum(temp3)
print(temp4)
with tf.GradientTape() as tape:
L = 0.5 * tf.reduce_sum(tf.square(tf.matmul(X, w) + b - y))
w_grad, b_grad = tape.gradient(L, [w, b]) # 计算L(w, b)关于w, b的偏导数
print([L.numpy(), w_grad.numpy(), b_grad.numpy()])
|
d070a6c21e6788543c94e042ddc9a1a6e6822029 | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/014check.py | 1,957 | 3.859375 | 4 | #密码安全检查
#Coding 酸饺子
# 密码安全性检查代码
#
# 低级密码要求:
# 1. 密码由单纯的数字或字母组成
# 2. 密码长度小于等于8位
#
# 中级密码要求:
# 1. 密码必须由数字、字母或特殊字符(仅限:~!@#$%^&*()_=-/,.?<>;:[]{}|\)任意两种组合
# 2. 密码长度不能低于8位
#
# 高级密码要求:
# 1. 密码必须由数字、字母及特殊字符(仅限:~!@#$%^&*()_=-/,.?<>;:[]{}|\)三种组合
# 2. 密码只能由字母开头
# 3. 密码长度不能低于16位
print('-------------酸饺子学Python-------------')
symbols = r'''`!@#$%^&*()_+-=/*{}[]\|'";:/?,.<>'''
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
nums = '0123456789'
passwd = input('请输入需要检查的密码组合:')
# 判断长度
length = len(passwd)
while (passwd.isspace() or length == 0) :
passwd = input("您输入的密码为空(或空格),请重新输入:")
length = len(passwd)
if length <= 8:
flag_len = 1
elif 8 < length < 16:
flag_len = 2
else:
flag_len = 3
flag_con = 0
# 判断是否包含特殊字符
for each in passwd:
if each in symbols:
flag_con += 1
break
# 判断是否包含字母
for each in passwd:
if each in chars:
flag_con += 1
break
# 判断是否包含数字
for each in passwd:
if each in nums:
flag_con += 1
break
# 打印结果
while 1 :
print("您的密码安全级别评定为:", end='')
if flag_len == 1 or flag_con == 1 :
print("低")
elif flag_len == 2 or flag_con == 2 :
print("中")
else :
print("高")
print("请继续保持")
break
print("请按以下方式提升您的密码安全级别:\n\
\t1. 密码必须由数字、字母及特殊字符三种组合\n\
\t2. 密码只能由字母开头\n\
\t3. 密码长度不能低于16位'")
break
|
3b17c72973b952d716cdd263b5faf377f3ec143c | SourDumplings/CodeSolutions | /OJ practices/牛客网:PAT真题练兵场-乙级/有理数四则运算.py | 2,615 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-11-16 10:28:17
# @Author : 酸饺子 (changzheng300@foxmail.com)
# @Link : https://github.com/SourDumplings
# @Version : $Id$
'''
https://www.nowcoder.com/pat/6/problem/4060
'''
import math as m
def main():
def gcd(a, b):
r = a % b
while r:
a = b
b = r
r = a % b
gcd = b
return gcd
def ToInt(n):
if n - int(n):
n *= 10
return n
s = input()
s = s.replace(' ', '/')
a1 = int(s.split('/')[0])
b1 = int(s.split('/')[1])
a2 = int(s.split('/')[2])
b2 = int(s.split('/')[3])
# print(a1, b1, a2, b2)
def OutPut(a, b):
# print("$$a = %.2f, b = %.2f$$" % (a, b))
if not a:
print(0, end='')
else:
temp_a = a
temp_b = b
g = gcd(temp_a, temp_b)
temp_a /= g
temp_b /= g
if a / b < 0:
print('(', end='')
k = int(m.fabs(temp_a) // m.fabs(temp_b))
if a / b < 0:
k *= -1
# print("$$k = %d$$" % k)
if k:
print(k, end='')
if temp_a < 0 and temp_b > 0:
temp_a *= -1
if temp_a > 0 and temp_b < 0:
temp_b *= -1
temp_a = temp_a - m.fabs(k) * temp_b
if temp_a:
print(" %d/%d" % (temp_a, temp_b), end='')
else:
if temp_a > 0 and temp_b < 0:
print("-%d/%d" % (temp_a, -temp_b), end='')
else:
print("%d/%d" % (temp_a, temp_b), end='')
if a / b < 0:
print(')', end='')
return
# 和
OutPut(a1, b1)
print(" + ", end='')
OutPut(a2, b2)
print(" = ", end='')
a = a1 * b2 + a2 * b1
b = b1 * b2
OutPut(a, b)
print()
# 差
OutPut(a1, b1)
print(" - ", end='')
OutPut(a2, b2)
print(" = ", end='')
a = a1 * b2 - a2 * b1
b = b1 * b2
OutPut(a, b)
print()
# 积
OutPut(a1, b1)
print(" * ", end='')
OutPut(a2, b2)
print(" = ", end='')
a = a1 * a2
b = b1 * b2
OutPut(a, b)
print()
# 商
OutPut(a1, b1)
print(" / ", end='')
OutPut(a2, b2)
print(" = ", end='')
if not a2:
print("Inf")
else:
a = ToInt(a1 / a2)
b = ToInt(b1 / b2)
# print("$$a = %.2f, b = %.2f$$" % (a, b))
OutPut(a, b)
return
if __name__ == '__main__':
main()
|
5d0e1b4504139b2166783311414a30d8ed0e3be7 | SourDumplings/CodeSolutions | /OJ practices/PAT甲级真题练习/1012. The Best Rank.py | 2,536 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-11-28 19:18:52
# @Author : 酸饺子 (changzheng300@foxmail.com)
# @Link : https://github.com/SourDumplings
# @Version : $Id$
'''
https://www.patest.cn/contests/pat-a-practise/1012
'''
def main():
temp = input()
temp = temp.split(' ')
N = int(temp[0])
M = int(temp[1])
Agrade = {}
Cgrade = {}
Mgrade = {}
Egrade = {}
for i in range(N):
s = input()
s = s.split(' ')
ID = s[0]
C = int(s[1])
m = int(s[2])
E = int(s[3])
A = (C + m + E) / 3
Agrade[ID] = A
Cgrade[ID] = C
Mgrade[ID] = m
Egrade[ID] = E
def readrankdata(rankdata, ranklist, index, N):
r = 1
# print(ranklist)
count = 0
for i in range(N):
if not rankdata.get(ranklist[i][0]):
rankdata[ranklist[i][0]] = [0, 0, 0, 0]
rankdata[ranklist[i][0]][index] = r
count += 1
if i < N - 1 and ranklist[i][1] > ranklist[i + 1][1]:
r += count
count = 0
# print(rankdata)
return
rankdata = {} # id : [Arank, Crank, Mrank, Ernak]
A_ranklist = sorted(Agrade.items(), key=lambda d: d[1], reverse=True)
readrankdata(rankdata, A_ranklist, 0, N)
C_ranklist = sorted(Cgrade.items(), key=lambda d: d[1], reverse=True)
readrankdata(rankdata, C_ranklist, 1, N)
M_ranklist = sorted(Mgrade.items(), key=lambda d: d[1], reverse=True)
readrankdata(rankdata, M_ranklist, 2, N)
E_ranklist = sorted(Egrade.items(), key=lambda d: d[1], reverse=True)
readrankdata(rankdata, E_ranklist, 3, N)
items = ['A', 'C', 'M', 'E']
bestrankdata = {} # id : [bestrank, best]
for each in rankdata:
bestrank = rankdata[each][0]
for each_rank in rankdata[each]:
if each_rank < bestrank:
bestrank = each_rank
best = rankdata[each].index(bestrank)
if not bestrankdata.get(each):
bestrankdata[each] = [0, 0]
bestrankdata[each][0] = bestrank
bestrankdata[each][1] = best
# print(bestrankdata)
checklist = []
for i in range(M):
temp = input()
# print(temp)
checklist.append(temp)
# print(checklist)
for each_id in checklist:
data = bestrankdata.get(each_id)
if data:
print("%d %s" % (data[0], items[data[1]]))
else:
print("N/A")
if __name__ == '__main__':
main()
|
00f241c31584d25d9a8eb0c93aeb1fdff2c5a5bc | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/025通讯录.py | 1,712 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-06-13 17:22:08
# @Author : 酸饺子 (changzheng300@foxmail.com)
# @Link : http://bbs.fishc.com/space-uid-437297.html
# @Version : $Id$
contact = {}
print('''|--- 欢迎进入通讯录程序---|
|--- 1 :查询联系人资料 ---|
|--- 2 :插入新的联系人 ---|
|--- 3 : 删除已有联系人 ---|
|--- 4 : 退出通讯录程序 ---|\n''')
while 1:
order = int(input('请输入相关指令代码:'))
if order == 2:
name2 = input('请输入联系人姓名:')
if name2 in contact:
print('您输入的用户名在通讯录中已存在!')
print(name2, ':', contact[name2])
edit = input('是否修改该用户的资料?(Yes/No)')
if (edit != 'Yes') and (edit != 'No'):
print('输入错误!')
elif edit == 'Yes':
contact[name2] = input('请输入用户联系电话:')
print('修改成功!')
else:
continue
else:
phone2 = input('请输入用户联系电话:')
contact[name2] = phone2
print('插入成功!')
if order == 1:
name1 = input('请输入联系人姓名:')
if name1 in contact:
print(name1, ':', contact[name1])
else:
print('该联系人不存在!')
if order == 3:
name3 = input('请输入联系人姓名:')
if name3 in contact:
contact.pop(name3)
print('删除成功!')
else:
print('该联系人不存在!')
if order == 4:
break
print('|--- 感谢使用通讯录程序 ---|')
|
89a06671ad98cebf5590a4ece8ad192d2954819b | SourDumplings/CodeSolutions | /OJ practices/PAT甲级真题练习/1035. Password.py | 957 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-12-05 20:30:26
# @Author : 酸饺子 (changzheng300@foxmail.com)
# @Link : https://github.com/SourDumplings
# @Version : $Id$
'''
https://www.patest.cn/contests/pat-a-practise/1035
'''
def main():
N = int(input())
modified = []
flag = 0
for i in range(N):
account = input().split()
pw0 = account[1]
pw = pw0
pw = pw.replace('1', '@')
pw = pw.replace('0', '%')
pw = pw.replace('O', 'o')
pw = pw.replace('l', 'L')
if pw != pw0:
modified.append([account[0], pw])
flag += 1
if (flag):
print(flag)
for each_modified in modified:
print(each_modified[0], each_modified[1])
elif N > 1:
print("There are %d accounts and no account is modified" % N)
else:
print("There is 1 account and no account is modified")
if __name__ == '__main__':
main()
|
ae952d0a06fff2b4f8ced902cd7355a19e0b17a1 | SourDumplings/CodeSolutions | /OJ practices/LeetCode题目集/88. Merge Sorted Array(easy).py | 943 | 3.65625 | 4 | '''
@Author: SourDumplings
@Date: 2020-02-16 19:37:18
@Link: https://github.com/SourDumplings/
@Email: changzheng300@foxmail.com
@Description: https://leetcode-cn.com/problems/merge-sorted-array/
双指针法,从后往前填
'''
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
p = m + n - 1
p1 = m - 1
p2 = n - 1
while 0 <= p1 and 0 <= p2:
num1 = nums1[p1]
num2 = nums2[p2]
if num1 < num2:
nums1[p] = nums2[p2]
p2 -= 1
else:
nums1[p] = nums1[p1]
p1 -= 1
p -= 1
while 0 <= p2:
nums1[p] = nums2[p2]
p -= 1
p2 -= 1
while 0 <= p1:
nums1[p] = nums1[p1]
p -= 1
p1 -= 1
|
70a075b1fba763f3a12d1baecbc20c50930c0c3d | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/010向列表中添加成绩.py | 287 | 4.21875 | 4 | #向列表中添加成绩
#Coding 酸饺子
print('-------------酸饺子学Python-------------')
member = ['小甲鱼', '黑夜', '迷途', '怡静', '秋舞斜阳']
member.insert(1, 88)
member.insert(3, 90)
member.insert(5, 85)
member.insert(7, 90)
member.insert(9, 88)
print(member)
|
ebc51cdc6f85317dc3e53bd614184c5b9a15519b | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/064tk2.py | 692 | 3.53125 | 4 | # encoding: utf-8
"""
@author: 酸饺子
@contact: changzheng300@foxmail.com
@license: Apache Licence
@file: tk2.py
@time: 2017/7/25 10:00
tkinter演示实例2,打招呼
"""
import tkinter as tk
def main():
class APP:
def __init__(self, master):
frame = tk.Frame(master)
frame.pack(side=tk.LEFT, padx=10, pady=10)
self.hi_there = tk.Button(frame, text='打招呼', fg='white',
command=self.say_hi, bg='black')
self.hi_there.pack()
def say_hi(self):
print('hello!我是酸饺子!')
root = tk.Tk()
app = APP(root)
root.mainloop()
if __name__ == '__main__':
main()
|
de09ee49797be6b1931cec7a4b4a17c50aa78b0f | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/009输入密码.py | 483 | 4.09375 | 4 | #输入密码
#Coding 酸饺子
print('-------------酸饺子学Python-------------')
count = 3
code = 'SourDumplings'
while count != 0:
guess = input('您好,请输入密码:')
if guess == code:
print('密码正确!')
break
elif '*' in guess:
print('密码中不能含有*!')
print('您还有', count, '次机会')
else:
count -= 1
print('密码错误。您还有', count, '次机会!')
|
6df6963f07c1073e3ae63b8ab99850fe90355a76 | SourDumplings/CodeSolutions | /OJ practices/PAT甲级真题练习/1023. Have Fun with Numbers.py | 692 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-12-01 20:52:18
# @Author : 酸饺子 (changzheng300@foxmail.com)
# @Link : https://github.com/SourDumplings
# @Version : $Id$
'''
https://www.patest.cn/contests/pat-a-practise/1023
'''
def main():
n = input()
num = int(n)
num *= 2
doubled_n = str(num)
flag = 1
for d in doubled_n:
# print("n = %s, d = %s" % (n, d))
i = n.find(d)
if i == -1:
flag = 0
break
n = n.replace(d, '', 1)
if len(n) > 0:
flag = 0
# print(n)
if flag:
print("Yes")
else:
print("No")
print(doubled_n)
if __name__ == '__main__':
main()
|
9348714135c920044a7664b82b4b8648b88a424f | SourDumplings/CodeSolutions | /Course practices/小甲鱼课程:小甲鱼—《零基础入门学习Python》/042字符串ASCII码四则运算.py | 1,054 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-06-30 18:23:48
# @Author : 酸饺子 (changzheng300@foxmail.com)
# @Link : http://bbs.fishc.com/space-uid-437297.html
# @Version : $Id$
class Nstr(str):
def __add__(self, other):
a = 0
b = 0
for each in self:
a += ord(each)
for each in other:
b += ord(each)
return (a + b)
def __sub__(self, other):
a = 0
b = 0
for each in self:
a += ord(each)
for each in other:
b += ord(each)
return (a - b)
def __mul__(self, other):
a = 0
b = 0
for each in self:
a += ord(each)
for each in other:
b += ord(each)
return (a * b)
def __truediv__(self, other):
a = 0
b = 0
for each in self:
a += ord(each)
for each in other:
b += ord(each)
return (a / b)
a = Nstr('FishC')
b = Nstr('love')
print(a + b)
print(a - b)
print(a * b)
print(a / b)
|
6baa21538651c4b215d774f883d17b0824f23a6a | guilfojm/01-IntroductionToPython-201930 | /src/m6_your_turtles.py | 2,180 | 3.703125 | 4 | """
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Aaron Wilkin, their colleagues, and Justin Guilfoyle.
"""
########################################################################
# DONE: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
########################################################################
########################################################################
# DONE: 2.
# You should have RUN the m5e_loopy_turtles module and READ its code.
# (Do so now if you have not already done so.)
#
# Below this comment, add ANY CODE THAT YOU WANT, as long as:
# 1. You construct at least 2 rg.SimpleTurtle objects.
# 2. Each rg.SimpleTurtle object draws something
# (by moving, using its rg.Pen). ANYTHING is fine!
# 3. Each rg.SimpleTurtle moves inside a LOOP.
#
# Be creative! Strive for way-cool pictures! Abstract pictures rule!
#
# If you make syntax (notational) errors, no worries -- get help
# fixing them at either this session OR at the NEXT session.
#
# Don't forget to COMMIT-and-PUSH when you are done with this module.
#
#######################################################################
import rosegraphics as rg
window = rg.TurtleWindow()
size = 150
blue_turtle = rg.SimpleTurtle('turtle')
blue_turtle.pen = rg.Pen('midnight blue',5)
blue_turtle.speed = 15
for k in range(15):
# Put the pen down, then draw a square of the given size:
blue_turtle.draw_square(size)
# Move a little below and to the right of where the previous
# square started. Do this with the pen up (so nothing is drawn).
blue_turtle.pen_up()
blue_turtle.right(30)
blue_turtle.forward(10)
blue_turtle.left(5)
# Put the pen down again (so drawing resumes).
# Make the size for the NEXT square be 12 pixels smaller.
blue_turtle.pen_down()
size = size - 12
green_turtle = rg.SimpleTurtle('turtle')
green_turtle.pen = rg.Pen('green',2)
green_turtle.speed = 4
for k in range(35):
green_turtle.left(k)
green_turtle.forward(20)
green_turtle.right(35)
green_turtle.backward(30)
window.close_on_mouse_click()
|
a4f4a928befdb63ceaf7f834d6b6641a7922674a | Debonairesnake6/ClashBot | /src/player_ranks.py | 2,521 | 3.75 | 4 | """
This file will gather all of the information needed to create a table showing each player's rank
"""
from text_to_image import CreateImage
class PlayerRanks:
"""
Handle creating the player ranks table
"""
def __init__(self, api_results: object):
"""
Handle creating the player ranks table
:param api_results: Results from the api_queries file
"""
self.api_results = api_results
self.titles = None
self.columns = []
self.player_column = []
self.rank_column = []
self.colour_columns = []
self.titles = ['Player', 'Rank']
self.player_ranked_info = None
self.player_name = None
self.setup()
def setup(self):
"""
Run the major functions of the object
"""
self.process_every_player()
self.set_colour_columns()
self.create_image()
def create_image(self):
"""
Create the image from the processed results
"""
CreateImage(self.titles, self.columns, '../extra_files/player_ranks.png',
colour=self.colour_columns, convert_columns=True)
def process_every_player(self):
"""
Process every player to grab their rank
"""
for player_name in self.api_results.player_information:
self.player_name = player_name
self.player_ranked_info = self.api_results.player_information[player_name]['ranked_info']
self.process_single_player()
self.columns.append(self.player_column)
self.columns.append(self.rank_column)
def process_single_player(self):
"""
Process a single player to grab their rank
"""
self.player_column.append(self.player_name)
try:
self.rank_column.append(f'{self.player_ranked_info["tier"]} {self.player_ranked_info["rank"]}')
# If the player has not been placed in ranked
except KeyError:
self.rank_column.append('UNRANKED')
def set_colour_columns(self):
"""
Set the colour depending on the player ranks
"""
colours = []
for row in self.rank_column:
colours.append(row.split()[0].lower())
self.colour_columns.append(colours)
self.colour_columns.append(colours)
if __name__ == '__main__':
import shelve
from api_queries import APIQueries
api_info = shelve.open('my_api')['api']
tmp = PlayerRanks(api_info)
print()
|
9d7c247e69d6d3a3f39d5124275746beb844ef77 | kaarthikalagappan/sonos-jukebox | /rfidOperations.py | 3,561 | 4.03125 | 4 | #!/usr/bin/env python
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
def writeToTag(data):
""" Function to write to the tag """
reader = SimpleMFRC522()
#Only 48 characters can be written using the mfrc522 library
if len(data) > 48:
print("""Can accept only string less than 48 characters,
but given data is > 48 chars, so writing only first 48 characters""")
print("Place Tag to write")
reader.write((str(data)[:48]))
print("Successfully written")
def start():
""" A method that manages writing to the RFID tag """
flag = True
"""
Grammar of the instruction embedded to the tags (jukebox uses this grammar)
An instruction that starts with '1' means it is a system command (play, pause...)
An instruction that starts with '2' means the following text is a Spotify URI and is followed
by the media name (the media name will be announced when the tag is used)
TODO: an instruction that starts with '3' means the following text is an Apply Music ID
TODO: an instruction that starts with '4' means the following text is an Amazon Music ID
"""
reader = SimpleMFRC522()
while flag:
flag = False
userInput = input("1. System Command\n2. Spotify URI\n3. Read RFID Tag\n")
if int(userInput) == 1:
systemInput = input("\n1. play\n2. pause\n3. playpause\n4. mute/unmute\n5. next\n6. previous\n7. shuffle\n8. clearqueue\n9. toggle night mode\n10. toggle enhanced speech mode\n11. custom\n")
if int(systemInput) == 1:
writeToTag("1;play")
elif int(systemInput) == 2:
writeToTag("1;pause")
elif int(systemInput) == 3:
writeToTag("1;playpause")
elif int(systemInput) == 4:
writeToTag("1;togglemute")
elif int(systemInput) == 5:
writeToTag("1;next")
elif int(systemInput) == 6:
writeToTag("1;previous")
elif int(systemInput) == 7:
writeToTag("1;shuffle")
elif int(systemInput) == 8:
writeToTag("1;clearqueue")
elif int(systemInput) == 9:
writeToTag("1;togglenightmode")
elif int(systemInput) == 10:
writeToTag("1;togglespeechmode")
elif int(systemInput) == 11:
data = input("Custom command (max 48 characters): ")
writeToTag("1;" + data)
else:
print("Invalid selection, please try again")
flag = True
continue
elif int(userInput) == 2:
URI = input("Enter the Spotify URI in the format given by Spotify ('spotify:{track/playlist/NO-ARTIST}:{ID}):'")
mediaName = input("What is the name of the album, track, or playlist: ")
writeToTag("2;" + URI[8:] + ";"+ mediaName)
print("Successfully written")
elif int(userInput) == 3:
print("Place the card on top of the reader")
id, text = reader.read()
print(text)
else:
print("Invalid selection, please try again")
flag = True
continue
userInput = input("""\n1. Write or read another tag\n2. Exit\n""")
if int(userInput) == 1:
flag = True
else:
GPIO.cleanup()
flag = False
if __name__ == '__main__':
start()
|
332db90717d18029d34aa1bbca1ce2d43fdd2a1d | InfiniteWing/Solves | /zerojudge.tw/a780.py | 361 | 3.53125 | 4 | def main():
while True:
try:
s = input()
except EOFError:
break
o, e, a = float(s.split()[0]),float(s.split()[1]),float(s.split()[2])
if(o == 0 and e == 0 and a == 0):
break
m = o / e
f = a / m
print('{0:.2f}'.format(round(m,2)),'{0:.2f}'.format(round(f,2)))
main() |
d3e7eed51bfb47b69c552328c2c584658200f54e | InfiniteWing/Solves | /zerojudge.tw/c082.py | 1,507 | 3.515625 | 4 | alert=[]
class Robot:
def __init__(self,x, y, d,map,alert):
self.x = x
self.y = y
self.alive = 1
self.alert=alert
self.lastLocation = map
if(d=='W'):
self.d = 1
if(d=='N'):
self.d = 2
if(d=='E'):
self.d = 3
if(d=='S'):
self.d = 4
self.map=map
def Action(self,c):
if(c=='L'):
self.d=self.d-1
if(self.d<1):
self.d=4
if(c=='R'):
self.d=self.d+1
if(self.d>4):
self.d=1
if(c=='F'):
self.Walk()
if(self.x>map.x or self.y>map.y or self.x<0 or self.y<0):
if(self.lastLocation in self.alert):
self.x=self.lastLocation.x
self.y=self.lastLocation.y
return 1
self.x=self.lastLocation.x
self.y=self.lastLocation.y
self.alive=0
return 0
return 1
def Walk(self):
self.lastLocation=Location(self.x,self.y)
if(self.d==1):
self.x-=1
if(self.d==2):
self.y+=1
if(self.d==3):
self.x+=1
if(self.d==4):
self.y-=1
class Location:
def __init__(self,x,y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
l=input()
data=l.split()
map=Location(int(data[0]),int(data[1]))
face=["","W","N","E","S"]
while True:
try:
l=input()
except EOFError:
break
data=l.split()
robot=Robot(int(data[0]),int(data[1]),data[2],map,alert)
l=input()
for s in l:
c=robot.Action(s)
if(c==0):
alert.append(robot.lastLocation)
break
if(robot.alive):
print(robot.x,robot.y,face[robot.d],sep=" ")
else:
print(robot.x,robot.y,face[robot.d],"LOST",sep=" ")
|
ec8bf34b460455bd32a2607fa7bab4ee23f15e4a | InfiniteWing/Solves | /zerojudge.tw/c419.py | 274 | 3.546875 | 4 | def main():
while True:
try:
n = int(input())
except EOFError:
break
for i in range(n-1,-1,-1):
ans = ''
for j in range(n):
ans += '*' if(j>=i) else '_'
print(ans)
main() |
e7ef5b40ececc2999a68c6873dde147dd5e725e3 | gahogg/Cracking-the-Coding-Interview-6th-Edition-Answers | /linked_lists/Return kth to last 2.py | 406 | 3.90625 | 4 | # Implement an algorithm to find the kth to last element
# of a singly linked list
from singly_linked_list_node import SinglyLinkedListNode
# O(n) runtime, O(1) space
def kth_to_last(head, k):
cur = head
while True:
k -= 1
if k == 0:
return cur
cur = cur.next
head = SinglyLinkedListNode.linkify([3, 3, 2, 2, 1, 4, 1])
print(head)
print(kth_to_last(head, 8)) |
d5a296818f6bd02b8c03c76b2aa042abbcb4ee17 | AlexanderOHara/programming | /week03/absolute.py | 336 | 4.15625 | 4 | # Give the absolute value of a number
# Author Alexander O'Hara
# In the question, number is ambiguous but the output implies we should be
# dealing with floats so I am casting the input to a flat
number = float (input ("Enter a number: "))
absoluteValue = abs (number)
print ('The absolute value of {} is {}'. format (number, absoluteValue))
|
027ae9177f91395fd0b224ace53b431bad3af815 | BaselECE/Assignment1 | /Question_1/B.py | 435 | 4.09375 | 4 | number1 =eval (input ("enter the first number : "))
number2 =eval (input ("enter the second number : "))
process =input ("enter the process(*,/,+,-):") # ask user to type process
# test what process to do
if (process=='*') :
print (number1*number2)
elif (process=='/') :
print (number1/number2)
elif (process=='+') :
print(number1+number2)
else :
print(number1-number2)
|
11a6a3f01707ad71dd18ea2e9a7bd330791ca7bb | fenghui2018/python | /lesson_9/op_oo.py | 929 | 3.984375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def getup(name):
print(name+' is getting up')
def eat(name):
print(name+' eats something')
def go_to_school(name):
print(name+' goes to school')
def op():
person1 = 'xiaoming'
getup(person1)
eat(person1)
go_to_school(person1)
person2 = 'xiaohong'
getup(person2)
eat(person2)
go_to_school(person2)
class Person:
name = ''
def __init__(self, name):
self.name = name
def getup(self):
print(self.name+' is getting up')
def eat(self):
print(self.name+' eats something')
def go_to_school(self):
print(self.name+' goes to school')
def oo():
person1 = Person('xiaoming')
person1.getup()
person1.eat()
person1.go_to_school()
person2 = Person('xiaohong')
person2.getup()
person2.eat()
person2.go_to_school()
if __name__ == "__main__":
op()
oo()
|
3c4bf7743c3aa9b70eaf040e8ed461bc6c8d9c6f | kyleedwardsny/monty_hall | /monty_hall.py | 627 | 3.6875 | 4 | import random
def monty_hall(size, omniscient, switch):
prize = random.randint(1, size)
choice = random.randint(1, size)
if not omniscient or choice == prize:
unopened = random.randint(1, size)
while unopened == choice:
unopened = random.randint(1, size)
else:
unopened = prize
if switch:
return unopened == prize
else:
return choice == prize
win = 0
lose = 0
for i in range(10000):
if monty_hall(3, True, True):
win += 1
else:
lose += 1
print("Win: %i" % win)
print("Lose: %i" % lose)
print("Total: %i" % (win + lose))
|
607120b19311605f418307cffc49981af62672c5 | miker7790/Arcade | /manager/games/hangman.py | 3,456 | 3.734375 | 4 | import os
import csv
import random
class HANGMAN:
def __init__(self, word=None, attempts=None):
self.word = word.lower() if word else self._selectRandomWord()
self.remainingAttempts = attempts if attempts else self._getInitialRemainingAttempts()
self.remainingLetters = list(self.word)
self.allGuesses = []
self.correctGuesses = []
self.incorrectGuesses = []
self.lastGuess = None
self._maskWord()
self._updateGameStatus()
# sets rules/ initalizes game
def playGame(self):
while self.remainingAttempts > 0 and len(self.remainingLetters) > 0:
print('Unknown Word: {}'.format(self.maskedWord))
print('Current Available Attempts: {}'.format(self.remainingAttempts))
while True:
guess=input('Please guess a single lowercase letter: ')
if guess and len(guess) == 1 and guess.isalpha() == True:
break
self.lastGuess = guess.lower()
self._guessLetter()
for key, item in self.gameStatus.items():
print('{}: {}'.format(key, item))
print()
self.gameStatus['word'] = self.word
self.gameStatus['win'] = True if len(self.remainingLetters) == 0 else False
message = 'Congrats, the word guessed was: {}' if len(self.remainingLetters) == 0 else 'You lost, you did not guess the word which was: {}'
print(message.format(self.word), '\n')
return(self.gameStatus)
# updates word after each guess
def _guessLetter(self):
if self.lastGuess in self.remainingLetters:
self._correctGuess()
elif self.lastGuess not in self.allGuesses:
self._incorrectGuess()
self.allGuesses.append(self.lastGuess)
self._updateGameStatus()
# updates word/ records guess
def _correctGuess(self):
self.remainingLetters = [i for i in self.remainingLetters if i != self.lastGuess]
self.correctGuesses.append(self.lastGuess)
self.remainingAttempts = self.remainingAttempts - 1
self._maskWord()
# records guess
def _incorrectGuess(self):
self.incorrectGuesses.append(self.lastGuess)
self.remainingAttempts = self.remainingAttempts - 1
# provides game details as you play
def _updateGameStatus(self):
self.gameStatus = {
'correctGuesses': self.correctGuesses,
'incorrectGuesses': self.incorrectGuesses,
'lastGuess': self.lastGuess,
}
# masks the word and reveals it for each correct guess
def _maskWord(self):
self.maskedWord = ''.join([' _ ' if i in self.remainingLetters else i for i in self.word])
# selects random word from file of words
def _selectRandomWord(self):
with open(os.path.dirname(os.path.abspath(__file__)) + '/gameInput/hangman/words.csv') as file:
words = list(csv.reader(file))
randomWord = random.choice(words)[0].lower()
return randomWord
# initializes the amount of attemps for the game based on the length of the word
def _getInitialRemainingAttempts(self):
return len(self.word) + 3 |
d50309f43cb772cdc2f212c0b6437a1c444a24a3 | tanmay-raichur/assignment-one | /morrisons/csv_converter.py | 4,728 | 3.84375 | 4 | """ This is a CSV file converter module.
It reads CSV file and creates a json file
with parent-child structure.
"""
import sys
import pandas as pd
import json
import logging as log
log.basicConfig(level=log.INFO)
def csv_to_json(ip_path: str, op_path: str) -> None:
""" Converts given csv file into json file.
Csv file needs to be in agreed format, below points are important
1. Base URL is first column and need not be displayed in the output Json
2. Each level of data will have 3 columns Label, ID and Link in said order
3. File can have any number of columns or rows
4. Duplicate IDs at any level will be ignored
5. First row is the header
:parameter
ip_path : csv filename or path to the file including filename
op_path : json filename or path to the file including filename
"""
try:
file_data, headers = _read_edit_data(ip_path)
NO_ATTR = 3
no_levels = int(len(headers)/NO_ATTR)
list_levels = [['label', 'id', 'link'] for i in range(no_levels)]
all_items = _filedata_to_flatlist(file_data, no_levels,
list_levels, NO_ATTR)
final = _flatlist_to_tree(all_items, no_levels)
_create_json(final, op_path)
except FileNotFoundError:
log.error('The CSV data file is missing.')
except PermissionError:
log.error('The required permissions missing on CSV file.')
except Exception:
log.error('Some other error occurred.', exc_info=True)
def _read_edit_data(ip_path: str) -> list:
""" This function will read the csv data and
make necessary transformations to the data frame
"""
file_data = pd.read_csv(ip_path)
headers = list(file_data.columns)
headers.pop(0)
file_data = file_data[headers[:]]
file_data.dropna(subset=[headers[0]], inplace=True)
return file_data, headers
def _filedata_to_flatlist(file_data: list, no_levels: int,
list_levels: list, NO_ATTR: int) -> list:
""" This function creates a list with flat structure. """
all_items = []
id_list = []
curr_id = 0
for line in file_data.values:
level_grp = _split_line(line, no_levels, NO_ATTR)
for level in range(0, (no_levels)):
data = {list_levels[level][i]: level_grp[level][i] for i in range(NO_ATTR)}
data['children'] = []
prev_id = curr_id
curr_id = data['id']
id_isnull = (curr_id != curr_id)
id_exists = (curr_id in id_list)
if not id_exists and not id_isnull:
data['id'] = int(data['id'])
if level == 0:
all_items.append(data.copy())
else:
data['level'] = level
data['parent'] = prev_id
all_items.append(data.copy())
id_list.append(curr_id)
data.clear()
return all_items
def _split_line(line: list, no_levels: int, NO_ATTR: int) -> list:
""" This function splits the line into one list per level. """
level_grp = []
for level in range(no_levels):
level_grp.append(line[level * NO_ATTR:(level + 1) * NO_ATTR])
return level_grp
def _flatlist_to_tree(all_items: list, no_levels: int) -> list:
""" This function will convert flat list into
a tree structure as requested.
"""
pop_list = []
final = []
for j in reversed(range(1, no_levels)):
for i in range(len(all_items)):
if 'level' in all_items[i].keys() and all_items[i]['level'] == j:
pop_list.append(i)
data = all_items[i].copy()
parent = all_items[i]['parent']
for k in range(len(all_items)):
if all_items[k]['id'] == parent:
data.pop('level')
data.pop('parent')
all_items[k]['children'].append(data.copy())
break
for i in range(len(all_items)):
if 'level' not in all_items[i].keys():
final.append(all_items[i])
return final
def _create_json(final: list, op_path: str) -> None:
""" Creates a json file at output path. """
json_dump = json.dumps(final)
json_str = json.loads(json_dump, parse_int=str)
final_json = json.dumps(json_str, indent=4)
with open(op_path, 'w') as outfile:
outfile.write(final_json)
log.info("Json file successfully created.")
if __name__ == "__main__":
csv_to_json(sys.argv[1],sys.argv[2])
|
a43ea1df7cbf7ab62ae50e8385d8d70c127d16b4 | PhillipDHK/Recommender | /RecommenderMaker.py | 1,488 | 3.546875 | 4 | '''
@author: Phillip Kang
'''
import RecommenderEngine
def makerecs(name, items, ratings, numUsers, top):
'''
This function calculates the top recommendations and returns a two-tuple consisting of two lists.
The first list is the top items rated by the rater called name (string).
The second list is the top items not seen/rated by name (string)
'''
recommend = RecommenderEngine.recommendations(name, items, ratings, numUsers)
recommend = recommend[:top]
lst = []
lst1 = []
for i in RecommenderEngine.recommendations(name, items, ratings, numUsers):
if ratings[name][items.index(i[0])] == 0:
lst.append(i)
if ratings[name][items.index(i[0])] != 0:
lst1.append(i)
return lst1[:top], lst[:top]
if __name__ == '__main__':
name = 'student1367'
items = ['127 Hours', 'The Godfather', '50 First Dates', 'A Beautiful Mind',
'A Nightmare on Elm Street', 'Alice in Wonderland',
'Anchorman: The Legend of Ron Burgundy',
'Austin Powers in Goldmember', 'Avatar', 'Black Swan']
ratings = {'student1367': [0, 3, -5, 0, 0, 1, 5, 1, 3, 0],
'student1046': [0, 0, 0, 3, 0, 0, 0, 0, 3, 5],
'student1206': [-5, 0, 1, 0, 3, 0, 5, 3, 3, 0],
'student1103': [-3, 3, -3, 5, 0, 0, 5, 3, 5, 5]}
numUsers = 2
top = 3
print(makerecs(name, items, ratings, numUsers, top))
|
87b052581e7ad1fe51f8e06fe1658b9d3d69ee26 | vdeangelis/Flask | /routes.py | 936 | 3.59375 | 4 | from flask import Flask, url_for, request, render_template
from app import app
# server/
@app.route('/')
def hello():
createLink = "<a href='" + url_for('create') + "'>Create a question</a>"
return """<html>
<head>
<title>Ciao Mondo!!'</title>
</head>
<body>
""" + createLink + """
<h1>Hello Vitto!</h1>
</body>
</html>"""
#server/create
@app.route('/create')
def create():
if request.method == 'GET':
#send user the format
return render_template('CreateQuestion.html')
elif request.method == 'POST':
#read form and data and save it
title = request.form['title']
answer = request.form['answer']
question = request.form['question']
#Store data in data store
return render_tempalte('CreatedQuestion.html',question = question)
else:
return "<h2>Invalid request</h2>"
#server/question/<tile>
@app.route('/question/<title>')
def question(title):
return "<h2>" + title + "</h2>"
|
6859cc2ba2ed3ba969b42861bc701dd1d0ca59fe | Neraverin/codewars-python | /Simple Encryption #1 - Alternating Split/main.py | 2,128 | 3.609375 | 4 | import unittest
class KataTest(unittest.TestCase):
@staticmethod
def decrypt(encrypted_text, n):
for i in range(n):
first = encrypted_text[:int(len(encrypted_text)/2)]
second = encrypted_text[int(len(encrypted_text)/2):]
if len(first) < len(second):
first += ' '
encrypted_text = ''.join(i for j in zip(second, first) for i in j).rstrip()
return encrypted_text
@staticmethod
def encrypt(text, n):
for i in range(n):
text = text[1::2] + text[0::2]
return text
def test_empty_case(self):
self.assertEqual(self.encrypt("", 0), "")
self.assertEqual(self.decrypt("", 0), "")
self.assertEqual(self.encrypt(None, 0), None)
self.assertEqual(self.decrypt(None, 0), None)
def test_encrypt_case(self):
self.assertEqual(self.encrypt("This is a test!", 0), "This is a test!")
self.assertEqual(self.encrypt("This is a test!", 1), "hsi etTi sats!")
self.assertEqual(self.encrypt("This is a test!", 2), "s eT ashi tist!")
self.assertEqual(self.encrypt("This is a test!", 3), " Tah itse sits!")
self.assertEqual(self.encrypt("This is a test!", 4), "This is a test!")
self.assertEqual(self.encrypt("This is a test!", -1), "This is a test!")
self.assertEqual(self.encrypt("This kata is very interesting!", 1), "hskt svr neetn!Ti aai eyitrsig")
def test_decrypt_case(self):
self.assertEqual(self.decrypt("This is a test!", 0), "This is a test!")
self.assertEqual(self.decrypt("hsi etTi sats!", 1), "This is a test!")
self.assertEqual(self.decrypt("s eT ashi tist!", 2), "This is a test!")
self.assertEqual(self.decrypt(" Tah itse sits!", 3), "This is a test!")
self.assertEqual(self.decrypt("This is a test!", 4), "This is a test!")
self.assertEqual(self.decrypt("This is a test!", -1), "This is a test!")
self.assertEqual(self.decrypt("hskt svr neetn!Ti aai eyitrsig", 1), "This kata is very interesting!")
if __name__ == "__main__":
unittest.main()
|
ddb2e24756117bf6869a1b10b93237566c9d1eae | LavaTime/Envelopes | /forthStrategy.py | 1,767 | 3.78125 | 4 | from envelope import Envelope
class N_max_strategy:
"""
can run the forth strategy on a set of envelops
Attributes:
envelops (list): list of envelops to run the strategy one
N (int): holds the N for the strategy
"""
def __init__(self, envelops):
self.envelops = envelops
self._N = None
@property
def N(self):
return self._N
@N.setter
def N(self, newN):
if newN is int:
self._N = newN
else:
print('N can only be an integer')
def display(self):
return "This is a strategy that opens N - 1 evelopes are are bigger than the first one"
def play(self):
"""
performs the strategy using the N and the object
Args:
self: the object
Returns:
None
Raises:
None
Warnings:
self.N must have been set before calling
"""
self.perform_strategy(self.N)
def perform_strategy(self, counter):
"""
perform the forth strategy, that opens envelopes that are bigger with some count
Args:
counter (int): how many bigger envelops to open before stopping
Returns:
None
"""
n_biggest = [self.envelops[0].money]
i = 0
while len(n_biggest) < counter:
if i == len(self.envelops):
print('Not enough numbers')
break
if self.envelops[i].money > n_biggest[-1]:
n_biggest.append(self.envelops[i].money)
i += 1
print(str(n_biggest))
#envs = []
#for i in range(10000000):
# envs.append(Envelope())
#stra = N_max_strategy(envs)
#stra.N = 100
#stra.play()
|
bfd3fe14514baab0e66c20b18a6ff2e098781415 | hamzahibrahim/Projects-with-python | /Tkinter/YouTube video downloader.py | 1,236 | 3.5625 | 4 | from pytube import YouTube
print('===================')
# =========================
rerun = "y"
while rerun == "y":
try:
url = input('Enter the YouTube link for the video u want: \n')
the_video = YouTube(url)
# =========================
print('===================')
print('your video title: ', the_video.title)
# =========================
print('===================')
choices = the_video.streams.filter(progressive=True)
print('please choose one:','\n==================')
for i in choices:
print(i)
user_choice = int(input('Please enter your choice (by nubers(1,2,3,....)): '))
the_choice = choices[user_choice-1]
# =========================
print('===================')
print('Please wait until it finsh downloding ......')
the_choice.download()
# =========================
print('Done\' -_- \' (the video is installed in the folder you are in)')
print('===================')
except:
print('Sorrry somethng went wrong')
print('===================')
rerun = input("Enter y to rerun or any thing else to end: ")
print('===================')
|
faf268ea926783569bf7e2714589f264ed4f3554 | Teddy-Sannan/ICS3U-Unit2-02-Python | /area_and_perimeter_of_circle.py | 606 | 4.1875 | 4 | #!/usr/bin/env python3
# Created by: Teddy Sannan
# Created on: September 16
# This program calculates the area and perimeter of a rectangle
def main():
# main function
print("We will be calculating the area and perimeter of a rectangle")
print("")
# input
length = int(input("Enter the length (mm): "))
width = int(input("Enter the width (mm): "))
# process
perimeter = 2 * (length + width)
area = length * width
print("")
# output
print("Perimeter is {} mm".format(perimeter))
print("Area is {} mm^2".format(area))
if __name__ == "__main__":
main()
|
c3c084946fd1e0634b9670fc1ef058fbc4c98045 | theguythatdoes/coding-assignments | /CreateAcronym.py | 381 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 15:34:58 2020
@author: reube
"""
def acronym(phrase):
y=phrase
phrase=phrase.split(' ')
mystring=len(phrase)
s=''
for k in range(0,mystring):
n=phrase[k]
s+=n[0]
return s
if __name__=="__main__":
print(acronym("dog ate my homework"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.