blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
2028185ced3c005ace0b7cb772c21839166f34ac | Randi20/24-hour-shift-plan- | /Vagtplan2/Submit.py | 4,104 | 3.515625 | 4 | from tkinter import *
import sqlite3
from Vagtplan2.Editor import *
class Submit:
def delete(self):
# Create a database or connect to ons
conn = sqlite3.connect('vagt_plan_app.db')
# Create cursor
c = conn.cursor()
# Delete a record
c.execute("DELETE from users WHERE oid= " + self.delete_box.get())
# Commit changes
conn.commit()
# Close Connection
conn.close()
def save(self):
# Create a database or connect to ons
conn = sqlite3.connect('vagt_plan_app.db')
# Create cursor
c = conn.cursor()
# Insert Into Table
c.execute("INSERT INTO users VALUES (:f_name, :l_name, :init)",
{
'f_name': self.f_name.get(),
'l_name': self.l_name.get(),
'init': self.init.get()
}
)
# Commit changes
conn.commit()
# Close Connection
conn.close()
def show(self):
# Create a database or connect to ons
conn = sqlite3.connect('vagt_plan_app.db')
# Create cursor
c = conn.cursor()
# Query the database
c.execute("SELECT *, oid FROM users")
records = c.fetchall()
print_records = ''
# Loop thru results
for record in records:
print_records += str(record[0]) + " " + str(record[1]) + " " + "\t" + str(record[3]) + "\n"
query_label = Label(self.user, text=print_records)
query_label.grid(row=12, column=0, columnspan=2)
# Commit changes
conn.commit()
# Close Connection
conn.close()
def __init__(self):
self.user = Tk()
self.user.title("Opret bruger")
self.user.geometry("400x600")
# Create a database or connect to one
conn = sqlite3.connect('vagt_plan_app.db')
# Create cursor
c = conn.cursor()
'''
# Create table
c.execute("""CREATE TABLE users (
first_name text,
last_name text,
initialer text
)""")
'''
# Create Text Box Labels
self.f_name_label = Label(self.user, text="For navn")
self.f_name_label.grid(row=0, column=0, pady=(10, 0))
self.l_name_label = Label(self.user, text="Efter navn")
self.l_name_label.grid(row=1, column=0)
self.init_label = Label(self.user, text="Initialer")
self.init_label.grid(row=2, column=0)
self.delete_box_label = Label(self.user, text="Vælg ID nummer:")
self.delete_box_label.grid(row=7, column=0)
# Create Text Boxes
self.f_name = Entry(self.user, width=30)
self.f_name.grid(row=0, column=1, padx=20, pady=(10, 0))
self.l_name = Entry(self.user, width=30)
self.l_name.grid(row=1, column=1)
self.init = Entry(self.user, width=30)
self.init.grid(row=2, column=1)
self.delete_box = Entry(self.user, width=30)
self.delete_box.grid(row=7, column=1)
# Create a save button
save_btn = Button(self.user, text="Gem", command=self.save)
save_btn.grid(row=5, column=0, columnspan=2, pady=10, padx=10, ipadx=145)
# Create a show user button
show_btn = Button(self.user, text="Vis bruger", command=self.show)
show_btn.grid(row=6, column=0, columnspan=2, pady=10, padx=10, ipadx=135)
# Create a delete user button
show_btn = Button(self.user, text="Slet bruger", command=self.delete)
show_btn.grid(row=8, column=0, columnspan=2, pady=10, padx=10, ipadx=135)
# Create a edit user button
edit_btn = Button(self.user, text="Rediger bruger", command=Editor)
edit_btn.grid(row=9, column=0, columnspan=2, pady=10, padx=10, ipadx=135)
# Commit changes
conn.commit()
# Close Connection
conn.close()
|
7908fea42d6e688f22fbf804af1821d7d4de7b05 | VenpleD/Python_Demo | /Demo1.py | 261 | 3.546875 | 4 | import os
a = 10
print(type(a))
b = 20
print(type(b))
# c = input("请输入年龄:")
#
# d = input("请输入姓名")
#
# print("我的年龄是:%i"%(a))
# print("我的名字:{},年龄:{}".format(d, c))
if a == 10 and b == 20:
print(a, end=" ")
|
cf321557ea5cf2aea708484b321b2ace1b208afc | kyky2912/UTS_REKAYASA-APLIKASI-TERDISTRIBUSI | /server.py | 2,340 | 3.59375 | 4 | #imports
import socket
import select
HEADER= 1
IP = "127.0.0.1"
PORT = 8888
#Membuat socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Alamat socket digunakan kembali
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((IP, PORT))
server_socket.listen()
#List socket/(socket.socket())
sockets_list = [server_socket]
#List client
clients = {}
print(f'Mendapatkan koneksi baru dari {IP}:{PORT}...')
#Pesan Masuk
def receive_message(client_socket):
try:
message_header = client_socket.recv(HEADER)
#data tidak ditemukan
if not len(message_header):
return False
message_length = int(message_header.decode('utf-8').strip())
return {'header': message_header, 'data': client_socket.recv(message_length)}
except:
return False
while True:
# Notifikasi Input/Output
read_sockets, _ , exception_sockets = select.select(sockets_list, [], sockets_list)
for socket_notifikasi in read_sockets:
if socket_notifikasi == server_socket:
client_socket, client_address = server_socket.accept()
user = receive_message(client_socket)
if user is False:
continue
sockets_list.append(client_socket)
clients[client_socket] = user
print('Koneksi baru diterima dari {}:{}, username: {}'.format(*client_address, user['data'].decode('utf-8')))
else:
message = receive_message(socket_notifikasi)
if message is False:
print('Koneksi telah ditutup oleh: {}'.format(clients[socket_notifikasi]['data'].decode('utf-8')))
sockets_list.remove(socket_notifikasi)
del clients[socket_notifikasi]
continue
user = clients[socket_notifikasi]
print(f'Pesan diterima dari: {user["data"].decode("utf-8")}: {message["data"].decode("utf-8")}')
for client_socket in clients:
if client_socket != socket_notifikasi:
client_socket.send(user['header'] + user['data'] + message['header'] + message['data'])
#Handling socket exception
for socket_notifikasi in exception_sockets:
sockets_list.remove(socket_notifikasi)
del clients[socket_notifikasi]
|
6dbe84052e4841a882ecb524616868c5651860ea | virocha/EP3---DESOFT | /Tabuleiro.py | 3,417 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Insper - Engenharia 1B
Design de Software
EP3: Jogo da Velha
Vitória Rocha e Isabella Oliveira
"""
import tkinter as tk
import tkinter.messagebox as tkm
from Jogo import Jogo
class Tabuleiro:
def __init__(self):
self.meu_jogo = Jogo()
# Janela principal
self.window = tk.Tk()
self.window.title("Jogo da Velha")
self.window.geometry("450x520")
for i in range(0, 3):
self.window.rowconfigure(i, minsize=150)
self.window.columnconfigure(i, minsize=150)
self.window.rowconfigure(3, minsize=40)
# Botões
self.botoes = [[[0],[0],[0]],[[0],[0],[0]],[[0],[0],[0]]]
for i in range(0, 3):
for j in range(0, 3):
self.botoes[i][j] = tk.Button(self.window)
self.botoes[i][j].configure(height=10, width=10, command=lambda botao=(i,j): self.botao_comando(botao))
self.botoes[i][j].grid(row=i, column=j, sticky="nsew")
# Labels
self.label_indicador = tk.Label(self.window)
self.label_indicador.configure(width=60, height=1)
self.label_indicador.grid(row=3, column=0, columnspan=3, sticky="w")
self.cria_label("Primeira jogada: {0}".format(self.meu_jogo.jogador))
def cria_botoes(self, posicao, limpar_tabuleiro):
texto_botao = tk.StringVar()
texto_botao.set("")
if limpar_tabuleiro == False:
texto_botao.set(self.meu_jogo.jogador)
self.botoes[posicao[0]][posicao[1]].config(textvariable = texto_botao,\
state="disabled")
self.cria_label("Próxima Jogada: {0}".format(self.meu_jogo.proximo))
def cria_label(self, texto):
label_indicador = tk.StringVar()
label_indicador.set(texto)
self.label_indicador.configure(textvariable = label_indicador, anchor="w")
def botao_comando(self, posicao):
self.cria_botoes(posicao, False)
self.meu_jogo.recebe_jogada(posicao)
resultado = self.meu_jogo.verifica_ganhador()
if resultado == -1:
pass
elif resultado == 0:
self.quem_venceu("O jogo empatou!")
elif resultado == 1:
self.quem_venceu("Vencedor: Jogador X")
elif resultado == 2:
self.quem_venceu("Vencedor: Jogador O")
def quem_venceu(self, resultado):
self.nova_janela = tkm.askquestion("Resultado", "{0}\nDeseja começar um novo jogo?".format(resultado))
self.meu_jogo.limpa_jogadas()
self.limpa_tela()
if self.nova_janela == "no":
self.window.destroy()
def limpa_tela(self):
for i in range(0,3):
for j in range(0,3):
self.cria_botoes((i,j), True)
self.botoes[i][j].config(state="normal")
self.cria_label("Primeira Jogada: {0}".format(self.meu_jogo.jogador))
def iniciar(self):
self.window.mainloop()
class Final_Jogo:
def __init__(self):
self.Final_Jogo = tk.Tk()
self.Final_Jogo.title("Resultado do Jogo da Velha")
self.Final_Jogo.geometry("100x200")
app = Tabuleiro()
app.iniciar() |
483a246fd2716da637750e1ba1f728e2ad843455 | ChrisStreadbeck/Python | /learning_notes/dictionaries/nested_dictionaries.py | 474 | 3.984375 | 4 | teams = [
{
'astros': {
'2B': 'Altuve',
'SS': 'Correa',
'3B': 'Bregman',
}
},
{
'angels': {
'OF': 'Trout',
'DH': 'Pujols',
}
}
]
# print(teams[0])
angels = teams[1].get('angels', 'Team not found') #this is treating it like a list. We knew it was a dictionary, so .get got the values we wanted and converts it to an actual list.
print(list(angels.values())[1])
#can use all the normal things when working with a list |
f69d4a3a4e1abadb5d462889976fcaffafbdc9f8 | ChrisStreadbeck/Python | /apps/fizzbuzz.py | 705 | 4.1875 | 4 | var_range = int(input("Enter a Number to set the upper range: "))
def fizzbuzz(upper):
for num in range(1, upper):
if num != upper:
if num % 3 == 0 and num % 5 == 0:
print('FizzBuzz')
elif num % 3 == 0:
print('Fizz')
elif num % 5 == 0:
print('Buzz')
else:
print(num)
fizzbuzz(upper = var_range + 1)
# ----------------------
#without input
def fizzbuzz(upper):
for num in range(1, upper):
if num != upper + 1:
if num % 3 == 0 and num % 5 == 0:
print('FizzBuzz')
elif num % 3 == 0:
print('Fizz')
elif num % 5 == 0:
print('Buzz')
else:
print(num)
fizzbuzz(100) |
34bf9545e8d5e9189df557c957e6f3bc6442b4c9 | ChrisStreadbeck/Python | /learning_notes/functions_and_methods/named_args.py | 327 | 4.09375 | 4 | #Named Arguments
def full_name(first, last):
print(f'{first} {last}')
full_name(first = 'Kristine', last = 'Hudgens')
full_name(last = 'Hudgens', first = 'Kristine')
#order doesn't matter in python, this is more explicit. Rule of thumb
# is to use named arguments if you have more than three being called in the function. |
14adf897de38f2d27bc32c8bc7d298b9f1ffbbed | ChrisStreadbeck/Python | /learning_notes/lambdas.py | 440 | 4.1875 | 4 | #Lambda is a tool used to wrap up a smaller function and pass it to other functions
full_name = lambda first, last: f'{first} {last}'
def greeting(name):
print(f'Hi there {name}')
greeting(full_name('kristine', 'hudgens'))
#so it's basically a short hand function (inline) and it allows the name to be called
# simply later on in the second function.
#Can be used with any type of code, but it's most commonly used for mathmatics
|
3ce71d04d48488071e8bbab36fae5b8efd986809 | ChrisStreadbeck/Python | /learning_notes/lists/lists_2.py | 734 | 4.0625 | 4 | tags = ['python', 'development', 'tutorials', 'code']
number_of_tags = len(tags) #remember 4 means index 0 to 3
last_item = tags[-1] #shows last value item in the list
index_of_last_item = tags.index(last_item) #gives index of last item when paired with the line before.
print(number_of_tags)
print(last_item)
print(index_of_last_item)
# List Sorting
#python sorts by the index order when imported into the list
print(tags)
tags.sort() #puts them in alphabetical
print(tags)
tags.sort(reverse=True) #inverse alphabetical order
print(tags)
totals = [234, 1, 543, 2345]
print(totals)
totals.sort() # sorts smallest number to biggest number
print(totals)
totals.sort(reverse=True) #inverse numerical order
print(totals) |
7182f0c5e9e969fd8d9f3eb17e2a8946bfb3e224 | ChrisStreadbeck/Python | /apps/annoying_toddler_sim.py | 282 | 3.96875 | 4 | from random import choice
questions = ["Why was Prince Hans mean?", "Why Anna punch him?", "Why did Elsa run away?"]
question = choice(questions)
answer = input(question).strip().lower
while answer !="just because":
answer = input("but.. why? ").strip().lower()
print("Oh.. Okay") |
e0f419a4c740d58617078e0483afc3cabf69e4b9 | ChrisStreadbeck/Python | /learning_notes/if_elif_else.py | 190 | 4.1875 | 4 | num1 = 10
num2 = 5
if num1 > num2:
print("num1 is bigger than num2")
elif num1 == num2:
print("num1 is equal to num2")
elif num1 < num2:
print("num2 is bigger than num1")
|
9abb45d4fcf7d9f851bf4c92a3dc9354be857976 | bespokeeagle/Cousera-Python-re-up | /web-scrapper.py | 1,008 | 4 | 4 | #Scraping Numbers from HTML using BeautifulSoup In this assignment you will write a Python program similar to
#The program will use urllib to read the HTML from the data files below, and parse the data, extracting numbers and compute the sum of the numbers in the file.
# import statements to enable GET requests
import urllib.request, urllib.parse, urllib.error
from urllib.request import urlopen
g = []
# import statements for Beautiful soup
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# enter url
url = input ("enter: ")
# open url and read it
x = urlopen(url,context=ctx).read()
# parse url url using beautiful soup
s = BeautifulSoup(x,'html.parser')
# search for and give me lines with span
tags = s("span")
# loop through said lines
for tag in tags:
print (tag)
for t in tag:
# a second loop to get the numbers out
g.append(int (t))
print (sum(g))
|
f91112d5f2d441cb357b52d77aa72c74d586fc73 | Shady-Data/05-Python-Programming | /studentCode/Recursion/recursive_lines.py | 928 | 4.53125 | 5 | '''
3. Recursive Lines
Write a recursive function that accepts an integer argument, n. The function should display
n lines of asterisks on the screen, with the first line showing 1 asterisk, the second line
showing 2 asterisks, up to the nth line which shows n asterisks.
'''
def main():
# Get an intger for the number of lines to print
num_lines = int(input('Enter the number of lines to print: '))
# call the recursive_lines function with the start of 1 and end of num_lines
recursive_lines('*', num_lines)
# define the recursive_lines function
# parameters: str pat, int num_lines
def recursive_lines(p_pat, p_stop):
# base case if len(p_pat) == p_stop
if len(p_pat) == p_stop:
print(p_pat)
else:
# print the pattern and return recursive lines p_pat + '*', p_stop
print(p_pat)
return recursive_lines(p_pat + '*', p_stop)
# Call the main function
main() |
dfc8a8902bff7cb34efefbf67ea932c241be6b7f | Shady-Data/05-Python-Programming | /studentCode/zip_func.py | 323 | 3.734375 | 4 | # zip() function
# This is a good way to take 2 different sequences of
# data and pair them together
# set up 2 lists
prices = [72.51, 9.27, 153.74, 30.23, 53.00]
names = ["CAT", 'GE', 'MSFT', 'AA', 'IBM']
# use for loop and zip() to pair lists together
for name, price in zip(names, prices):
print(name, '=', price)
|
44147daf5db0fb48d23759c14e23515af7edf827 | Shady-Data/05-Python-Programming | /studentCode/filter_func.py | 624 | 4.09375 | 4 | # filter()
# Takes in two arguments, function and an iterable
# Only returns items in the list that are True
def isPrime(x):
for n in range(2, x):
if x % n == 0:
return False
return True
filterObject = filter(isPrime, range(10))
print('Prime numbers between 1-10: ', list(filterObject))
# filter applied with lambda
filterObject2 = filter(lambda x: x % 2 == 0, range(10))
print(list(filterObject2))
# filter on a random list
randomlist = [1, 'a', 0, False, True, '0']
filteredList = filter(None, randomlist)
print('The filtered elements are ')
for element in filteredList:
print(element) |
db773a98b8c70a91aab88dc6c38c30c73bdd87c6 | Shady-Data/05-Python-Programming | /studentCode/Trivia/pickle_trivia_ques.py | 960 | 3.546875 | 4 | import pickle
import csv
from random import randint
def main():
with open('Trivia_v2.csv', 'r') as csv_file:
csv_read = csv.reader(csv_file)
csv_list = []
for line in csv_read:
csv_list.append(line)
questions = []
answers = []
correct = []
for line in csv_list:
questions.append(line[0])
answers.append([line[1]])
correct.append(line[1])
for ans in answers:
while len(ans) < 4:
rng = randint(0, len(correct) - 1)
if correct[rng] not in ans:
ans.append(correct[rng])
question_bank = []
for ind in range(len(questions)):
quest = []
quest.append(questions[ind])
for ans in answers[ind]:
quest.append(ans)
quest.append(correct[ind])
question_bank.append(quest)
with open('trivia-v2.dat', 'wb') as outfile:
pickle.dump(question_bank, outfile)
main() |
671db6f7df24c7f99178b538dc8cdfe44b33a7c2 | Shady-Data/05-Python-Programming | /studentCode/Recursion/forever_recursion.py | 249 | 3.640625 | 4 | # Endless recursion
def forever_recursion(times):
annoying_message(times)
def annoying_message(times):
if times > 0:
print('Nudge Nudge, Wink Wink, Say No More Say No More')
annoying_message(times -1)
forever_recursion(995) |
630e3b1afa907f03d601774fa4aec19c8ae1fbbb | Shady-Data/05-Python-Programming | /studentCode/cashregister.py | 1,718 | 4.3125 | 4 | '''
Demonstrate the CashRegister class in a program that allows the user to select several
items for purchase. When the user is ready to check out, the program should display a list
of all the items he or she has selected for purchase, as well as the total price.
'''
# import the cash register and retail item class modules
import CashRegisterClass
import RetailItemClass as ri
from random import randint
# generate a list of retail item to test with
items = {
'Jacket': {'desc': 'Jacket', 'units' : 12, 'price' : 59.95},
'Designer Jeans': {'desc': 'Designer Jeans', 'units' : 40, 'price' : 34.95},
'Shirt': {'desc': 'Shirt', 'units' : 20, 'price' : 24.95}
}
# Create and empty list to store the items
retail_items = []
# generate an object for each entry
for key in items.keys():
# add the object to the list
retail_items.append(ri.RetailItem(items[key]['desc'], items[key]['units'], items[key]['price']))
def main():
# Instanstiate a Class Register object
register = CashRegisterClass.CashRegister()
# add an item to the cash register
register.purchase_item(retail_items[randint(0, 2)])
# display the items in the register
# register.show_items()
# add 5 more items to the register
for x in range(5):
register.purchase_item(retail_items[randint(0, 2)])
print('Show items before clear:')
# Display the details of the items purchased
register.show_items()
# display the total of the items
print(f'\n\tTotal: ${register.get_total():,.2f}')
# clear the register
register.clear()
print('\nShow Items after clear:')
# display the items in the register
register.show_items()
# call the main function
main() |
6849e93f6a59e6e69fe7346ae49974ba4729e240 | Shady-Data/05-Python-Programming | /studentCode/Trivia/triviagame.py | 5,044 | 4.34375 | 4 | '''
8. Trivia Game
In this programming exercise you will create a simple trivia game for two players. The program will
work like this:
• Starting with player 1, each player gets a turn at answering 5 trivia questions. (There
should be a total of 10 questions.) When a question is displayed, 4 possible answers are
also displayed. Only one of the answers is correct, and if the player selects the correct
answer, he or she earns a point.
• After answers have been selected for all the questions, the program displays the number
of points earned by each player and declares the player with the highest number of points
the winner.
To create this program, write a Question class to hold the data for a trivia question. The
Question class should have attributes for the following data:
• A trivia question
• Possible answer 1
• Possible answer 2
• Possible answer 3
• Possible answer 4
• The number of the correct answer (1, 2, 3, or 4)
The Question class also should have an appropriate __init__ method, accessors, and
mutators.
The program should have a list or a dictionary containing 10 Question objects, one for
each trivia question. Make up your own trivia questions on the subject or subjects of your
choice for the objects.
'''
# import the question and player classes
from QuestionClass import Question, Player
from os import system
import random
import pickle
def main():
# generate a dictionary of questions
questionsbank = generate_questionbank(10)
# Get the players
players = get_players()
# play the game
play_game(questionsbank, players)
def generate_questionbank(p_amount):
# load a question list
with open('trivia-v2.dat', 'rb') as read_file:
all_questions = pickle.load(read_file)
# start an empty list to store the questions
game_questions = []
# get random questions until p_amount is hit or all questions is empty
while len(game_questions) < p_amount:
# RNG
rdm_index = random.randint(0, len(all_questions) - 1)
rdm_ans = []
while len(rdm_ans) < 4:
rng = random.randint(1, 4)
if rng not in rdm_ans:
rdm_ans.append(rng)
# generate the question
rdm_q = all_questions[rdm_index]
correct = -1
for ind, rng in enumerate(rdm_ans):
if rdm_q[rng] == rdm_q[5]:
correct = ind + 1
gen_question = Question(rdm_q[0], rdm_q[rdm_ans[0]], rdm_q[rdm_ans[1]], rdm_q[rdm_ans[2]], rdm_q[rdm_ans[3]], correct)
# add the generated question object to the game questions
game_questions.append(gen_question)
# return the game questions list
return game_questions
def get_players():
# prompt for a number of players
try:
amount = int(input('How many players sill be playing? '))
except ValueError:
print('Bad Input: setting to default: 2')
amount = 2
# create an empty player list
players = []
# add the players
for num in range(1, amount + 1):
name = input(f'Enter Player {num}\'s name: ')
players.append(Player(name))
# return the list of players
return players
def play_game(p_questions, p_players):
# Iterate through the questions
for num, q in enumerate(p_questions):
possible_ans = [q.get_possible_1(), q.get_possible_2(), q.get_possible_3(), q.get_possible_4()]
# iterate through the players
for p in p_players:
clear_screen()
# display player's turn
print(f'\n\n\tIt\'s {p.get_name()}')
# wait for player input for load the question (maybe add timer)
input("Press any key to get your question...")
# display the question
print(f'\n{num + 1}: {q.get_question()}')
print('\n')
# display the possible answers
for ind, ans in enumerate(possible_ans):
print(f'\t{ind + 1}) {ans}')
print()
# Prompt for player's answer
play = 0
while play <= 0 or play >= 5:
try:
play = int(input(f'{p.get_name()}\'s Answer? (1,2,3,4): '))
except ValueError:
print('Invalid choice!')
play = 0
if play == q.get_correct():
p.add_points()
# once all players and questions have been iterated through
clear_screen()
# iterate through the players and print their scores
highest_score = p_players[0]
for player in p_players:
print(f'{player.get_name()} : Scored {player.get_points()} Points')
if player.get_points() > highest_score.get_points():
highest_score = player
# print player win statement
print(f'{highest_score.get_name()} Wins!')
def clear_screen():
system('cls')
# call the main function
main() |
443db5f0cfbc98abc074444ad8fccdf4a891491c | Shady-Data/05-Python-Programming | /studentCode/CellPhone.py | 2,681 | 4.53125 | 5 | """
Wireless Solutions, Inc. is a business that sells cell phones and wireless service.
You are a programmer in the company’s IT department, and your team is designing a program to manage
all of the cell phones that are in inventory. You have been asked to design a class that represents
a cell phone. The data that should be kept as attributes in the class are as follows:
• The name of the phone’s manufacturer will be assigned to the __manufact attribute.
• The phone’s model number will be assigned to the __model attribute.
• The phone’s retail price will be assigned to the __retail_price attribute.
The class will also have the following methods:
• An __init__ method that accepts arguments for the manufacturer, model number,
and retail price.
• A set_manufact method that accepts an argument for the manufacturer. This
method will allow us to change the value of the __manufact attribute after the object has been created, if necessary.
• A set_model method that accepts an argument for the model. This method will allow
us to change the value of the __model attribute after the object has been created, if
necessary.
• A set_retail_price method that accepts an argument for the retail price. This
method will allow us to change the value of the __retail_price attribute after the
object has been created, if necessary.
• A get_manufact method that returns the phone’s manufacturer.
• A get_model method that returns the phone’s model number.
• A get_retail_price method that returns the phone’s retail price.
"""
class CellPhone:
# define the __init__ method with 3 attributes
def __init__(self, p_manufacturer, p_model, p_msrp):
self.__manufact = p_manufacturer
self.__model = p_model
self.__retail_price = p_msrp
# define set_manufact to modify the __manufact attribute, if necessary
def set_manufact(self, p_manufact):
self.__manufact = p_manufact
# define set_model to modify the __model attribute, if necessary
def set_model(self, p_model):
self.__model = p_model
# define set_retail_price to modify the __retail_price attribute, if necessary
def set_retail_price(self, p_msrp):
self.__retail_price = p_msrp
# define get_manufact to return the __manufact attribute
def get_manufact(self):
return self.__manufact
# define get_model to return the __model attribute
def get_model(self):
return self.__model
# define get_retail_price to return the __retail_price attribute
def get_retail_price(self):
return self.__retail_price |
915a6111d78d3bd0566d040f9342ddb59239c467 | Shady-Data/05-Python-Programming | /studentCode/Recursion/recursive_printing.py | 704 | 4.46875 | 4 | '''
1. Recursive Printing
Design a recursive function that accepts an integer argument, n, and prints the numbers 1
up through n.
'''
def main():
# Get an integer to print numbers up to
stop_num = int(input('At what number do you want this program to stop at: '))
# call the recursive print number and pass the stop number
recursive_print(1, stop_num)
# define the recursive_print function the start parameter the stop parameter
def recursive_print(p_start, p_stop):
# base case, print 1
if p_start == p_stop:
print(p_stop)
# recursive case
else:
print(p_start)
return recursive_print(p_start + 1, p_stop)
# call the main function
main() |
5a229c15df2083e3cc76075b6b555611f041c57b | Shady-Data/05-Python-Programming | /studentCode/notes_master/tree_definitions.py | 3,517 | 3.734375 | 4 | '''
Binary Tree is a tree data structure in which each node has at most two children which are left child and right child
- top node is root
Complete binary tree - every level, except possibly the last, is completely filled and all nodes in the last level are as far left as possible
Full binary tree - A full binary tree (referred to as a proper or plane binary tree) is a tree where every node except the leaves has two children
Tree Traversal - process of visiting (checking and/or updating) each node in a tree data structure, exactly once
Unlike linked lists, one-dimensional arrays, etc., which are traversed in linear order, trees may be traveresed in multiple-ways.
depth-first order, pre-order, post-order, in-order
pre-order - check if the current node is empty
display the data part of the root or current node
traverse the left subtree by recursively calling the pre-order function
traverse the right subtree by recursively calling the pre-order function
in-order - check if the current node is empty
traverse the left subtree by recursively calling the in-order function
display the data part of the root or current node
traverse the right subtree by recursively calling the in-order function
post-order -check if the current node is empty
traverse the left subtree by recursively calling the in-order function
traverse the right subtree by recursively calling the in-order function
display the data part of the root or current node
'''
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
def __init__(self, root):
self.root = TreeNode(root)
def print_tree(self, traversal_type):
if traversal_type == 'preorder':
return self.preorder_print(self.root, '') # start with an empty string that will fill out
if traversal_type == 'inorder':
return self.inorder_print(self.root, '') # start with an empty string that will fill out
if traversal_type == 'postorder':
return self.postorder_print(self.root, '') # start with an empty string that will fill out
def preorder_print(self, start, traversal):
# root --> left --> right
if start:
traversal += (str(start.value) + '-')
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
def inorder_print(self, start, traversal):
# left --> root --> right
if start:
traversal = self.inorder_print(start.left, traversal)
traversal += (str(start.value) + '-')
traversal = self.inorder_print(start.right, traversal)
return traversal
def postorder_print(self, start, traversal):
# left --> right --> root
if start:
traversal = self.postorder_print(start.left, traversal)
traversal = self.postorder_print(start.right, traversal)
traversal += (str(start.value) + '-')
return traversal
bt = BinaryTree('D')
bt.root.left = TreeNode('B')
bt.root.left.left = TreeNode('A')
bt.root.left.right = TreeNode('C')
bt.root.right = TreeNode('F')
bt.root.right.left = TreeNode('E')
bt.root.right.right = TreeNode('G')
print(bt.print_tree('preorder'))
print(bt.print_tree('inorder'))
print(bt.print_tree('postorder')) |
c4d39fadba7f479ce554198cd60c7ce4574c2d6b | Shady-Data/05-Python-Programming | /studentCode/Recursion/sum_of_numbers.py | 874 | 4.40625 | 4 | '''
6. Sum of Numbers
Design a function that accepts an integer argument and returns the sum of all the integers from 1 up
to the number passed as an argument. For example, if 50 is passed as an argument, the function will
return the sum of 1, 2, 3, 4, . . . 50. Use recursion to calculate the sum.
'''
def main():
# get the stop number
stop_num = int(input('Enter the number to stop at: '))
# print the return of the sum_of_nums function with stop_num as an argument
print(sum_of_nums(stop_num))
# Debug check print sum of ints in range + 1
# print(sum([x for x in range(stop_num + 1)]))
# Define sum_of_nums() function
# parameters: p_stop
def sum_of_nums(p_stop):
# base case:
if p_stop == 0:
return 0
# recursive case:
else:
return p_stop + sum_of_nums(p_stop - 1)
# Call the main function
main() |
a8d51535c905c2f78445f2cfb6c607d163a96330 | stufflebear/connect4 | /connect4.py | 1,541 | 3.578125 | 4 | import sys
from grid import Grid
class Connect4():
"""
Plays Terminal Connect 4
"""
def __init__(self):
self.grid = Grid()
self.lastMove = -1
def runGame(self):
p1sTurn = False
self.grid.printGrid()
self.nextMove(1)
while not self.grid.isWinningState(self.lastMove) and not self.grid.isFull():
self.grid.printGrid()
if p1sTurn:
self.nextMove(1)
p1sTurn = False
else:
self.nextMove(2)
p1sTurn = True
self.grid.printGrid()
if self.grid.isFull():
print "Oh no! The grid filled up! :("
return
if p1sTurn:
print "Congrats Player 2 - You win!"
else:
print "Congrats Player 1 - You win!"
def nextMove(self, player):
"""
Read and eval the next move
"""
rawInput = raw_input("Please enter a column player " + str(player) + ": ")
while not self.isValidInput(rawInput) or not self.grid.canInsert(int(rawInput)):
rawInput = raw_input("Please enter a number from 0 to " + str(self.grid.getNumCols()) + " for a column that is not full: ")
col = int(rawInput)
self.grid.insertToken(col, player)
self.lastMove = col
def isValidInput(self, col):
return col in [str(num) for num in range(0, self.grid.getNumCols())]
if __name__ == "__main__":
game = Connect4()
game.runGame()
|
2ab8916d18ca47e2ec254c41a45a6ddb2db7e55a | GoncaloFerreira00/Python-Algorithms | /CountVowels.py | 537 | 3.65625 | 4 | vogais = ['a','e', 'i', 'o', 'u']
frequencia = [0, 0, 0, 0, 0]
palavra = input("Digite uma palavra: ")
for i in palavra.lower():
if i in vogais:
indexVogais = vogais.index(i)
value = frequencia[indexVogais]
frequencia[indexVogais] = value + 1
print("ocorrências com a vogal A: ", frequencia[0])
print("ocorrências com a vogal E: ", frequencia[1])
print("ocorrências com a vogal I: ", frequencia[2])
print("ocorrências com a vogal O: ", frequencia[3])
print("ocorrências com a vogal U: ", frequencia[4]) |
b9c6aa7aa70c2f28eae154e5d4a6c3d326822713 | sdvornikov/thermostat-master | /local_store.py | 2,306 | 3.609375 | 4 | import sqlite3
from sqlite3 import Error
sql_create_sensors_table = """ CREATE TABLE IF NOT EXISTS sensor (
id integer PRIMARY KEY,
name text NOT NULL
); """
sql_create_data_table = """ CREATE TABLE IF NOT EXISTS data (
id integer PRIMARY KEY,
data text NOT NULL,
ts text NOT NULL,
sensor_id integer NOT NULL,
FOREIGN KEY(sensor_id) REFERENCES sensor(id)
); """
class LocalStorage:
def __init__(self, db_file):
self.__conn = self.create_connection(db_file)
self.create_table(sql_create_sensors_table)
self.create_table(sql_create_data_table)
def create_table(self, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = self.__conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def init_sensor(self, name):
""" creates a record for the sensor.
:param name: sensor's name
:return: sensor id
"""
try:
c = self.__conn.cursor()
c.execute('SELECT * FROM sensor WHERE name=?', (name,))
row = c.fetchone()
if row is None:
c.execute('INSERT INTO sensor (name) VALUES (?)', (name,))
self.__conn.commit()
return c.lastrowid
return row[0]
except Error as e:
print(e)
def log_sensor_data(self, sensor_id, data):
try:
c = self.__conn.cursor()
c.execute("INSERT INTO data(data, ts, sensor_id) VALUES (?, datetime('now'), ?)", (data, sensor_id))
self.__conn.commit()
except Error as e:
print(e)
def create_connection(self, file_name):
try:
conn = sqlite3.connect(file_name)
return conn
except Error as e:
print(e)
return None
|
fd2dff6222f7014bd6bebded1968d787a395e4b6 | fouad20-meet/YL1-201819 | /lab7_8.py | 243 | 3.90625 | 4 | class Cake():
def __init__(self,flavor):
self.flavor = flavor
def eat(self):
print("Yummy!!! Eating a " + self.flavor + " cake :)")
cake = Cake("chocolate")
cake.eat()
# what I want to be printed: Yummy!!! Eating a chocolate cake :)
|
96387763eafc4c2ee210c866e43f30ebd9fbb6b5 | Vinod096/learn-python | /lesson_02/personal/chapter_4/14_pattern.py | 264 | 4.25 | 4 | #Write a program that uses nested loops to draw this pattern:
##
# #
# #
# #
# #
number = int(input("Enter a number : "))
for r in range (number):
print("#", end="",sep="")
for c in range (r):
print(" ", end="",sep="")
print("#",sep="")
|
d4420e85272e424bdf66086eda6912615d805096 | Vinod096/learn-python | /lesson_02/personal/chapter_3/09_wheel_color.py | 1,617 | 4.4375 | 4 | #On a roulette wheel, the pockets are numbered from 0 to 36. The colors of the pockets are
#as follows:
#• Pocket 0 is green.
#• For pockets 1 through 10, the odd-numbered pockets are red and the even-numbered
#pockets are black.
#• For pockets 11 through 18, the odd-numbered pockets are black and the even-numbered
#pockets are red.
#• For pockets 19 through 28, the odd-numbered pockets are red and the even-numbered
#pockets are black.
#• For pockets 29 through 36, the odd-numbered pockets are black and the even-numbered
#pockets are red.
#Write a program that asks the user to enter a pocket number and displays whether the
#pocket is green, red, or black. The program should display an error message if the user
#enters a number that is outside the range of 0 through 36.
number = int(input("enter a number : "))
if number >= 0 and number <= 36:
print("number is in range")
else:
print("out of range")
if number == 0:
print("green")
if number >= 1 and number < 10:
if number % 2 == 0 :
print("odd-numbered pockets are red")
else:
print("even-numbered pockets are black")
if number >= 11 and number <= 18:
if number % 2 == 0 :
print("even-numbered pockets are red")
else:
print("odd-numbered pockets are black")
if number >= 19 and number <= 28:
if number % 2 == 0 :
print("even-numbered pockets are black.")
else:
print("odd-numbered pockets are red")
if number >= 29 and number <= 36:
if number % 2 == 0:
print("even-numbered pockets are red")
else:
print("odd-numbered pockets are black")
|
6411437fe4e73b46d8756a61d44f929a83c8dbf7 | Vinod096/learn-python | /lesson_02/personal/chapter_6/03_line_numbers.py | 386 | 4.34375 | 4 | #Write a program that asks the user for the name of a file. The program should display the
#contents of the file with each line preceded with a line number followed by a colon. The
#line numbering should start at 1.
count = 0
file = str(input("enter file name :"))
print("file name is :", file)
content = open(file, 'r')
for i in range(0, 10):
i += count + 1
print(f"{i} :",i)
|
b09e8d2cd18d517e904889ecf2809f1f1392e7eb | Vinod096/learn-python | /lesson_02/personal/chapter_4/12_population.py | 1,321 | 4.71875 | 5 | #Write a program that predicts the approximate size of a population of organisms. The
#application should use text boxes to allow the user to enter the starting number of organisms,
#the average daily population increase(as a percentage), and the number of days the
#organisms will be left to multiply. For example, assume the user enters the following values:
#Starting number of organisms: 2
#Average daily increase: 30%
#Number of days to multiply: 10
#The program should display the following table of data:
#Day Approximate Population
#1 2
#2 2.6
#3 3.38
#4 4.394
#5 5.7122
#6 7.42586
#7 9.653619
#8 12.5497
#9 16.31462
#10 21.209
size = 0
Starting_number_of_organisms = int(input("Starting_number_of_organisms : "))
daily_increase = int(input("daily increase : "))
Average_daily_increase = daily_increase / 100
print("Average daily increase :",Average_daily_increase)
number_of_days_to_multiply = int(input("number_of_days_to_multiply : "))
print("Day Approximate Population :")
for number_of_days_to_multiply in range (1,number_of_days_to_multiply + 1):
Starting_number_of_organisms = (Starting_number_of_organisms * Average_daily_increase) + Starting_number_of_organisms
print(f"{number_of_days_to_multiply} {Starting_number_of_organisms}")
|
f5a8090ff67003d79e2f431256d4b277381c8dd7 | Vinod096/learn-python | /lesson_02/personal/chapter_3/01_Day.py | 757 | 4.40625 | 4 | #Write a program that asks the user for a number in the range of 1 through 7. The program
#should display the corresponding day of the week, where 1 = Monday, 2 = Tuesday,
#3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday, and 7 = Sunday. The program should
#display an error message if the user enters a number that is outside the range of 1 through 7.
days_number = int(input("Enter a number : "))
if days_number == 1 :
print("monday")
elif days_number == 2 :
print("tuesday")
elif days_number == 3 :
print("wednesday")
elif days_number == 4 :
print("thursday")
elif days_number == 5 :
print("friday")
elif days_number == 6 :
print("saturday")
elif days_number == 7 :
print("sunday")
else:
print("out of days_number") |
322e33e0feb4d816a5b812a1bf8d60be1559cc91 | Vinod096/learn-python | /lesson_02/personal/functions/food.py | 2,581 | 3.9375 | 4 | from secrets import choice
from tkinter.messagebox import YES
from sqlalchemy import true
from sympy import And
def customer():
user = str(input("What type of food you requried : "))
if user == 'burgers':
print("Food item is available")
else:
print("You've entered unavailable item ")
exit()
return user
def order_burgers(user) :
food_burgers = []
burgers = {'McDonalds': 'McSpicy Chicken Burger, 20$','Hungry Jacks': 'Double Tender Crispy Chicken Burger,15$', 'Grilld': 'Chicken Burger, 25$ \n Beef Burger, 15$'}
while (True):
restuarant_name = str(input("Enter name of the resturant : "))
if (restuarant_name == 'McDonalds'):
print ("Resturant contains following Burgers : \n ",burgers['McDonalds'])
food_burgers.append(burgers['McDonalds'])
choice = input('Do you want to more food items (Yes / No ) : ')
if choice == "yes":
continue
elif choice == "no":
print("Thanks for Ordering..!")
print("Your order has been sent to Restaurant. Enjoy your food")
return True
if (restuarant_name == 'Grilld'):
print("Resturant contains following Burgers : \n", burgers['Grilld'])
food_burgers.append(burgers['Grilld'])
choice = input('Do you want to more food items (Yes / No ) : ')
if choice == "yes":
continue
elif choice == "no":
print("Thanks for Ordering..!")
print("Your order has been sent to Restaurant. Enjoy your food")
return True
if (restuarant_name == 'Hungry Jacks'):
print("Resturant contains following Burgers : \n ", burgers['Hungry Jacks'])
food_burgers.append(burgers['Hungry Jacks'])
choice = input('Do you want to more food items (Yes / No ) : ')
if choice == "yes":
continue
elif choice == "no":
print("Thanks for Ordering..!")
print("Your order has been sent to Restaurant. Enjoy your food")
return True
else:
print("Please enter valid restaurant name")
break
return food_burgers
def main() :
person = customer()
burgers_order = order_burgers(person)
main()
|
e0b176c877b9b553dbcee2b6124cfde4dd4c128c | Vinod096/learn-python | /lesson_02/personal/For_loop/scrimba.py | 220 | 4.15625 | 4 | names = ['Jane','John','Alena']
names_1 = ['John','Jane','Adeev']
text = 'Welcome to the party'
names.extend(names_1)
for name in range(1):
names.append(input("enter name :"))
for name in names:
print(name,text)
|
7feb19a5121eeb321f0b2a187852cae0becb4c4f | Vinod096/learn-python | /lesson_02/personal/chapter_2/ingredient.py | 1,022 | 4.40625 | 4 | total_no_of_cookies = 48
cups_of_sugar = 1.5
cups_of_butter = 1
cups_of_flour = 2.75
no_of_cookies_req = round(int(input("cookies required :")))
print("no of cookies required in roundup : {0:2f} ".format(no_of_cookies_req))
req_sugar = (no_of_cookies_req / total_no_of_cookies) * cups_of_sugar
print("no of cups of sugar_required : {0:.2f}".format(req_sugar))
req_butter = (no_of_cookies_req / total_no_of_cookies) * cups_of_butter
print("no of cups of butter_required : {0:.2f}".format(req_butter))
flour_req = (no_of_cookies_req / total_no_of_cookies) * cups_of_flour
print("no of cups of flour_required : {0:.2f}".format(flour_req))
#Question :
#A cookie recipe calls for the following ingredients:
#• 1.5 cups of sugar
#• 1 cup of butter
#• 2.75 cups of flour
#The recipe produces 48 cookies with this amount of the ingredients. Write a program that
#asks the user how many cookies he or she wants to make, and then displays the number of
#cups of each ingredient needed for the specified number of cookies.
|
3689740b0bc43992cf29f1ddcff04c88dbaf0705 | Vinod096/learn-python | /lesson_02/personal/chapter_2/stock.py | 2,466 | 3.90625 | 4 | #12. S tock Transaction Program
#Last month Joe purchased some stock in Acme Software, Inc. Here are the details of the
#purchase:
#• The number of shares that Joe purchased was 2, 000.
#• When Joe purchased the stock, he paid $40.00 per share.
#• Joe paid his stockbroker a commission that amounted to 3 percent of the amount he
#paid for the stock.
#Two weeks later Joe sold the stock. Here are the details of the sale:
#• The number of shares that Joe sold was 2, 000.
#• He sold the stock for $42.75 per share.
#• He paid his stockbroker another commission that amounted to 3 percent of the amount
#he received for the stock.
#Write a program that displays the following information:
#• The amount of money Joe paid for the stock.
#• The amount of commission Joe paid his broker when he bought the stock.
#• The amount that Joe sold the stock for.
#• The amount of commission Joe paid his broker when he sold the stock.
#• Display the amount of money that Joe had left when he sold the stock and paid his
#broker(both times). If this amount is positive, then Joe made a profit. If the amount is
#negative, then Joe lost money.
shares_purchased = 2000
print("Number of shares purchased :",shares_purchased)
amount_paid_per_share = 40.00
print("Amount paid for each share :",amount_paid_per_share)
stockbroker_commission = 3 / 100
print("Commission paid to stockbroker :",stockbroker_commission)
shares_sold = 2000
print("Number of shares sold :",shares_sold)
sold_amount_per_share = 42.75
print("Price of each share when selling :",sold_amount_per_share)
stockbroker_commission = 3 / 100
print("Commission paid to stockbroker for selling shares :", stockbroker_commission)
Amount_paid_for_purchasing_of_shares = shares_purchased * amount_paid_per_share
print("Amount_paid_for_purchasing_of_shares :",Amount_paid_for_purchasing_of_shares)
Commission_while_Purchasing = Amount_paid_for_purchasing_of_shares * stockbroker_commission
print("Commission paid for purchasing :",Commission_while_Purchasing)
Sold_stock_amount = sold_amount_per_share * shares_purchased
print("Total amount after selling shares :",Sold_stock_amount)
Commission_while_Selling = Sold_stock_amount * stockbroker_commission
print("Commission for selling :",Commission_while_Selling)
Total_amount_with_Joe = (Sold_stock_amount - Commission_while_Selling - Commission_while_Purchasing)
print("Total amount left over with Joe :",Total_amount_with_Joe)
|
dd42d5e406efde3b62d76588eeb37a7470edafe8 | Vinod096/learn-python | /lesson_02/personal/chapter_8/01_initials.py | 463 | 4.5 | 4 | #Write a program that gets a string containing a person’s first, middle, and last names,and then display their first, middle, and last initials. For example, if the user enters John William Smith the program should display J. W. S.
first_name = str(input("Enter First Name : "))
middle_name = str(input("Enter Middle Name : "))
last_name = str(input("Enter Last Name : "))
print("Initials of persons names : ", '\n',first_name[0],'\n', middle_name[0],'\n', last_name[0])
|
ad1f65388986962de297bba5f1219809634fccd3 | Vinod096/learn-python | /lesson_02/personal/chapter_4/09_ocean.py | 380 | 4.28125 | 4 | #Assuming the ocean’s level is currently rising at about 1.6 millimeters per year, create an
#application that displays the number of millimeters that the ocean will have risen each year
#for the next 25 years.
rising_oceans_levels_per_year = 1.6
years = 0
for i in range (1,26):
years = rising_oceans_levels_per_year * i
print(f"rising levels per {i} year : {years}")
|
da15e6e27a561aa3c7bb1f3d377f9b999482bbf7 | Vinod096/learn-python | /lesson_02/personal/chapter_2/temperature.py | 103 | 3.71875 | 4 | Celsius = float(input("enter the celsius : "))
far = 9 * ( Celsius / 5 ) + 32
print(Celsius)
print(far) |
80906ba30bc751f48e177907ab2967803c269022 | Vinod096/learn-python | /lesson_02/personal/chapter_5/12_Maximum_of_Two_Values.py | 867 | 4.625 | 5 | #Write a function named max that accepts two integer values as arguments and returns the
#value that is the greater of the two. For example, if 7 and 12 are passed as arguments to
#the function, the function should return 12. Use the function in a program that prompts the
#user to enter two integer values. The program should display the value that is the greater
#of the two.
def value_1():
number_1 = int(input("enter value 1 : "))
return number_1
def value_2():
number_2 = int(input("enter value 2 : "))
return number_2
def max(value_1,value_2):
if value_1 > value_2 :
return value_1
else:
return value_2
def main():
number_1 = value_1()
number_2 = value_2()
max_value = max(number_1,number_2)
print("number 1 :",number_1)
print("number 2 :",number_2)
print("greater number :",max_value)
main() |
83b9e523b3ff90d47c7689f3293b77a16d05a965 | Vinod096/learn-python | /lesson_02/personal/chapter_5/06_calories.py | 1,078 | 4.65625 | 5 | #A nutritionist who works for a fitness club helps members by evaluating their diets. As part
#of her evaluation, she asks members for the number of fat grams and carbohydrate grams
#that they consumed in a day. Then, she calculates the number of calories that result from
#the fat, using the following formula:
#calories from fat = fat grams * 9
#Next, she calculates the number of calories that result from the carbohydrates, using the
#following formula:
#calories from carbs= carb grams * 4
#The nutritionist asks you to write a program that will make these calculations.
def fat():
fat_grams = float(input("Enter fat grams :"))
calories_from_fat = fat_grams * 9
return calories_from_fat
def carbohydrates():
carb_grams = float(input("Enter Carbohydrates :"))
calories_from_carbs = carb_grams * 4
return calories_from_carbs
def calculations():
C_fat = fat()
C_carbohydrates = carbohydrates()
print("Calories from fat is :{0:.2f}".format(C_fat))
print("calories from carbohydrates :{0:.2f}".format(C_carbohydrates))
calculations()
|
0b4bd4faeb2a1fdc777b1d1dd799be3cd68d7ba9 | LDoubleZhi/PythonLearn | /eg.py | 744 | 3.53125 | 4 | # encoding:utf-8
def DemoString():
stra = 'hello world'
print stra.capitalize()
def Dict():
dicta = {'a': 1, 'b': 2}
print 1, dicta
print 2, dicta.keys(), dicta.values()
for key, value in dicta.items():
print key, value
class User:
type = 'USER'
def __init__(self, name, uid):
self.name = name
self.uid = uid
def __repr__(self):
return 'im' + self.name + ' ' + str(self.uid)
class Admin(User):
type = 'ADMIN'
def __init__(self, name, uid, group):
User.__init__()
self.group = group
def __repr__(self):
return 'im' + self.name + ' ' + str(self.uid) + ' ' + self.group
if __name__ == '__main__':
# Dict()
# print 'hello world !!'
|
8557471f67dfdb15e878f6e00d948966c424d02e | harsha16208/Training | /sumofprimes.py | 529 | 3.5625 | 4 | from math import sqrt as s
for i in range(int(input())):
l,r=[int(x) for x in input().split(" ")]
def sumOfPrimes(l,r):
primes=['','']
for i in range(2,r+1):
primes.append(True)
for j in range(2,int(s(r))+1):
if primes[j]==True:
for k in range(j*j,r+1,j):
primes[k]=False
sum=0
for m in range(l,len(primes)):
if primes[m]==True:
sum+=m
print(sum)
sumOfPrimes(l,r)
|
76b1ab54ae7e0cf832236dcf6a3f49e9fbdb27b9 | RKramare/advent-of-code-2020 | /day2.py | 795 | 3.5625 | 4 | DAY_NUM = 2
def input():
f = open("input/day" + str(DAY_NUM) + ".txt")
inp = [l.rstrip('\n') for l in f]
f.close()
return inp
def checkPasswords(inp):
res1, res2 = 0, 0
for line in inp:
x = line.split(" ")
fir = int(x[0].split("-")[0])
sec = int(x[0].split("-")[1])
letter = x[1][0]
word = x[2]
if bool(word[fir-1] == letter) != bool(word[sec-1] == letter):
res1 += 1
if word.count(letter) >= fir and word.count(letter) <= sec:
res2 += 1
return res1, res2
def main():
inp = input()
answer1, answer2 = checkPasswords(inp)
print(f"Answer to question one: {answer1}\nAnswer to question two: {answer2}")
if __name__ == "__main__":
main()
|
b168f20cfbbe2df83a2152f9f35847a9e9507168 | jtibbertsma/python-sudoku | /sudoku/concrete.py | 3,344 | 3.703125 | 4 | """
Concrete sudoku solver classes which use various algorithms to solve sudoku
puzzles.
"""
from .errors import Catastrophic, NoNextMoveError
from .solver import (BasicSolver, Solver, Elimination, HiddenSingles,
NakedPairs, NakedTriples, NakedQuads,
HiddenPairs, HiddenTriples, HiddenQuads,
SimpleXWings, UniqueRectangles,
LockedCandidates, BUGPlusOne, Sledgehammer, Random)
class ProfileSolver(
Solver,
Elimination,
HiddenSingles,
NakedPairs,
HiddenPairs,
LockedCandidates,
UniqueRectangles,
SimpleXWings,
HiddenTriples,
NakedTriples,
HiddenQuads,
NakedQuads,
BUGPlusOne,
Sledgehammer
):
"""This is the solver used by the profiler script prof.py. Adjust this
to test the relative speeds of Algorithm combinations.
"""
class UniqueProver(BasicSolver, Elimination, HiddenSingles, NakedPairs, Sledgehammer):
"""This is used to prove that a given sudoku grid has a unique
solution.
"""
def check(self):
"""Returns True if the puzzle has a unique solution; False
otherwise.
"""
self.solve()
# Force a backtrack to the previous guess
try:
move = self.backtrack("Forced")
except NoNextMoveError:
# No guesses were made while solving the puzzle
return True
self.apply(move)
try:
self.solve()
except NoNextMoveError:
# Couldn't find another solution
return True
else:
return False
class StartCreating(BasicSolver, Random):
"""This is a weird solver whose solve method just does eleven moves,
which will all be RandomGuesses. This is used to generate random terminal
patterns as the first step of creating a new puzzle.
"""
def solve(self):
#for n in range(self.howmanymoves()):
for n in range(11):
move = self.findnextmove()
self.apply(move)
# def howmanymoves(self):
# """Calculate the number of cells to fill into the new terminal pattern.
# This is set up to give 11 in the normal case of a sudoku grid with 9
# rows. However, 11 doesn't work well for other grid sizes.
# """
# size = self.state.size
# square = size * size
# return square // 10 + 3
class FinishCreating(BasicSolver, Elimination, Sledgehammer):
"""This solver is used to finish filling the grid which was started by
StartCreating. Since grids at this point may have multiple solutions,
it's much faster if we don't use any complicated algorithms. However,
it's possible that StartCreating will generate a catastrophic case
that takes forever to solve, so we raise an error if we start taking
too long.
"""
def solve(self):
count = 0
while not self.state.done:
if count == 200:
raise Catastrophic
move = self.findnextmove()
self.apply(move)
count += 1
class FastSolver(Solver, Elimination, HiddenSingles, NakedPairs, Sledgehammer):
"""Designed to solve the widest variety of puzzles the fastest."""
class Slowpoke(Solver, Elimination, Random):
"""Designed to be super slow and take up hella memory."""
|
11a462649f8ebd34f0d29ab619e6d36bc98160af | Moandh81/python-self-training | /tuple/9.py | 494 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write a Python program to find the repeated items of a tuple.
mytuple = ("dog", "cat", "cow", "fox", "hen", "cock", "lion" , "zebra","duck" ,"bull", "sheep", "cat", "cow", "fox", "lion")
frequency = {}
for item in mytuple:
if item.lower() not in frequency:
frequency[item.lower()] = 1
else:
frequency[item.lower()] = frequency[item.lower()] + 1
for key,value in frequency.items():
if frequency[key] > 1:
print(key)
|
71998f2f85093291d6de0a61e49d012bbca4bdc0 | Moandh81/python-self-training | /datetime/30.py | 218 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write a Python program to convert a date to the timestamp.
from datetime import datetime
now = datetime.now()
timestamp = datetime.timestamp(now)
print(timestamp) |
ac6d44000cce88e231a9a85d082c8538b44fd515 | Moandh81/python-self-training | /datetime/32.py | 272 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write a Python program to calculate a number of days between two dates.
from datetime import date
t1 = date(year = 2018, month = 7, day = 12)
t2 = date(year = 2017, month = 12, day = 23)
t3 = t1 - t2
print("t3 =", t3)
|
fee021a37c322579ad36109a92c914eaf4a809b7 | Moandh81/python-self-training | /functions/1.py | 657 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*
# Write a Python function to find the Max of three numbers.
import re
expression = r'[0-9]+'
numberslist = []
number1 = number2 = number3 = ""
while re.search(expression, number1) is None:
number1 = input('Please input first number: \n')
while re.search(expression, number2) is None:
number2 = input('Please input second number: \n')
while re.search(expression, number3) is None:
number3 = input('Please input third number: \n')
numberslist.append(number1)
numberslist.append(number2)
numberslist.append(number3)
print(numberslist)
print("the maximum number is {}".format(max(numberslist))) |
4a43f7f498cda12296b75247c5b6d45941519527 | Moandh81/python-self-training | /conditional-statements-and-loops/5.py | 268 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write a Python program that accepts a word from the user and reverse it.
word = input("Please input a word : \n")
newword = ""
i = len(word)
while i > 0:
newword = newword + word[i-1]
i = i - 1
print(newword) |
c78566301e0cc885f89c65310e9245fb5072dce1 | Moandh81/python-self-training | /dictionary/24.py | 517 | 4.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write a Python program to create a dictionary from a string. Go to the editor
# Note: Track the count of the letters from the string.
# Sample string : 'w3resource'
# Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
txt = input('Please insert a string : \n')
dictionary = {}
for letter in txt:
if letter not in dictionary.keys():
dictionary[letter] = 1
else:
dictionary[letter] = dictionary[letter] + 1
print(dictionary) |
7897869a67893a3ea72027ae8911e80e9e1d8f6a | Moandh81/python-self-training | /datetime/7.py | 450 | 4.4375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write a Python program to print yesterday, today, tomorrow
from datetime import datetime, date, time
today = datetime.today()
print("Today is " , today)
yesterday = today.timestamp() - 60*60*24
yesterday = date.fromtimestamp(yesterday)
print( "Yesterday is " , yesterday)
tomorrow = today.timestamp() + 60*60*24
tomorrow = date.fromtimestamp(tomorrow)
print("Tomorrow is ", tomorrow) |
cdf3abaafdf05f6cc6a164b72120b100c010fe28 | Moandh81/python-self-training | /sets/6.py | 256 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write a Python program to create an intersection of sets.
set1 = {"apple", "banana", "cherry" , "strawberry"}
set2 = {"cherry", "ananas", "strawberry", "cocoa"}
set3 = set1.intersection(set2)
print(set3) |
f552ed71c41a45b8838d36ca289e6ded418370f5 | Moandh81/python-self-training | /tuple/12.py | 355 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Write a Python program to remove an item from a tuple.
mytuple = ("dog", "cat", "cow", "fox", "hen", "cock", "duck" ,"bull", "sheep")
myliste = []
txt = input("Please input a text : \n")
for element in mytuple:
if element != txt:
myliste.append(element)
myliste=tuple(myliste)
print(myliste) |
c05aca3c8637d78d9f31db8209ec7f3f1d6060cd | Moandh81/python-self-training | /functions/2.py | 360 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*
# Write a Python function to sum all the numbers in a list. Go to the editor
# Sample List : (8, 2, 3, 0, 7)
# Expected Output : 20
liste = [1,2,3,4,5]
def sumliste(liste):
sum = 0
for item in liste:
sum = sum + item
print("The sum of the numbers in the list is {}".format(sum))
sumliste(liste) |
601024dde5afc78a8e89a2065009fd376c1e04fb | eightys3v3n/matter_simulator | /test_vectors.py | 6,012 | 3.5 | 4 | import unittest
import utils
from space import Vector3f,Position3f,Position2f
class TestVector3f(unittest.TestCase):
def test___init__(self):
a = Vector3f()
self.assertEqual(a.origin,Position3f())
self.assertEqual(a.destination,Position3f())
with self.assertRaises(TypeError):
Vector3f(1)
with self.assertRaises(TypeError):
Vector3f(1,1)
with self.assertRaises(TypeError):
Vector3f(Position3f(),0)
with self.assertRaises(TypeError):
Vector3f(Position3f(),Position3f(),1)
with self.assertRaises(Exception):
Vector3f(0,0,0,0,0)
with self.assertRaises(Exception):
Vector3f(origin=Position3f(),abc=1)
with self.assertRaises(TypeError):
Vector3f(origin=1)
a = Vector3f(Position3f(1,1,1),Position3f(-1,-1,-1))
self.assertEqual(a.destination,Position3f(-1,-1,-1))
self.assertEqual(a.origin,Position3f(1,1,1))
a = Vector3f(Position3f(1,1,1))
self.assertEqual(a.destination,Position3f(1,1,1))
self.assertEqual(a.origin,Position3f())
a = Vector3f(origin=Position3f(1,1,1))
self.assertEqual(a.destination,Position3f())
self.assertEqual(a.origin,Position3f(1,1,1))
a = Vector3f(origin=Position3f(1,1,1),destination=Position3f(-1,-1,-1))
self.assertEqual(a.destination,Position3f(-1,-1,-1))
self.assertEqual(a.origin,Position3f(1,1,1))
a = Vector3f(1,1,1)
self.assertEqual(a.destination,Position3f(1,1,1))
self.assertEqual(a.origin,Position3f())
a = Vector3f(1,1,1,-1,-1,-1)
self.assertEqual(a.destination,Position3f(-1,-1,-1))
self.assertEqual(a.origin,Position3f(1,1,1))
def test___str__(self):
a = Vector3f()
a.origin = Position3f(0,0,0)
a.destination = Position3f(1,1,1)
self.assertEqual(a.__repr__(),"(0.0,0.0,0.0)->(1.0,1.0,1.0)")
def test___repr__(self):
a = Vector3f()
a.origin = Position3f(0,0,0)
a.destination = Position3f(1,1,1)
self.assertEqual(a.__repr__(),"(0.0,0.0,0.0)->(1.0,1.0,1.0)")
def test___eq__(self):
self.assertTrue(
Vector3f(Position3f(1,1,1),Position3f()) ==
Vector3f(Position3f(1,1,1),Position3f())
)
self.assertFalse(
Vector3f(Position3f(2,1,1),Position3f()) ==
Vector3f(Position3f(1,1,1),Position3f())
)
self.assertFalse(
Vector3f(Position3f(),Position3f(1,1,1)) ==
Vector3f(Position3f(),Position3f())
)
self.assertTrue(
Vector3f(Position3f(),Position3f(1,1,1)) ==
Vector3f(Position3f(),Position3f(1,1,1))
)
self.assertFalse(
Vector3f(Position3f(),Position3f(1,1,1)) ==
Vector3f(Position3f(1,1,1),Position3f())
)
self.assertTrue(
Vector3f(Position3f(2,2,2),Position3f(1,1,1)) ==
Vector3f(Position3f(2,2,2),Position3f(1,1,1))
)
self.assertFalse(Vector3f() == 1)
def test___ne__(self):
self.assertFalse(
Vector3f(Position3f(1,1,1),Position3f()) !=
Vector3f(Position3f(1,1,1),Position3f())
)
self.assertTrue(
Vector3f(Position3f(2,1,1),Position3f()) !=
Vector3f(Position3f(1,1,1),Position3f())
)
self.assertTrue(
Vector3f(Position3f(),Position3f(1,1,1)) !=
Vector3f(Position3f(),Position3f())
)
self.assertFalse(
Vector3f(Position3f(),Position3f(1,1,1)) !=
Vector3f(Position3f(),Position3f(1,1,1))
)
self.assertTrue(
Vector3f(Position3f(),Position3f(1,1,1)) !=
Vector3f(Position3f(1,1,1),Position3f())
)
self.assertFalse(
Vector3f(Position3f(2,2,2),Position3f(1,1,1)) !=
Vector3f(Position3f(2,2,2),Position3f(1,1,1))
)
self.assertTrue(Vector3f() != 6)
def test___add__(self):
a = Vector3f(1,1,1)
b = Vector3f(2,2,2)
self.assertEqual(a+b,Vector3f(3,3,3))
a = Vector3f(1,1,1,4,4,4)
b = Vector3f(2,2,2)
self.assertEqual(a+b,Vector3f(1,1,1,6,6,6))
def test___iadd__(self):
init = Vector3f()
res = init
res += Vector3f(3,3,3,1,1,1)
self.assertIs(res,init,msg="in-place addition isn't changing the original")
self.assertEqual(res,Vector3f(3,3,3,1,1,1))
def test___sub__(self):
a = Vector3f(1,1,1,3,3,3)
b = Vector3f(2,2,2,1,1,1)
self.assertEqual(a-b,Vector3f(-1,-1,-1,2,2,2))
a = Vector3f(1,1,1,4,4,4)
b = Vector3f(1,1,1,3,3,3)
self.assertEqual(a-b,Vector3f(0,0,0,1,1,1))
def test___isub__(self):
init = Vector3f()
res = init
res -= Vector3f(2,2,2,1,1,1)
self.assertIs(res,init,msg="in-place subtraction isn't changing the original")
self.assertEqual(res,Vector3f(-2,-2,-2,-1,-1,-1))
def test___mul__(self):
res = Vector3f(1,1,1,3,5,1)
self.assertEqual(res*5,Vector3f(1,1,1,15,25,5))
def test___imul__(self):
init = Vector3f(1,1,1,3,1,2)
res = init
res *= 4
self.assertIs(res,init,msg="in-place multiplication isn't changing the original")
self.assertEqual(res,Vector3f(1,1,1,12,4,8))
def test___truediv__(self):
ret = Vector3f(1,1,1,9,9,9)
self.assertEqual(ret/3,Vector3f(1,1,1,3,3,3),msg="division isn't working correctly")
def test___itruediv__(self):
init = Vector3f(1,1,1,9,9,9)
ret = init
ret /= 3
self.assertIs(ret,init,msg="in-place division isn't changing the original")
self.assertEqual(ret,Vector3f(1,1,1,3,3,3),msg="in-place division isn't working correctly")
def test_from_zero(self):
self.assertEqual(Vector3f(1,1,1,3,3,3).from_zero,Vector3f(2,2,2))
self.assertEqual(Vector3f(-1,-1,-1,3,3,3).from_zero,Vector3f(4,4,4))
def test_array(self):
self.assertEqual(Vector3f(1,1,1,3,3,3).array,[1,1,1,3,3,3])
def test_magnitude(self):
self.assertEqual(Vector3f(3,3,3).magnitude,5.196152)
def test_direction(self):
self.assertEqual(Vector3f(1,1,1,3,3,3).from_zero,Vector3f(2,2,2))
self.assertEqual(Vector3f(-1,-1,-1,3,3,3).from_zero,Vector3f(4,4,4))
def test_angles(self):
self.assertEqual(Vector3f(1,1,1).angles,Position2f(45,45))
if __name__ == '__main__':
unittest.main() |
b8d9bdd2e06b0ed23b477c46e24bd320d9c54103 | eightys3v3n/matter_simulator | /test.py | 4,012 | 3.5 | 4 | import os
from sys import exit
from types import ModuleType
import test_files
"""
Contains a framework for automatically compiling and running tests
"""
class Test():
"""
Stores a refernece to the actual test function, and a list of tests that must be run before this one is
"""
def __init__(self,function,requires):
self.function = function
self.requires = requires
self.completed = False
def __getattr__(self,key):
"""
.name: return the name of the test function with a ' test' added on
.function_name: returns the name of the test function
"""
if key == "name":
return self.function.__name__+" test"
elif key == "function_name":
return self.function.__name__
def __call__(self):
"""
Runs the function referenced if it has not already been completed
"""
if self.completed:
return False
ret = self.function()
if ret == False:
self.completed = True
return ret
class Tests():
"""
A collection of Test objects with no duplicates.
This class handles running all of the tests in the correct order
"""
def __init__(self):
self.completed = []
self.tests = []
def already_testing(self,function):
"""
param function: a reference to a function
returns:
True: if the test function is already in this collection of tests; i.e. it doesn't need to be added again
False: if the test function is not in this collection of tests
"""
for test in self.tests:
if test.function == function:
return True
return False
def new(self,function,func_requires=[]):
"""
Adds a new test and it's prerequisites to the collection
param function: a reference to the test function
param func_requires: an array of references to the functions that must be run before this one
"""
if not self.already_testing(function):
self.tests.append(Test(function,func_requires))
def run_test(self,test):
"""
Runs the Test object after all of it's prerequisites
param test: A Test object
"""
if not test.completed:
for req in test.requires:
req_test = None
for funcs in self.tests:
if req == funcs.function:
req_test = funcs
if req_test == None:
raise Exception(test.name+" requires a non-test ",req)
if not req_test.completed:
self.run_test(req_test)
ret = test()
if ret == False:
if os.name == "posix":
print("\033[92m"+test.name+" passed\033[0m")
elif os.name == "nt":
print(test.name+" passed")
test.completed = True
elif ret == None:
if os.name == "posix":
print("\033[90m"+test.name+" has no test\033[0m")
elif os.name == "nt":
print(test.name+" has no test")
else:
if os.name == "posix":
print("\033[91m"+test.name+" failed\033[0m")
elif os.name == "nt":
print(test.name+" failed")
exit(2)
def __call__(self):
"""
Runs all the tests in the collection
"""
for test in self.tests:
self.run_test(test)
tests = Tests()
def compile_tests(module):
"""
Adds all the functions that meet a criteria to the global Tests object
criteria:
function ends in '_Test'
an array called 'functions name'+'_req' that is [] or contains references to other test functions
"""
for function_str in dir(module):
function = getattr(module,function_str)
if isinstance(function,ModuleType):
compile_tests(function)
elif callable(function) and len(function_str) > 5 and function_str[-5:] == "_Test":
requirements = getattr(module,function_str+"_req")
tests.new(function,requirements)
#print("found test",function_str)
#print(" requires",requirements)
def test_all():
"""
Compiles and runs all the tests included in the specified module
Currently retrieving all tests from 'test_files.py'
"""
compile_tests(test_files)
tests() |
6ea91562526656fb3b566cfbdaaee74c1c1d4d88 | jmacarter/Python-Data | /chapter 8.py | 1,662 | 4 | 4 | for i in [5,4,3,2,1]:
print i
print "Blastoff!"
friends = ['Joseph','Jeremy','Jimmy Jackhammer','Tyrone', 'Jamal', 'Terrance']
for i in friends:
print i+' is a friend'
print range(len(friends))
for i in range(len(friends)):
friend = friends[i]
print friend+' is a good friend'
a = [1,2,3]
b = [4,5,6]
c = a + b
d = a + friends
print c[1:4]
print c[:5]
print c[:]
print d
stuff = list()
stuff.append('book')
stuff.append(99)
print stuff
stuff.append('cookie')
print stuff
friends.append('Antonio')
friends.sort()
print friends
print max(friends)
print min(friends)
print len(friends)
# total = 0
# count = 0
# while True:
# inp = raw_input("Enter a number:")
# if inp == 'done':break
# value = float(inp)
# total = total + value
# count = count + 1
#
# average = total/count
# print 'Average:',average
#
# numlist = list()
# while True:
# inp = raw_input('Enter a number:')
# if inp == 'done':break
# value=float(inp)
# numlist.append(value)
#
# average = sum(numlist)/len(numlist)
# print 'Average:',average
abc = 'With three words'
stuff = abc.split()
print stuff
print len(stuff)
print stuff[0]
for w in stuff:
print w
line = 'A lot of spaces'
etc = line.split()
print etc
line = 'first;second;third'
thing = line.split()
print thing
print len(thing)
thing = line.split(';')
print thing
print len(thing)
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From '): continue
words = line.split()
# print words[2]
email = words[1]
print email
pieces = email.split('@')
print pieces[1]
|
d3557aa58cd0ffc9a317979cb632e71b01dbf3ca | aevalo/aev | /python_stuff/return_test.py | 199 | 3.71875 | 4 | def ret_3():
return 1, 2, 3
def main():
a, b, c = ret_3()
print("a = {0}, b = {1}, c = {2}".format(a, b, c))
print("a = %d, b = %d, c = %d" % (a, b, c))
if __name__ == "__main__":
main() |
2617a2ae708f1b4c24600a0bad94ecabf410cd2a | J-Krisz/project_Euler | /Problem 20 - Factorial digit sum.py | 356 | 3.59375 | 4 | # n! means n × (n − 1) × ... × 3 × 2 × 1
# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
# Find the sum of the digits in the number 100!
# The page has been left unattended for too long and that link/button is no longer active. Please refresh the page.
|
4870640a39e9da3773c603ccb30b877b56c6c693 | J-Krisz/project_Euler | /Problem 4 - Largest palindrome product.py | 462 | 4.125 | 4 | # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
def is_palindrome(n):
return str(n) == str(n)[::-1]
my_list = []
for n_1 in range(100, 1000):
for n_2 in range(100, 1000):
result = n_1 * n_2
if is_palindrome(result):
my_list.append(result)
print(max(my_list)) |
0818f935f67ba43847d75076c4755343f79a8c34 | plazmonik/compare_model_tool | /iris_example.py | 867 | 3.515625 | 4 | # At first, let's try to use the application for a famous Iris dataset;
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from app import two_model_feature_importance_app
# The data is available in sklearn.dataset
dict_ = datasets.load_iris()
# We split data into train and test set, as every good Data Scientist would do:
X_train, X_test, y_train, y_test = train_test_split(dict_['data'], dict_['target'])
# Then we define and train the models:
model1 = RandomForestClassifier(n_estimators = 100)
model1.name = 'Random Forest'
model2 = DecisionTreeClassifier()
model2.name = 'Decision Tree'
for model in (model1, model2):
model.fit(X_train, y_train)
two_model_feature_importance_app(model1, model2, dict_['feature_names']) |
3b2c787354767c33e08fa2991820ead0ae30e56d | bertrandvidal/stuff | /alternating_characters/alternating.py | 388 | 3.625 | 4 | number_test_cases = int(input("Enter the number of test cases: "))
for idx in range(number_test_cases):
test_case = input("Test case #{} ".format(idx+1))
suppression = 0
for i, c in enumerate(test_case):
if i < 1:
continue
if c == test_case[i-1]:
suppression += 1
print("{} suppression(s) for '{}'".format(suppression, test_case))
|
7263d1e36de8add654306c2da70f1fcb79cb3110 | dgan11/Cracking_The_Coding_Interview_Python_Solutions | /Chp1_Arrays_and_Strings/1.5_One_Away.py | 3,309 | 4.15625 | 4 | """
There are three types of edits that can be performed on strings:
- insert a charachter
- remove a charachter
- replace a charachter
Given two strings, wrtie a function to check if they are one edit
(or zero) edits away
Ex:
pale, ple -> True // {'a':1}
pales, pale -> True // {'s':1}
pale, bale -> True // {'p':1, 'b':1}
pale, bake -> False // {'p':1, 'l':1, 'b':1, 'k':1}
ppp, app
"""
"""
How to check that zero edits
- check the strings are the same
How to check that one edits"
- If the length of one string is more than the other+1 then there has to be more than one edit
How to check for insertion/remove a charachter:
- dictionary can add and then remove, if more than one character has a count leftover than False
How to check for replace a charachter:
-
"""
class OnePassSolution:
def oneAway(self, s1, s2):
s1_size = len(s1)
s2_size = len(s2)
if abs(s1_size - s2_size) > 1:
return False
elif s1_size == s2_size:
return self.checkSwap(s1, s2)
elif s1_size > s2_size:
return self.checkChange(s1, s2)
else:
return self.checkChange(s2, s1)
def checkSwap(self, s1, s2):
numSwaps = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
numSwaps += 1
if numSwaps > 1:
return False
return True
def checkChange(self, longer, shorter):
li, si = 0, 0
numChanges = 0
while li < len(longer) and si < len(shorter):
if longer[li] != shorter[si]:
numChanges += 1
if numChanges > 1:
return False
else:
si += 1
li += 1
return True
# Time : O(2n) where n is the lenght of the shorter. O(1) if the strings are more than 1 length away.
# Space : O(1) space requirement doesn't change as n increases
test2 = OnePassSolution()
assert(test2.oneAway('pale', 'ple'))
assert(test2.oneAway('pale', 'bale'))
assert(test2.oneAway('pale', 'bale'))
assert(test2.oneAway('pale', 'bake') == False)
class Solution:
def oneAway(self, s1, s2):
if abs(len(s1)-len(s2)) > 1:
return False
if s1 == s2:
return True
# Local Vars
letterCounts = {}
changesCount = 0
# Insert letters from s1 into letterCounts
for curLetterS1 in s1:
letterCounts[curLetterS1] = letterCounts.get(curLetterS1, 0) + 1
# Insert letters from s2 into letterCounts
for curLetterS2 in s2:
if curLetterS2 in letterCounts:
letterCounts[curLetterS2] = letterCounts[curLetterS2] - 1
else:
letterCounts[curLetterS2] = 1
# Loop through counts in letterCounts
for count in letterCounts.values():
if count != 0:
changesCount += 1
if changesCount > 2:
return False
return True
# Time: O(1) if string different in length or O(4n) where n is the length of the shorter
# Space: O(2n)
test = Solution()
assert(test.oneAway('pale', 'ple'))
assert(test.oneAway('pale', 'bale'))
assert(test.oneAway('pale', 'bale'))
assert(test.oneAway('pale', 'bake') == False)
|
f11e726a83933846f8ffc4e5d12f15bbb789145b | saadmk11/image_downloader | /image_downloader/downloader.py | 1,598 | 3.96875 | 4 | import os
import urllib.parse as urlparse
import urllib.request
def image_downloader(file):
"""
This Function Downloads all images from a Text File including urls.
Args:
file: the path of the text file.
On Execution:
Downloads the images from URLs provided on the text file
and saves them in the images Directory.
Raises:
ValueError or URLError if url is incorrect or unknown url type.
"""
directory = './images'
if not os.path.exists(directory):
# if directory Doesnt Exist Create it.
os.makedirs(directory)
with open(file, "r") as text_file:
image_count = 0
for line in text_file:
name_from_url = urlparse.urlsplit(line)[2].split('/')[-1]
try:
image = name_from_url.split('.')[0]
# Try to get Image Extention.
image_ext = name_from_url.split('.')[1]
image_name = '{}-{}.{}'.format(
image, image_count, image_ext)
except IndexError:
# As Some URLs Don't Include Extentions use .jpg format.
image_name = '{}-{}.jpg'.format(
name_from_url, image_count)
file_path = directory + '/' + image_name
# Download The image
urllib.request.urlretrieve(line, file_path)
# increase count for name uniqueness.
image_count += 1
if __name__ == '__main__':
input_file = input("Provide The Text File Path Which Include Image URLs: ")
image_downloader(input_file)
|
4aef5e6a7c9cc50af0ba2fa439f8ecf870b7d68f | uchicago-cs/debugging-guide | /examples/runtime/runtime-error.py | 332 | 3.609375 | 4 | #!/usr/bin/python3
import sys
def foo(a, b):
return a // b
def bar(a, b):
return foo(a, b)
if __name__ == "__main__":
if len(sys.argv) != 3:
print("USAGE: runtime-error.py NUM1 NUM2")
sys.exit(1)
a = int(sys.argv[1])
b = int(sys.argv[2])
x = bar(a, b)
print("a / b = {}".format(x)) |
f3e31b5d7485467c5a8b08d95aefecd6d9cad5b3 | rohit04445/Creating-Engineering-Notation | /engineering.py | 4,887 | 4.09375 | 4 | def multiply(num, power_of_ten):
num = str(num)
if num.find('.') == -1:
num = num + '.'
point_index = num.find('.')
while len(num[point_index + 1:len(num)]) < power_of_ten:
num = num + '0'
point_index = num.find('.')
num = num.replace('.', '')
num = num[0:point_index + power_of_ten] + '.' + num[point_index + power_of_ten:]
minusSignPresent = False
if num[0] == '-':
minusSignPresent = True
num = num[1:]
iterate = 0
while iterate < num.find('.'):
if num[iterate] != "0":
break
else:
num = num[iterate + 1:]
iterate = iterate + 1
if num[0] == '.':
num = '0' + num
if num[len(num) - 1] == '.':
num = num + '0'
if minusSignPresent:
num = '-' + num
return num
# this function return the rounded value to the required number of significant numbers
def round_to_given_significant_figures(x, p):
return round(x, p)
# In eng_notation we first find the e notation of the given number i.e if number is 1250000
# gives 1.250000e+06.As from here we an see this the last two characters gives the power of 10 required
# and the characters before e gives the Actual number to be presented
# And according to the no. of significant figures the required string is given back
def eng_notation(number, sigfigs=3):
Scientific_Notation = "{:e}".format(number) # Scientific_Notation contains the scientific notation
# By string slicing and type conversion the power_of_ten contains the power of 10
power_of_ten = int(Scientific_Notation[Scientific_Notation.__len__() - 2:Scientific_Notation.__len__()])
# Sign contains the sign i.e. the power of 10 is +ve or -ve
sign = Scientific_Notation[Scientific_Notation.__len__() - 3]
# no contains the actual value in such a way that there is only single digit
# before decimal point
no = float(Scientific_Notation[0:Scientific_Notation.__len__() - 4])
# m will contain the value we have to use the while loop before loop ends because by this number we have
# to multiply our number to get correct answer
m = 0
# if condition will check if sign is +ve or -ve because for +ve sign the suffix are like 'M','G'
# but for -ve sign the suffix are 'm','u'
if sign.__eq__('+'):
suffix = ["", "k", "M", "G", "T", "P"]
while 1:
if power_of_ten % 3 == 0:
Suffix_index = int(power_of_ten / 3)
Suffix_Notation_Used = suffix[Suffix_index]
break
# power_of_ten is decreased because it is not matching with the required suffix index so by decreasing it
# we will try for next option and also have to increase m as now no to be multiplied by 10
power_of_ten = power_of_ten - 1
m = m + 1
# for getting the number of significant figures we use round function but in another way we will first convert
# our number to a number like 0.233 etc. so then calling the round function will five us the correct number of
# significant figures so we will have to divide the no by 10 and also increment m
rounded_number = round_to_given_significant_figures(no / 10, sigfigs)
m += 1
# for getting correct decimal point after notation we will call multiple function
Scientific_Notation = multiply(rounded_number, m)
return str(Scientific_Notation) + Suffix_Notation_Used
else:
suffix = ["", "m", "u", "n", "p", "f"]
while 1:
if power_of_ten % 3 == 0:
Suffix_index = int(power_of_ten / 3)
Suffix_Notation_Used = suffix[Suffix_index]
break
# power_of_ten is decreased because it is not matching with the required suffix index so by decreasing it
# we will try for next option and also have to increase m as now no to be multiplied by 10
power_of_ten = power_of_ten - 1
m = m + 1
# for getting the number of significant figures we use round function but in another way we will first convert
# our number to a number like 0.233 etc. so then calling the round function will five us the correct number of
# significant figures so we will have to divide the no by 10 and also increment m
rounded_number = round_to_given_significant_figures(no / 10, sigfigs)
m += 1
# for getting correct decimal point after notation we will call multiple function
Scientific_Notation = multiply(rounded_number, m)
return str(Scientific_Notation) + Suffix_Notation_Used
if __name__ == "__main__":
test_cases = [0.0, 1.2345, 23.456, -345.67, 4567.8, -56789, 12345e6,
-2345.6e9]
for i in range(1, 5):
print("i is", i)
for case in test_cases:
print(case, "-->", eng_notation(case, i))
|
2898083afcc9242417f89af4fd4de2786818d7f5 | djeikyb/learnpythonthehardway | /ex15a.py | 639 | 3.6875 | 4 | # allow us to take arguments for the script
from sys import argv
# unpack the first two argv array elements
script, filename = argv
# variable txt is now an open file
txt = open(filename)
# print the file name
print "Here's your file %r:" % filename
# read and print the open file that is txt
print txt.read()
# ask the user to painstakingly type the file name
# even though they already passed it as an argument
print "Type the filename again:"
file_again = raw_input("> ")
# variable 'txt_again' now holds an open file
txt_again = open(file_again)
# read and print the open file txt_again
print txt_again.read()
# vim: syntax=off
|
4f05572563bd615a85bccc3d225f28b8a4ae36b5 | djeikyb/learnpythonthehardway | /ex19a.py | 1,298 | 4.125 | 4 | # write a comment above each line explaining
# define a function. eats counters for cheese and cracker boxen
# shits print statements
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# print var as decimal
print "You have %d cheeses!" % cheese_count
# print var as decimal
print "You have %d boxes of crackers!" % boxes_of_crackers
# print string
print "Man that's enough for a party!"
# print string
print "Get a blanket.\n"
# print string
print "We can just give the function numbers directly:"
# call function passing two decimals
cheese_and_crackers(20, 30)
# print string
print "OR, we can use variables from our script:"
# set cheese counter
amount_of_cheese = 10
# set cracker boxen counter
amount_of_crackers = 50
# call function passing cheese and cracker boxen count variables
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# print string
print "We can even do math inside too:"
# call function, passing two arguments. each argument uses elementary math
cheese_and_crackers(10 + 20, 5 + 60)
# print string
print "And we can combine the two, variables and math:"
# call function. each argument uses elementary algebra
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
# vim: syntax=off
|
47d3f9feac0d9304cbe51bc2eb87f25f56ca9e49 | k-sashank/Phone_Number_and_Email_Extractor | /Phone_Number_And_Email_Identifier.py | 1,296 | 3.765625 | 4 | #Import required Libraries
import pyperclip, re
#Regular Expressions to detect Phone Numbers and Email Addresses
phoneRegex = re.compile(r'''((\s|\+|\.)?(\d{2}|\(\d{2}\))?(\s|-|\.)?(\d{10}))''', re.VERBOSE)
emailRegex = re.compile(r'''([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4}))''', re.VERBOSE)
#List to store all the detected Phone Numbers and Email Addresses
matches = []
#Opening file.txt in read-mode
file = open('sample_text_file.txt', 'r')
#Loop to scan each line in the file
for each in file:
#Loop to scan all the phone numbers in the line and appending them to matches
for groups in phoneRegex.findall(each):
phoneNum = groups[1] + groups[2] + groups[4]
matches.append(phoneNum)
#Loop to scan all the email ids in the line and appending them to matches
for groups in emailRegex.findall(each):
matches.append(groups[0])
#Conditional to check if we got at least one match
if len(matches) > 0:
#Printing th data found
print("Data Found: ")
for i in range(0,len(matches)):
print(matches[i])
#Copying to clipboard
pyperclip.copy('\n'.join(matches))
print('Copied to clipboard')
#Conditional in case nothing is found
else:
print('No phone numbers or email addresses found.')
|
40ebb96140e37fd9540dd5fda11c60a17cb3bfda | jithendra945/mountblue-dataproject-sqlalchemy | /generating_json.py | 6,787 | 3.53125 | 4 | """
Generating JSON data files to plot graphs on Browser
"""
# importing the required libraries
import csv
from collections import defaultdict
import json
from sqlalchemy import Column, Float, String, create_engine, desc
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.sqltypes import Integer
from sqlalchemy.sql import func
Base = declarative_base()
class PopulationData(Base):
"""
Defining table populationdata and its columns
"""
__tablename__ = "populationdata"
id = Column(Integer, primary_key=True)
region = Column(String)
year = Column(Integer)
population = Column(Float)
class AseanCountries(Base):
"""
Defining table aseancountries and its columns
"""
__tablename__ = "aseancountries"
id = Column(Integer, primary_key=True)
country = Column(String)
class SaarcCountries(Base):
"""
Defining table saarccountries and its columns
"""
__tablename__ = "saarccountries"
id = Column(Integer, primary_key=True)
country = Column(String)
def total_population(session):
"""
Adding data from csv to table PopulationData
"""
with open('datasets/csv/population_estimates_csv.csv', 'r') as csv_file:
csv_list = list(csv.DictReader(csv_file, delimiter=','))
csv_file.close()
for row in csv_list:
session.add_all([
PopulationData(region=row['Region'],
year=row['Year'], population=row['Population'])
])
session.commit()
def asean_countries(session):
"""
Adding data from csv to table AseanCountries
"""
with open('datasets/csv/asean_countries.csv', 'r') as file:
asean_list = [row['ASEAN-countries'] for row in csv.DictReader(file)]
file.close()
for row in asean_list:
session.add_all([
AseanCountries(country=row)
])
session.commit()
def saarc_countries(session):
"""
Adding data from csv to table SaarcCountries
"""
with open('datasets/csv/saarc_countries.csv', 'r') as file:
saarc_list = [row['SAARC-countries'] for row in csv.DictReader(file)]
file.close()
for row in saarc_list:
session.add_all([
SaarcCountries(country=row)
])
session.commit()
def indian_population():
"""
JSON data generation for Bar Plot of 'population of India' vs. years.
"""
query1 = Session.query(PopulationData)\
.filter(PopulationData.region == 'India')\
.order_by(desc(PopulationData.year))\
.limit(10).offset(1)
# formatting data accordingly
data = [[row.year, int(float(row.population))] for row in query1]
# duming data in JSON file
with open('datasets/json/indian-population.json', 'w') as json_file:
json.dump(data, json_file)
def asean_population():
"""
JSON data generation for
population of ASEAN countries for the year 2014
"""
query2 = Session.query(PopulationData)\
.filter(PopulationData.region
.in_(Session.query(AseanCountries.country)))\
.filter(PopulationData.year == 2014)\
.order_by(PopulationData.region)
asean_list = []
population = []
for row in query2:
asean_list.append(row.region)
population.append(int(float(row.population)))
# changing names to shorter one's
for key, value in enumerate(asean_list):
if value == "Brunei Darussalam":
asean_list[key] = "Brunei"
elif value == "Lao People's Democratic Republic":
asean_list[key] = "Laos"
# formatting data accordingly
data = [[country, pop] for country, pop in zip(asean_list, population)]
# duming data in JSON file
with open('datasets/json/asean-population.json', 'w') as json_file:
json.dump(data, json_file)
def total_saarc_population():
"""
JSON data generation for Total SAARC population vs year
"""
query3 = Session.query(func.sum(PopulationData.population)
.label("population_sum"))\
.filter(PopulationData
.region.in_(Session
.query(SaarcCountries.country)))\
.filter(PopulationData.year.between(2005, 2015))\
.group_by(PopulationData.year)\
.order_by(PopulationData.year)
population = [int(float(row.population_sum)) for row in query3]
# formatting data accordingly
years = [
"2005", "2006", "2007", "2008",
"2009", "2010", "2011", "2012",
"2013", "2014", "2015"
]
data = [[year, pop] for year, pop in zip(years, population)]
# duming data in JSON file
with open('datasets/json/total-saarc-population.json', 'w') as json_file:
json.dump(data, json_file)
def total_asean_population():
"""
JSON data generation for ASEAN countries for the years 2005 to 2014
"""
population = defaultdict(list)
query4 = Session.query(PopulationData)\
.filter(PopulationData.region
.in_(Session.query(AseanCountries.country)))\
.filter(PopulationData.year.between(2005, 2014))
for row in query4:
population[row.region].append(int(float(row.population)))
# duming data in JSON file
with open('datasets/json/total-asean-population.json', 'w') as json_file:
json.dump(population, json_file)
if __name__ == '__main__':
# Connection URL
PGURL = "postgresql://abcd:password1@localhost:5432/populationdata"
# Creating engine and binding Session
engine = create_engine(PGURL, echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)()
# Checking if data exist in table PopulationData
if Session.query(PopulationData).count():
print("Data exists in Table PopulationData.")
else:
# dumping data into table
total_population(Session)
# Checking if data exist in table AseanCountries
if Session.query(AseanCountries).count():
print("Data exists in Table AseanCountries.")
else:
# dumping data into table
asean_countries(Session)
# Checking if data exist in table SaarcCountries
if Session.query(SaarcCountries).count():
print("Data exists in Table SaarcCountries.")
else:
# dumping data into table
saarc_countries(Session)
# Calling respective functions to generate JSON's
indian_population()
asean_population()
total_saarc_population()
total_asean_population()
|
5b3354f55435f6e34724c4a7a02b0180bb079e10 | Arvindvishwakarma/Multiplication-Table-Python | /multiplication table.py | 836 | 3.875 | 4 | from tkinter import *
def MulTable():
print("\n")
print("Table")
for x in range(1,11):
m = int(EnterTable.get())
print((x), 'once the', (m), '=', (x*m))
win = Tk()
win.geometry('200x200')
win.title('Multiplication Table')
EnterTable = StringVar()
label = Label(win, text='Table', font=30, fg='Black')
label.grid(row=1,column=6)
label = Label(win, text=' ')
label.grid(row=2,column=6)
entry = Entry(win, textvariable=EnterTable, justify='center')
entry.grid(row=2,column=6)
button = Button(win, text='Table', command=MulTable)
button.grid(row=5,column=6)
label = Label(win, text=' ')
label.grid(row=4,column=6)
QUIT=Button(win, text='Exit', command=win.destroy)
QUIT.grid(row=6,column=6)
win.mainloop()
|
44142626c57508d50cf1977411479703657439fc | stjohn/csci127 | /errorsHex.py | 1,179 | 4.21875 | 4 | #CSci 127 Teaching Staff
#October 2017
#A program that converts hex numbers to decimal, but filled with errors...
Modified by: ADD YOUR NAME HERE
define convert(s):
""" Takes a hex string as input.
Returns decimal equivalent.
"""
total = 0
for c in s
total = total * 16
ascii = ord(c
if ord('0) <= ascii <= ord('9'):
#It's a decimal number, and return it as decimal:
total = total+ascii - ord('0')
elif ord('A") <= ascii <= ord('F'):
#It's a hex number between 10 and 15, convert and return:
total = total + ascii - ord('A') + 10
else ord('a') =< ascii <= ord('f'):
#Check if they used lower case:
#It's a hex number between 10 and 15, convert and return:
total = total + ascii - ord('a') +++ 10
else:
#Not a valid number!
return(-1)
return(total)
def main()
hexString = input("Enter a number in hex: ')
prnt("The number in decimal is", convert(hexString))
#Allow script to be run directly:
if __name__ == "__main__":
main()
|
9dfe3923af1ed8a1f91c44815d32590acab926f9 | canvasnote/hanabiAI | /test/TestDeck.py | 2,956 | 3.78125 | 4 | import unittest
from Deck import *
from Card import *
class TestDeck(unittest.TestCase):
def test_init(self):
# starter
assumeResult = \
"Y1 Y1 Y1 Y2 Y2 Y3 Y3 Y4 Y4 Y5 " + \
"G1 G1 G1 G2 G2 G3 G3 G4 G4 G5 " + \
"W1 W1 W1 W2 W2 W3 W3 W4 W4 W5 " + \
"R1 R1 R1 R2 R2 R3 R3 R4 R4 R5 " + \
"B1 B1 B1 B2 B2 B3 B3 B4 B4 B5"
starterDeck = Deck()
self.assertEqual(assumeResult, starterDeck.reprCards())
# given initial, [Y1, G2, W3, R4, B5]
assumeResult = "Y1 G2 W3 R4 B5"
initial = [
Card(cardId=0),
Card(cardId=13),
Card(cardId=25),
Card(cardId=37),
Card(cardId=49),
]
initialGivenDeck = Deck(initial=initial)
self.assertEqual(assumeResult, initialGivenDeck.reprCards())
def test_draw(self):
deck = Deck(_seed=12345)
assumeResult = ("W3", "B4", "Y1", "W1", "W3", "G2", "G5", "B1", "R2")
for assume in assumeResult:
# print(deck.draw().toShort())
self.assertEqual(assume, deck.draw().toShort())
def test_remainCardNum(self):
deck = Deck()
assumeResult = (49 - x for x in range(50))
# initial
self.assertEqual(50, deck.remainCardNum())
# each draws
for assume in assumeResult:
deck.draw()
self.assertEqual(assume, deck.remainCardNum())
def test_remainCardList(self):
deck = Deck(_seed=12345)
assumeResult = (
"W3", "B4", "Y1", "W1", "W3",
"G2", "G5", "B1", "R2", "G1",
"R1", "Y4", "R4", "W1", "B5",
"G3", "G3", "R3", "Y3", "W4",
"B1", "W2", "R2", "R1", "Y4",
"Y3", "G1", "Y2", "G4", "W5",
"R1", "Y1", "B2", "R4", "Y1",
"R3", "B3", "B3", "W2", "Y2",
"Y5", "G4", "W1", "W4", "G1",
"B2", "G2", "B4", "R5", "B1")
for assume in assumeResult:
# print(deck.draw())
self.assertEqual(assume, deck.draw().toShort())
def test_drewCardList(self):
deck = Deck(_seed=12345)
assumeResult = (
"W3", "B4", "Y1", "W1", "W3",
"G2", "G5", "B1", "R2", "G1",
"R1", "Y4", "R4", "W1", "B5",
"G3", "G3", "R3", "Y3", "W4",
"B1", "W2", "R2", "R1", "Y4",
"Y3", "G1", "Y2", "G4", "W5",
"R1", "Y1", "B2", "R4", "Y1",
"R3", "B3", "B3", "W2", "Y2",
"Y5", "G4", "W1", "W4", "G1",
"B2", "G2", "B4", "R5", "B1")
for _ in range(len(assumeResult)):
deck.draw()
remains = (
card.toShort()
for card
in deck.remainCardList()
)
for assume, remain in zip(assumeResult, remains):
self.assertEqual(assume, remains)
if __name__ == '__main__':
unittest.main()
|
f0a6897e5d202e1f445af2addcaf9f913bc4c480 | heraudk/Digicom | /test/test.py | 1,897 | 3.78125 | 4 | #a=5
#print (a)
#b=8.2
#print(a+b)
#a = (b+1)
#print(a)
#c = 1
#c = c + 3
#print(c)
#a, b = 4, 5.2
#print(a,b)
#c = a
#a = b
#b = c
#print(a,b)
#print(type(a))
#print(type(b))
#chaine = """Et voila, du texte"""
#print(chaine)
#var = 10
#print(type(var))
#var = str(var)
#print(type(var))
#var = float(var)
#print(type(var))
#print(var)
#var = int(var)
#print(var)
#reponse = input()
#age = input("Age : ")
#print(age, reponse)
#age = int(input("Quel est votre age ? "))
#if age > 18:
#print("Vous etes majeur")
#print(7>5>1)
#couleur = input("quelle est ta couleur ?")
#poids = int(input("Quel est ton poids ?"))
#if couleur == "rouge":
#if poids == "10 kg":
# print (couleur, poids)
# else:
# print(poids)
#else:
# print("la couleur n'est pas rouge")
#if couleur == "rouge" and poids > 10:
#print (couleur, poids)
#if couleur == "verte" or poids == 15:
#print(couleur, poids)
#else:
#print("la condition est fausse")
#i = 0
#while i < 10:
#i += 1
#if i%2 == 0:
#continue
#print(i)
#table = int(input("Voici une table de multiplication"))
#for x in range (1,11):
#print(2, "x", table, " = ",x*table)
#formulaire age:
#age = int(input("Quel est votre age ? "))
#if age >= 18:
#print("Vous etes majeur")
#if age <18:
#print("Vous etes mineur")
#Multiplication avec while:
#a=int(input("entrer un chiffre :"))
#b=10
#i=1
#while i<=b:
#print(a,"x",i,"=",a*i)
#i=i+1
#multiplication avec for/in methode 1 :
#def multiplication(valeur, max=10):
#for i in range(1, max + 1) :
#print(valeur * i, end=" ")
#print()
#multiplication (7)
#multiplication avec for/in méthode 2 :
#n = int(input("entrer un chiffre :"))
#print("La table de multiplication de : ", n," est :")
#for i in range(1,10):
#print(i , " x ", n, " = ",i*n)
|
2a07a1991ddede46faa3ac411306644c137e0dcf | Tamby998/Test | /diviseur.py | 258 | 3.9375 | 4 | a = 0
b = 0
r = 0
print('Donner 2 entiers positif A et B')
print('A : ')
a = int(input())
print('B : ')
b = int(input())
r = a
while r > 0:
r = r - b
if r == 0:
print('A est Divisible par B')
else:
print('A n\'est pas divisible par B')
|
b82d34ef7d95c94244ab552d6fc6ed8ee5f70163 | danilocamus/curso-em-video-python | /aula16a - Fatiamento.py | 482 | 4 | 4 | '''Tuplas são imutáveis.'''
linguagens = ('Python', 'JavaScript', 'C#', 'PHP')
print(linguagens[1]) #mostra a tupla que esta no índice 1 nesse caso o JavaScript
print(linguagens[0][1]) #mostra a tupla de indice 0 e o caractere de índice 1 dessa tupla
print(linguagens[1:3])
print(linguagens[1:])
print(linguagens[-2:])
print(len(linguagens))
for cont in range(0, len(linguagens)):
print(f'Eu vou aprender {linguagens[cont]} na posição {cont}')
print(20 * '-=')
|
1fd8f54834d80b0e0e56e54bc2e1e09d3aaac106 | danilocamus/curso-em-video-python | /aula 21/aula21d.py | 591 | 4.03125 | 4 | '''def somar(a=0, b=0, c=0):
s = a + b + c
print(f'A soma vale {s}')
somar(3, 2, 5)
somar(2, 2)
somar(7)
'''
def somar(a=0, b=0, c=0):
s = a + b + c
return s
r1 = somar(3, 4, 1)
r2 = somar(1, 9)
r3 = somar(2, 4)
print(f'{r1}, {r2}, {r3}')
print(somar(3, 2, 8))
def fatorial(num=1):
f = 1
for c in range(num, 0, -1):
f *= c
return f
n = int(input('Digite um numero: '))
print(f'O fatorial de {n} é igual a {fatorial(n)}')
f1 = fatorial(3)
f2 = fatorial(7)
f3 = fatorial(4)
print(f'Os resultados são {f1}, {f2}, {f3}') |
280ee2912d42ad706451ef7bea4647c6bafad1ba | danilocamus/curso-em-video-python | /aula 13/desafio 053.py | 548 | 3.921875 | 4 | frase = str(input('Digite uma frase: ')).strip().upper()
frase = frase.replace(" ", "")
''' ou
palavras = frase.split()
junto = ''.join()palavras
'''
inverso = ''
for letra in range(len(frase) - 1, -1, -1):
inverso += frase[letra]
print('O inverso de {} é {}'.format(frase, inverso))
if inverso == frase:
print('A frase é um palindromo')
else:
print('A frase não um palindromo')
'''
frase = frase.replace(" ", "")
frase = frase[::-1]
print(frase, len(frase))
for c in range(len(frase), 0, -1):
print(c)''' |
1eaa7fdb7ff4bde5dfd7365e20c38112315e3fca | danilocamus/curso-em-video-python | /desafio 013.py | 160 | 3.71875 | 4 | sal = float(input('Digite o salário atual para aplicar o aumento: '))
aum = (sal * 115) / 100
print('O salário era R$ {} e agora é R$ {}'.format(sal, aum)) |
dccef04f9cecca3e75bede170891e9768801ced0 | danilocamus/curso-em-video-python | /desafio 024.py | 159 | 3.71875 | 4 | n = str(input('Digite o nome de sua cidade: '))
div = n.split()
print('A cidade é {}\nEla possui santo no nome?\n{}'.format(n, 'santo' in div[0].lower()))
|
c2a4be9846b6603c8e292cba0c915ab2853ea895 | danilocamus/curso-em-video-python | /aula 13/desafio 055.py | 455 | 3.8125 | 4 | peso = 0
maior = 0
menor = 0
qnt = int(input('Digite quantas pessoas você quer analisar: '))
for c in range(1, qnt + 1):
peso = int(input('Digite o peso da pessoa {}: '.format(c)))
if c == 1:
maior = peso
menor = peso
else:
if peso > maior:
maior = peso
elif peso < menor:
menor = peso
print('O maior peso é {}'.format(maior))
print('O menor peso é {}'.format(menor)) |
78f47980996c9081dd8d301daa92193f2156a20d | danilocamus/curso-em-video-python | /aula 15/desafio 068.py | 1,170 | 3.515625 | 4 | import random
ia = 0
tot = 0
vit = 0
while True:
n = int(input('Digite um valor: '))
pi = ' '
while pi not in 'PI':
pi = str(input('Par ou Ímpar? [P/I] ')).strip().upper()[0]
ia = random.randint(0, 10)
tot = (n + ia) % 2
if tot == 0:
if pi in 'P':
print(f'Você jogou {n} e escolheu PAR. O computador escolheu {ia} e ÍMPAR. Total de {n + ia}')
print('Parabéns, você VENCEU!')
vit += 1
elif pi in 'I':
print(f'Você jogou {n} e escolheu ÍMPAR. O computador escolheu {ia} e PAR. Total de {n + ia}')
print('Você PERDEU!')
break
if tot == 1:
if pi in 'I':
print(f'Você jogou {n} e escolheu ÍMPAR. O computador escolheu {ia} e PAR. Total de {n + ia}')
print('Você VENCEU!')
vit += 1
elif pi in 'P':
print(f'Você jogou {n} e escolheu PAR. O computador escolheu {ia} e ÍMPAR. Total de {n + ia}')
print('Você PERDEU!')
break
print('Vamos jogar novamente...')
print(f'Fim de Jogo. Você venceu um total de {vit} vez(es)') |
fe3389ffe3afc3c607418d461b8628cf8dfd50ee | danilocamus/curso-em-video-python | /aula 17/desafio 081.py | 487 | 3.875 | 4 | lista = []
cont = 0
while True:
sair = ' '
lista.append(int(input('Digite um valor para pôr na lista: ')))
cont += 1
while sair not in 'SsNn':
sair = str(input('Você deseja continuar? [S/N] '))
if sair in 'Nn':
break
print(f'Foram digitados {cont} números')
lista.sort(reverse=True)
print(f'A lista em forma decrescente é {lista}')
if 5 in lista:
print('O valor 5 esta na lista')
else:
print('O valor 5 não esta na lista') |
9f47f94c531526d90ab4b3340852892d56e24f11 | danilocamus/curso-em-video-python | /aula 13/desafio 054.py | 426 | 3.703125 | 4 | from datetime import datetime
maior = 0
menor = 0
quant = int(input('Digite quantas pessoas você quer analisar: '))
data = datetime.now()
for c in range(1, quant + 1):
idade = int(input('Informe o ano de nascimento da pessoa {}: '.format(c)))
if (data.year - idade) < 18:
maior += 1
else:
menor += 1
print('{} pessoa(s) são de maior.\n{} pessoa(s) são de menor.'.format(maior, menor)) |
8dea88d32f690c94db0d91c77430c73137d0d5b8 | danilocamus/curso-em-video-python | /aula 15/desafio 071.py | 504 | 3.6875 | 4 | cedulas = 50
saque = int(input('Digite o valor a ser sacado: '))
totced = 0
total = saque
while True:
if total >= cedulas:
total -= cedulas
totced += 1
else:
if totced > 0:
print(f'total de {totced} cédulas de R$ {cedulas}')
if cedulas == 50:
cedulas = 20
elif cedulas == 20:
cedulas = 10
elif cedulas == 10:
cedulas = 1
totced = 0
if total == 0:
break |
e99f64f7a7c47001fda2b7493f136c528b0d2da2 | danilocamus/curso-em-video-python | /aula15b.py | 361 | 4 | 4 | nome = 'Amanda'
idade = 28
salario = 987.35
print(f'A {nome:10} tem {idade} anos e ganha R$ {salario}')
print(f'A {nome:^10} tem {idade} anos e ganha R$ {salario}')
print(f'A {nome:-^10} tem {idade} anos e ganha R$ {salario}')
print(f'A {nome:->10} tem {idade} anos e ganha R$ {salario}')
print(f'A {nome:-<10} tem {idade} anos e ganha R$ {salario}')
|
7bb50d2132b47e415d67bd07dcdf4a82ce95fc16 | danilocamus/curso-em-video-python | /aula18a.py | 327 | 4.28125 | 4 | pessoas = [['Pedro', 25], ['Maria', 26], ['Jaqueline', 29]]
print(pessoas[1]) #mostra a lista de índice 1 que esta dentro da lista pessoas
print(pessoas[0][1]) #mostra o conteudo de índice 1 da lista de índice 0 que esta na lista pessoas
print(pessoas[0][0])
print(pessoas[1][1])
print(pessoas[2][0])
print(pessoas[2]) |
7bfde9995154ed324c387c2c211583ee1e42cfe9 | cuihee/LearnPython | /Day01/c0108.py | 471 | 4.375 | 4 | """
字典的特点
字典的key和value是什么
新建一个字典
"""
# 字典
# 相对于列表,字典的key不仅仅是有序的下标
dict1 = {'one': "我的下标是 one", 2: "我的下标是 2"}
print(dict1['one']) # 输出键为 'one' 的值
print(dict1[2]) # 输出键为 2 的值
print('输出所有下标', type(dict1.keys()), dict1.keys())
# 另一种构建方式
dict2 = dict([(1, 2), ('2a', 3), ('3b', 'ff')])
print('第二种构建方式', dict2)
|
451ec9dda32cce125e3ff29be9592c2ff06e9b4f | cuihee/LearnPython | /Day04/c0401_iter.py | 561 | 3.78125 | 4 | l1 = [1, 2, 3, 4]
l1_iter = iter(l1)
print(next(l1_iter))
print(next(l1_iter))
print(next(l1_iter))
print(next(l1_iter))
l1_iter = iter(l1)
for _ in l1_iter:
print(_, end=" ")
print()
class MyNumbers:
def __iter__(self):
self.a = 10
return self
def __next__(self):
if self.a<=30:
x = self.a
self.a += 10
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter)) |
f1739857331375f4a48f609922e3b12caa103d48 | cuihee/LearnPython | /Day01/c0110.py | 2,182 | 3.953125 | 4 | # math
"""
在python中如何进行数学运算
"""
x, y = 2, 3
print('两个数比较的三个结果 -1 0 1:', (x > y) - (x < y))
'''
abs(x) 返回数字的绝对值,如abs(-10) 返回 10
ceil(x) 返回数字的上入整数,如math.ceil(4.1) 返回 5
exp(x) 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045
fabs(x) 返回数字的绝对值,如math.fabs(-10) 返回10.0
floor(x) 返回数字的下舍整数,如math.floor(4.9)返回 4
log(x) 如math.log(math.e)返回1.0,math.log(100,10)返回2.0
log10(x) 返回以10为基数的x的对数,如math.log10(100)返回 2.0
max(x1, x2,...) 返回给定参数的最大值,参数可以为序列。
min(x1, x2,...) 返回给定参数的最小值,参数可以为序列。
modf(x) 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。
pow(x, y) x**y 运算后的值。
round(x [,n]) 返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。
sqrt(x)返回数字x的平方根。
随机数
choice(seq) 从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。
randrange([start,] stop [,step]) 从指定范围内,按指定基数递增的集合中获取一个随机数,基数默认值为 1
random() 随机生成下一个实数,它在[0,1)范围内。
seed([x]) 改变随机数生成器的种子seed。如果你不了解其原理,你不必特别去设定seed,Python会帮你选择seed。
shuffle(lst) 将序列的所有元素随机排序
uniform(x, y) 随机生成下一个实数,它在[x,y]范围内。
三角函数
acos(x) 返回x的反余弦弧度值。
asin(x) 返回x的反正弦弧度值。
atan(x) 返回x的反正切弧度值。
atan2(y, x) 返回给定的 X 及 Y 坐标值的反正切值。
cos(x) 返回x的弧度的余弦值。
hypot(x, y) 返回欧几里德范数 sqrt(x*x + y*y)。
sin(x) 返回的x弧度的正弦值。
tan(x) 返回x弧度的正切值。
degrees(x) 将弧度转换为角度,如degrees(math.pi/2) , 返回90.0
radians(x) 将角度转换为弧度
'''
import math
print('常量pi=', math.pi)
print('常量e=', math.e)
|
58300c6d8bcadcc21a62e52a29c69e80cc6dbfc3 | RamrajSegur/Computer-Vision-Python | /OpenCV-Python/imagemasking.py | 924 | 3.625 | 4 | import cv2
import numpy as np
img1=cv2.imread('/home/ramraj/Downloads/messi.jpg',0)#Image that is going to be on background
img=cv2.imread('/home/ramraj/Downloads/mainlogo.png',0)#Image that is going to be on foreground
rows,columns=img.shape
roi=img1[0:rows,0:columns]#Making the region on interest
ret,img_thres=cv2.threshold(img,220,255,cv2.THRESH_BINARY_INV)#Making the mask for foreground image
img_thres_inv=cv2.bitwise_not(img_thres)#Making the mask for background image
img_3=cv2.bitwise_and(roi,roi,mask=img_thres_inv)#Making the pixels transparent on the region where the foreground image will come
img_4=cv2.bitwise_and(img,img,mask=img_thres)#Making the pixels transparent on the region where the background image will come
img_5=cv2.add(img_3,img_4)#Blending two regions
img1[0:rows,0:columns]=img_5#Adding the blended region to the image
cv2.imshow("Image_blended",img1)
cv2.waitKey(0)
cv2.destroyAllWindows() |
59412e27906d5aa3a7f435bfb4ab63d9ee5ed5a2 | RamrajSegur/Computer-Vision-Python | /OpenCV-Python/line.py | 1,046 | 4.125 | 4 | #Program to print a line on an image using opencv tools
import numpy as np
import cv2
# Create a grayscale image or color background of desired intensity
img = np.ones((480,520,3),np.uint8) #Creating a 3D array
b,g,r=cv2.split(img)#Splitting the color channels
img=cv2.merge((10*b,150*g,10*r))#Merging the color channels with modified color channel values
# Draw a diagonal blue line with thickness of 5 px
print img.dtype
print img
cv2.line(img,(0,0),(200,250),(0,0,0),5)#First argument defines the image matrix to which the line has to be added
#Second and third are coordinate points
#Fourth will determine the color of the line which is in matrix form : in BGR Order
#Fifth argument gives the width of the line
cv2.rectangle(img,(20,30),(300,400),(255,255,255),2)
cv2.circle(img,(400,400),40,(0,255,255),4)
pts=np.array([[40,50],[80,90],[60,80],[80,90]],np.int32)
cv2.polylines(img,[pts],False,(0,0,0),3)
font=cv2.FONT_HERSHEY_DUPLEX
cv2.putText(img, 'Hello There!',(200,400),font, 1, (200,150,255),2)
cv2.imshow('image',img)
cv2.waitKey(0)
|
7df534569230d885c07c1b24f81c5d32361063ef | mozartkun/TakeHomeAssignment | /Charles&Keith/ZhaoYunkun_CharlesKeith_Question1.py | 14,869 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Question 1: Neo Saves World
# ### Python Version 3.5+
# In[ ]:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#Python version: 3.5+
from collections import defaultdict
import random
import string
import sys, os, time, datetime
from copy import deepcopy
# In[ ]:
# Define the class of this game
class neo_save_world(object):
def __init__(self):
self.num_of_balls = -1 # Initialize the cardinality of balls set: number of balls in this set
self.balls_set = [] # Initialize the balls set: value is color 0/1
self.color = [0, 1] # Ball color is either 0 or 1
self.majority_color = -1 # Initialize majority color in this game: either 0 or 1
self.num_of_query = -1 # Initialize the number of queries that Neo should ask Viky
self.same_diff_color = defaultdict(lambda: [set(), set()]) # Neo's memory about queries;
# key: each ball index;
# value: 1st set() stores same-color balls set,
# 2nd set() stores diff-color balls set
self.neo_guess = -1 # Initialize Neo's guess about which ball index is majority-color
self.trantab = str.maketrans({key: None for key in ' ' + string.punctuation}) # Remove punctuations from each inputted value if exists any
def input_line1(self):
'''This function is used to return formatted inputs from the user.
Outputs:
1) line1: A list of string values converted from the first line inputs
'''
# This block of codes is used to deal with first line of inputs by the user
print("Line 1: Please input 5 single space separated characters/Integers.")
print("1st value is an integer N which is the cardinality of the balls set.")
print("2nd value is 0 indicating that Majority exists.")
print("3rd value is an integer indicating the number of times Viky might lie (0 in this version of the game).")
print("4th value is 2 indicating each ball can only have any of the 2 colors.")
print("5th value is an integer 1 indicating the Viky lies exactly 0 time(ignore this number).")
input_value1 = input("Please input these 5 values, delimited by single space and end with enter: \n")
line1 = input_value1.strip().split()
line1 = [item.translate(self.trantab) for item in line1] # Each splitted input value should remove punctuations if exists any
return line1
def input_line2(self):
'''This function is used to return formatted inputs from the user.
Outputs:
1) line2: A string value converted from the second line input.
'''
# This block of codes is used to deal with second line of inputs by the user
print("Line 2: Please input an integer D, indicating D queries that Neo should ask and Viky should answer.")
input_value2 = input("Please input one integer and end with enter: \n")
line2 = input_value2.strip()
return line2
def display_introduction(self):
'''This function is used to display the introduction of this game, and initialize this game.
Make sure that the first line of values inputted by the user really satisfies the formatted rule.
If yes, then continue. If not, then repeat until everything is satisfies.
'''
print("=====Beginning of A New Game: Local Time {0}=====".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
time.sleep(1)
# Make sure whether Line 1 inputted values satisfy the formatted rule
flag_line1 = False # A flag showing that Line 1 inputs are fine
while not flag_line1:
# First line of inputs by the user
line_1 = self.input_line1()
if len(line_1) != 5:
print("Warning: You did not input exactly 5 values. Please follow the guidelines.")
elif not line_1[0].isdigit():
print("Warning: 1st value you input is not an integer. Please follow the guidelines.")
elif int(line_1[0]) < 2:
print("Warning: 1st value you input is lower than 2. Please input a bigger integer and follow the guidelines.")
elif line_1[1] not in ['0', 0]:
print("Warning: 2nd value you input is not 0. Please follow the guidelines.")
elif line_1[2] not in ['0', 0]:
print("Warning: 3rd value you input is not 0. Please follow the guidelines.")
elif line_1[3] not in ['2', 2]:
print("Warning: 4th value you input is not 2. Please follow the guidelines.")
elif line_1[4] not in ['1', 1]:
print("Warning: 5th value you input is not 1. Please follow the guidelines.")
else:
print("Your 5 input values of first line are: {0}".format(line_1))
flag_line1 = True
time.sleep(1)
# Make sure whether Line 2 inputted value satisfy the formatted rule
flag_line2 = False # A flag showing that Line 2 input is fine
while not flag_line2:
# Second line of inputs by the user
line_2 = self.input_line2()
if not line_2.isdigit():
# Repeat Line 2
print("Warning: This value is not integer. Please follow the guidelines.")
else:
print("Your input value of second line is: {0}".format(line_2))
flag_line2 = True
time.sleep(1)
# After two lines are correctly inputted, the game is then initialized
self.num_of_balls = int(line_1[0]) # Cardinality of this balls set
self.balls_set = [random.choice(self.color) for i in range(self.num_of_balls)] # Now each ball has its color: 0/1
self.num_of_query = int(line_2) # Number of queries that Neo should ask Viky
# Make sure balls_set has majority-color indeed; If not, then randomly assign color again
while sum(self.balls_set) == self.num_of_balls / 2:
self.balls_set = [random.choice(self.color) for i in range(self.num_of_balls)] # Re-assign ball color
self.majority_color = 1 if sum(self.balls_set) > self.num_of_balls / 2 else 0 # Majority color: 0/1
print("The balls set and their colors are prepared. Let Neo send queries to Viky and then guess.")
def neo_query_viky(self):
'''This function is used to show what queries is Neo making to ask Viky, and what responses is Viky making to Neo's queries.
Neo updates memory when making queries.
'''
# Brush Neo's memory about same-color balls
for ball_index in range(self.num_of_balls):
self.same_diff_color[ball_index][0].add(ball_index)
# Ask queries:
for query_id in range(self.num_of_query):
time.sleep(1)
# Initialize two balls index that Neo ask each time: Sampling without replacement
first_ball, second_ball = random.sample(range(self.num_of_balls), 2)
# Neo asks and Viky answers
print("Neo asks {0}: Ball {1} and Ball {2} are same-color?".format(query_id, first_ball, second_ball))
answer = "YES" if self.balls_set[first_ball] == self.balls_set[second_ball] else "NO" # Viky's answer
print("Viky answers {0}: {1}".format(query_id, answer))
print("Query {0} is: {1}".format(query_id, [first_ball, second_ball, answer]))
# Neo memorizes this query in the brain: Update Neo's memory about same-color balls
# If balls are same-color, add positive index in the same-color set; If not, add ball index in the diff-color set
if answer == "YES":
self.same_diff_color[first_ball][0].add(second_ball)
self.same_diff_color[second_ball][0].add(first_ball)
elif answer == "NO":
self.same_diff_color[first_ball][1].add(second_ball)
self.same_diff_color[second_ball][1].add(first_ball)
def neo_make_guess(self):
'''This function is used to show how Neo processes memory and makes guess.
In the end of game, after Neo finishes D queries (D is given in second line input), Neo should make a guess about
majority-color ball. Neo should propose a ball index (possibly majority-color or not) based on Neo's judgement on
previous queries.
'''
# Since there are only 2 colors, ball A and ball B are either same-color or diff-color
update_memory = defaultdict(lambda: [set(), set()]) # make a copy and then update and compare
# Neo updates the memory until reaching consistency/statiblity
print("Neo says: Let me think for a while.")
while(update_memory != self.same_diff_color):
update_memory = deepcopy(self.same_diff_color) # temporary copy
# Then update
for ball_index in range(self.num_of_balls):
#ball_same, ball_diff = self.same_diff_color[ball_index]
for compare_index in range(self.num_of_balls):
#compare_same, compare_diff = self.same_diff_color[compare_index]
# Case 1. If two same-color ball set share the same ball index, or two diff-color ball set share the same ball index,
# then combine same-color ball set
if not self.same_diff_color[ball_index][0].isdisjoint(self.same_diff_color[compare_index][0]) or not self.same_diff_color[ball_index][1].isdisjoint(self.same_diff_color[compare_index][1]):
self.same_diff_color[ball_index][0].update(self.same_diff_color[compare_index][0])
self.same_diff_color[ball_index][1].update(self.same_diff_color[compare_index][1])
self.same_diff_color[compare_index][0].update(self.same_diff_color[ball_index][0])
self.same_diff_color[compare_index][1].update(self.same_diff_color[ball_index][1])
# Case 2. If one same-color ball set share the same ball index with another diff-color ball set,
# then combine one same-color ball set with another diff-color ball set
if not self.same_diff_color[ball_index][0].isdisjoint(self.same_diff_color[compare_index][1]) or not self.same_diff_color[ball_index][1].isdisjoint(self.same_diff_color[compare_index][0]):
self.same_diff_color[ball_index][0].update(self.same_diff_color[compare_index][1])
self.same_diff_color[ball_index][1].update(self.same_diff_color[compare_index][0])
self.same_diff_color[compare_index][0].update(self.same_diff_color[ball_index][1])
self.same_diff_color[compare_index][1].update(self.same_diff_color[ball_index][0])
print("The same-color diff-color ball memory is: {0}".format(self.same_diff_color))
print("Neo says: Let me guess a number.")
# Select the ball index with longest same-color balls set
length_same_color_ballset = 0 # Initialize
for ball_index in range(self.num_of_balls):
if len(self.same_diff_color[ball_index][0]) > length_same_color_ballset:
self.neo_guess = ball_index
length_same_color_ballset = len(self.same_diff_color[ball_index][0])
print("Neo says: I know which ball index number of majority-color.")
def end_game(self):
'''This function is used to determine whether Neo's guess is correct.
If Neo's guess is really a majority-color ball, then Neo wins the game and human being is saved.
'''
if self.balls_set[self.neo_guess] != self.majority_color:
print("Bad Ending: Neo loses the game. John destroys human being.")
print("=====Game Over: Local Time {0}=====".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
else:
print("Happy Ending: Neo wins the game. John reaches truce. Human being is saved.")
print("=====The End of This Story: Local Time {0}=====".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
def main(self):
'''This function is used to be main function of this guess game.
First, the screen will display guidelines for the user to input 2 lines of values, in order to initilize this game.
Second,
'''
# Step 1. Display game guidelines. Wait for the user's inputs of first line and second line. Initialize this game.
self.display_introduction()
# Constraint: If number of queries is lower than half of cardinality of balls set, then quickly game over
if self.num_of_query < self.num_of_balls / 2:
print("Bad Ending: Neo has too few queries and loses the game. John destroys human being.")
print("=====Game Over: Local Time {0}=====".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
else:
time.sleep(1)
# Step 2. Neo makes queries and Viky responses
self.neo_query_viky()
time.sleep(1)
# Step 3. Neo makes guess. Then John shows the game initialization: Balls set, ball color, majority-color
self.neo_make_guess()
print("Neo answers: The ball indexed at {0} with color {1} is of the majority".format(self.neo_guess, self.balls_set[self.neo_guess]))
print("John says: The majority color is: {0}".format(self.majority_color))
print("John says: The balls index and their colors are: \n{0}".format([(index, color) for index, color in enumerate(self.balls_set)]))
time.sleep(1)
# Step 4. John decides whether Neo's guess is correct or not. Neo wins if Neo's guess is correct.
self.end_game()
print("Final Output: Neo answers that the ball indexed at {0} is of the majority.".format(self.neo_guess))
# In[ ]:
# Run this game
if __name__ == "__main__":
new_game = neo_save_world()
new_game.main()
# In[ ]:
|
b4aa1339a99c1743c6c27102d987bfaf5ff52916 | gulcanfatih/python-kodlari | /7_if.py | 1,213 | 3.984375 | 4 | # if kullanarak hesap makinesi yapma işlemi
print("---MENÜ---")
print("1-toplama")
print("2-çıkarma")
print("3-bölme")
print("4-çarpma")
print(10 * "-")
secim = int(input("seçiminizi giriniz :"))
if secim == 1:
print("toplama")
sayi1 = int(input("1.sayıyı giriniz :"))
sayi2 = int(input("2.sayıyı giriniz :"))
sonuc = sayi1 + sayi2
print(f"{sayi1} + {sayi2} = {sonuc}")
elif secim == 2:
print("çıkartma")
sayi1 = int(input("1.sayıyı giriniz :"))
sayi2 = int(input("2.sayıyı giriniz :"))
sonuc = sayi1 - sayi2
print(f"{sayi1} - {sayi2} = {sonuc}")
elif secim == 3:
print("bölme")
sayi1 = int(input("1.sayıyı giriniz :"))
sayi2 = int(input("2.sayıyı giriniz :"))
if sayi2 == 0:
print("tanımsız")
exit()
sonuc = sayi1 // sayi2
kalan = sayi1 % sayi2
print(f"{sayi1} / {sayi2} = {sonuc}")
print(f"kalan = {kalan}")
elif secim == 4:
print("çarpma")
sayi1 = int(input("1.sayıyı giriniz :"))
sayi2 = int(input("2.sayıyı giriniz :"))
sonuc = sayi1 * sayi2
print(f"{sayi1} * {sayi2} = {sonuc}")
else:
print("hatalı seçim yaptınız.")
|
c4c484d4a0d445ce4324e4804e4ec3a609c6c97c | arya140101/Pemrograman-Jaringan- | /Python/kelilingdanluas.py | 277 | 3.6875 | 4 | panjang=eval(input("Masukkan panjang persegi panjang = "))
lebar=eval(input("Masukkan lebar persegi panjang = "))
luas=panjang * lebar
print("\nLuas Persegi Panjang adalah = %d"%(luas))
keliling=2*(panjang + lebar)
print("nkeliling Persegi Panjang adalah = %d"%(keliling)) |
5aa8cf71a6585c139789e83b13447e3f51de6fe3 | ScipioXaos/BUGZ | /engine/world/Location.py | 805 | 3.90625 | 4 | # BUGZ! - A Python 'Learning' Adventure coded in Python!
# File Description: Location.py is a wrapper class used to pair two integers
# together. These integers represent an X-Y coordinate
# pair and a "Location" in a Map instance.
# Class Description: Location is the wrapper class used to represent an
# X-Y coordinate pair in a more efficient manner.
class Location:
def __init__(self, y, x):
self.y = y
self.x = x
def get_x(self):
return self.x
def get_y(self):
return self.y
def set_coords(self, y, x):
self.y = y
self.x = x
def set_x(self, x):
self.x = x
def set_y(self, y):
self.y = y
|
dac4fea633910137cc60dc5c73d8558886877f09 | dennisSaadeddin/pythonDataStructures | /manual_queue/Queue.py | 2,121 | 4.15625 | 4 | from manual_queue.QueueElem import MyQueueElement
class MyQueue:
def __init__(self):
self.head = None
self.tail = None
self.is_empty = True
def enqueue(self, elem):
tmp = MyQueueElement(elem)
if self.head is None:
self.head = tmp
if self.tail is not None:
self.tail.next = tmp
self.tail = tmp
self.is_empty = False
def dequeue(self):
if self.is_empty:
print("Queue is empty.")
else:
self.head = self.head.next
if self.head is None:
self.is_empty = True
def front(self):
if self.is_empty:
print("Queue is empty. There's no front element.")
else:
print("Head: ", self.head.data)
def rear(self):
if self.is_empty:
print("Queue is empty. There's no rear element.")
else:
print("Tail: ", self.tail.data)
def print_queue(self):
tmp = self.head
while tmp is not None:
if tmp.next is None:
print(tmp.data)
else:
print(tmp.data, " - ", end="", flush=True)
tmp = tmp.next
breadQueue = MyQueue()
breadQueue.enqueue(1)
breadQueue.enqueue(2)
breadQueue.enqueue(3)
breadQueue.enqueue(4)
breadQueue.enqueue(5)
breadQueue.enqueue(6)
breadQueue.enqueue(7)
breadQueue.front()
breadQueue.rear()
if breadQueue.is_empty:
print("The queue is empty. Please add elements.")
else:
print("Here's your queue: ")
breadQueue.print_queue()
breadQueue.dequeue()
breadQueue.print_queue()
breadQueue.dequeue()
breadQueue.print_queue()
breadQueue.dequeue()
breadQueue.print_queue()
breadQueue.dequeue()
breadQueue.print_queue()
breadQueue.dequeue()
breadQueue.print_queue()
breadQueue.dequeue()
breadQueue.print_queue()
breadQueue.dequeue()
breadQueue.print_queue()
breadQueue.front()
breadQueue.rear()
if breadQueue.is_empty:
print("The queue is empty. Please add elements.")
else:
print("Here's your queue: ", breadQueue.print_queue())
if __name__ == "__main__":
MyQueue()
|
ba1922c5b9c011d78ce7928c2c0de395f468e521 | saifulmz/learning-python | /one-code-per-day/2017-05-15-sensitive_words-replace.py | 1,980 | 4.09375 | 4 | # -*- coding: utf-8 -*-
'''
敏感词文本文件 filtered_words.txt,
里面的内容为以下内容("北京 程序员 公务员 领导 牛比 牛逼 你娘 你妈 love sex jiangge",
当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。
2017-05-15
Jing Qin
'''
import string
import sys
def sensitive_words(filtered_file):
# read file and save it as a sensitive_words list
with open(filtered_file, 'r') as f:
lines =f.read()
sensitive_words = lines.split()
return sensitive_words
def test_words(test_file):
#read from input, if there is word in the sensitive_words list print "Freedom",otherwise print"Human Rights"
with open(test_file, 'r') as t:
lines =t.read()
test_words = lines.split()
return test_words
def replace_sensitive_word(filtered_file,test_file):
'''
Get filtered_file and test_file as arguments of function "replace_sensitive_word",
call function "test_words" and "sensitive_words" inside.
Since sensitive words only contain English and Chinese,
so the length of the none-English word (Chinese)will be divided by 3
to get the correct number of characters.
'''
new_line = ""
sensitive = False
sensitive_words_list = sensitive_words(filtered_file)
for word in test_words(test_file):
chinese = False
len_word = len(word)
replaced_word = word
if word in sensitive_words_list:
for ch in word:
if ch not in string.ascii_letters:
chinese = True
break
if chinese:
replaced_word = (len_word/3)*"*"
else:
replaced_word = len_word*"*"
new_line =new_line + replaced_word +" "
print new_line
if __name__ == '__main__':
replace_sensitive_word(sys.argv[1],sys.argv[2])
|
23d8c3236510bb3c7c8aceccea380067093deaa2 | PhathuAuti/intro-oop | /bank_account.py | 837 | 3.640625 | 4 | class BankAccount:
def __init__(self, bank_account_number, balance, int_rate, month_fee, customer):
self.bank_account_number = bank_account_number
self.balance = balance
self.int_rate = int_rate
self.month_fee = month_fee
self.customer = customer
def finish_month(self):
int_amount = self.balance * self.int_rate / 12
self.balance = self.balance + int_amount - self.month_fee
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
self.balance -= amount
return self.balance
# bank_acc = BankAccount("1234567789",1000, 0.12, 50, "Harold")
# bank_acc.deposit(100)
# bank_acc.withdraw(300)
# print(bank_acc.finish_month())
# # print(bank_acc.balance) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.