blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
65a65098dd270deac773c7a30002197e02ba1189 | eduardojordan/Practicas-Python | /KC_EJ05.py | 222 | 4.09375 | 4 |
mes = input("Escribe el Mes:")
año = input("Escribe el Año:")
mesDos = input("Escribe otro Mes:")
añoDos = input("Escribe otro Año:")
if mes != mesDos or año != añoDos:
print ("False")
else:
print ("True")
|
6224a5adabe1b796d293ccf35b0adedc5f9bac69 | FossMec/Code-a-pookalam | /Malavika_S_Menon/Malavika_pookalam.py | 1,389 | 3.90625 | 4 | import turtle
my_window = turtle.Screen()
my_window.bgcolor("black")
# creates a graphics window
my_pen = turtle.Turtle()
my_pen.speed()
my_pen.up()
my_pen.goto(0,-250)
my_pen.down()
my_pen.color('darkgreen')
my_pen.begin_fill()
my_pen.circle(250)
my_pen.end_fill()
my_pen.goto(0,-220)
my_pen.color('yellow')
my_pen.begin_fill()
my_pen.circle(220)
my_pen.end_fill()
side=8
length=50
angle=360/8
my_pen.goto(0,0)
for j in range(8):
my_pen.begin_fill()
my_pen.right(360/8)
my_pen.color('orangered')
for i in range(side):
my_pen.forward(length)
my_pen.left(angle)
my_pen.end_fill()
for j in range(8):
my_pen.begin_fill()
my_pen.right(360/8)
my_pen.color('orange')
for i in range(side):
my_pen.forward(30)
my_pen.left(angle)
my_pen.end_fill()
my_pen.up()
my_pen.left(90)
#my_pen.left(90)
my_pen.forward(120)
my_pen.left(90)
my_pen.forward(50)
my_pen.left(360/8)
my_pen.down()
my_pen.color('brown')
my_pen.begin_fill()
my_pen.forward(100)
my_pen.right(120)
my_pen.forward(100)
my_pen.right(120)
my_pen.forward(100)
my_pen.end_fill()
for i in range(7):
my_pen.begin_fill()
my_pen.left(75)
my_pen.forward(100)
my_pen.right(120)
my_pen.forward(100)
my_pen.end_fill()
my_pen.up()
my_pen.goto(0,0)
my_pen.down()
my_pen.left(60)
print my_pen.xcor()
print my_pen.ycor()
my_pen.color('white')
my_pen.shape('circle')
turtle.exitonclick()
|
da489ff3d3767dafa2f7edaf12f4e1d7038ec935 | mortontaj/Python_9 | /Part 9/timezone_challenge.py | 1,679 | 4.3125 | 4 | # create a program that allows a user to choose one of
# up to 9 time zones from a menu. You can choose any
# zones you want from the all_timezones list
#
# The program will then display the time in that timezone,
# as well as local time and UTC time.
#
# Entering 0 as a choice will quit the program.
#
# Display the dates and times in a format suitable for the
# user of your program to understand, and include the
# timezone name when displaying the chosen time..
import pytz
import datetime
number = {1: {"1": "US/Eastern"},
2: {"2": "US/Central"},
3: {"3": "US/Mountain"},
4: {"4": "US/Pacific"},
5: {"5": "US/Alaska"},
6: {"6": "US/Arizona"},
7: {"7": "US/Hawaii"},
8: {"8": "US/Michigan"},
9: {"9": "US/Indiana-Starke"},
10: {"10": "US/East-Indiana"},
}
while True:
for val in number.values():
print(val)
removed_symbols = "[", "]", "'"
time_zone = ""
chose = int(input("Enter a number between 1 and 10 or 0 to quit: "))
zone = number.get(chose)
if chose == 0:
print("Bye!")
break
else:
for char in zone.values():
if char == removed_symbols:
continue
else:
time_zone = "".join(char)
chosen = pytz.timezone(time_zone)
print("*" * 60)
print()
print("{}: \t{}".format(chosen, datetime.datetime.now(tz=chosen).strftime("%A %x %X %z")))
print("Local time: \t{}".format(datetime.datetime.now().strftime("%A %x %X %z")))
print("UTC time: \t\t{}".format((datetime.datetime.utcnow().strftime("%A %x %X %z"))))
|
e6ebe1c40435126ca25592cb7b558f86d0732c43 | chriscarter3377/ASSIGNMENTS | /osimport.py | 530 | 3.65625 | 4 |
import os
filepath = input("Enter path for file: ")
filename = input("Enter name of file: ")
if not os.path.exists(filepath):
os.makedirs(filepath)
fullname = os.path.join(filepath,filename + ".csv")
name = input("Enter full name: ")
address = input("Enter Address: ")
phone = input("Enter Phone Number: ")
fileobj = open(fullname, "w")
fileobj.write(name+'\n' " " +address+'\n' " " +phone +'\n')
fileobj.close()
fileobj = open(fullname, "r")
print('\n')
print(fileobj.read())
|
547fbf27509a9ebabbceecf4e3334220f09cad70 | Nicolas5425/WWW | /Hola.py | 1,216 | 4.03125 | 4 | print "Elija Opcion 1.Calculadora, 2.Impar o Par"
sel1=int(raw_input("Que Opcion Desea Elegir?"))
if sel1==1:
op=(raw_input("Que Opcion Desea Elegir (+, -, *, /"))
if op=="+":
val1=int(raw_input("Ingresa Primer Dato"))
val2=int(raw_input("Ingresa Segundo Dato"))
print "Suma", val1 + val2
else:
if op=="-":
val1=int(raw_input("Ingresa Primer Dato"))
val2=int(raw_input("Ingresa Segundo Dato"))
print "Resta", val1 - val2
else:
if op=="*":
val1=int(raw_input("Ingresa Primer Dato"))
val2=int(raw_input("Ingresa Segundo Dato"))
print "Multiplicacion", val1 * val2
else:
if op=="/":
val1=int(raw_input("Ingresa Primer Dato"))
val2=int(raw_input("Ingresa Segundo Dato"))
if val2!=0:
print "Division", val1 / val2
print "Residuo", val1 % val2
else:
if sel1==2:
val2=int(raw_input("Ingrese Numero"))
if val2%2==0:
print "Es Par"
else:
print "Es Impar"
else:
print "Es Bobo"
|
c79387cb43043b472739790b14f16236cd884c90 | gwaxG/pypatterns | /structural/facade/facade.py | 1,070 | 3.5625 | 4 | #!/usr/bin/env python3
# coding: utf-8
from abc import ABC, abstractmethod
'''
Facade proposes a simple interface for a complex system.
'''
class Computer:
def power_suply(self):
print('Power suply')
def post(self):
print('Power-on self-test')
def show_loading_screen(self):
print('Loading screen')
def BIOS(self):
print('Accessing the first sector')
def BIOS_confirmation(self):
print('BIOS confirms there\'s a bootstrap loader')
def loading_os(self):
print('Loading operating system into memory')
def turn_control(self):
print('Control is passed over OS')
class ComputerUserFacade:
def __init__(self, pc: Computer):
self.pc = pc
def turn_on(self):
self.pc.power_suply()
self.pc.post()
self.pc.show_loading_screen()
self.pc.BIOS()
self.pc.BIOS_confirmation()
self.pc.loading_os()
self.pc.turn_control()
if __name__ == '__main__':
pc = Computer()
ui = ComputerUserFacade(pc)
ui.turn_on()
|
02d3a50e1834ece511b82c51937761f027419ebb | raviarrow88/Python-coding | /algorithms/sequential_search.py | 324 | 3.828125 | 4 | #Write a Python program for sequential search.
def seq_search(l,target):
found = False
pos = 0
while pos<len(l) and not found:
if l[pos] == target:
found = True
else:
pos = pos+1
return found, pos
print(seq_search([11, 23, 58, 31, 56, 77, 43, 12, 65, 19], 31))
|
e381307d78620c19c0e9f6a279b774937b5fcef6 | Oscarpingping/Python_code | /01-Python基础阶段代码/04-Python文件操作/Python文件操作.py | 2,069 | 3.625 | 4 |
# 1. 打开文件
# 相对路径, 相对于哪一个目录下面的指定文件
# f = open("a.txt", "r+")
#
# # 2. 读写操作
# content = f.read()
# print(content)
# #
# f.write("88888")
#
#
# # 3. 关闭文件
# f.close()
# 1. 打开xx.jpg文件, 取出内容, 获取内容的前面半部分
# 1.1 打开文件
# fromFile = open("xx.jpg", "rb")
#
# # 1.2 读取文件内容
# fromContent = fromFile.read()
# print(fromContent)
#
# # 1.3 关闭文件
# fromFile.close()
#
#
# # 2. 打开另外一个文件xx2.jpg, 然后, 把取出的半部分内容, 写入到xx2.jpg文件里面去
# # 2.1 打开目标文件
# toFile = open("xx2.jpg", "wb")
#
# # 2.2 写入操作
# content = fromContent[0: len(fromContent) // 2]
# toFile.write(content)
#
#
# # 2.3 关闭文件
# toFile.close()
# f = open("a.txt", "rb")
#
# print(f.tell())
# f.seek(-2, 2)
# print(f.tell())
#
# print(f.read())
# print(f.tell())
#
#
#
# f.close()
# f = open("a.txt", "r")
# f.read(字节数)
# 字节数默认是文件内容长度
# 下标会自动后移e
# f.seek(2)
# content = f.read(2)
# print(f.tell())
# print(content)
# f.readline([limit])
# 读取一行数据
# limit
# 限制的最大字节数
# print("----", f.tell())
# content = f.readline()
# print(content, end="")
# print("----", f.tell())
#
#
#
# content = f.readline()
# print(content, end="")
#
#
# print("----", f.tell())
#
# content = f.readline()
# print(content, end="")
#
# print("----", f.tell())
# f.readlines()
# 会自动的将文件按换行符进行处理
# 将处理好的每一行组成一个列表返回
# content = f.readlines()
# print(content)
#
#
# f.close()
import collections
# f = open("a.txt", "r")
# print(isinstance(f, collections.Iterator))
#
# for i in f:
# print(i, end="")
#
# if f.readable():
# content = f.readlines()
# for i in content:
# print(i, end="")
# f.close()
# f = open("a.txt", "r")
#
# if f.writable():
# print(f.write("abc"))
#
#
# f.close()
f = open("a.txt", "w")
f.write("123")
f.flush()
f.close()
|
264e2c62ad8315183ea1629a01db026952c30101 | amz049/IS-Programming-samples | /IS code examples/Unit 7/koch.py | 552 | 4.21875 | 4 | import turtle
def drawFractalLine(width, height, size, level):
if level > 0:
for d in [60, -120, 60, 0]:
drawFractalLine(width, height, size / 3, level-1)
# t.forward(size / 3)
turtle.left(d)
# t.setheading(d)
else:
turtle.forward(size)
def main():
width = 200
height = 200
size = 150
level = 4
for i in range(3):
drawFractalLine(width, height, size, level)
turtle.right(120)
if __name__ == "__main__":
main()
|
cc1ca821cf31b9ae4fbd07cb73f49892f59718b7 | tarnowski-git/Python_Algoritms | /modular_inverse.py | 932 | 4.0625 | 4 | #!/usr/bin/python3
"""
Multiplicative Inverse of `a` under modulo `m`.
a * x ≡ 1 (mod m)
The value of x should be in {0, 1, 2, … m-1}
The multiplicative inverse of `a modulo m` exists
if and only if a and m are relatively prime (i.e., if gcd(a, m) = 1).
e.g
m = 7, a = 4, x = 2 4 * 2 = 8 mod 7 = 1
m = 11, a = 8, x = 7 87 = 56 mod 11 = 1
"""
import time
from extended_euclidean_algorithm import gcd_extended
def modular_inverse(a, m):
"""Based on Extended Euler’s GCD algorithm [Works when a and m are coprime]"""
gdc, x, _ = gcd_extended(a, m)
if gdc != 1:
raise Exception("Inverse doesn't exists")
else:
res = (x % m + m) % m
return res, x
if __name__ == '__main__':
# example
t0 = time.time()
a = 16
m = 29
mod_inv, x = modular_inverse(a, m)
print(f"{a} * {x} mod {m} = {mod_inv}")
t1 = time.time()
print("Time reqired: ", t1 - t0)
|
dfb8eb585181f6d4104b573d55e709878deec55f | VeriitoQD/Cursos | /HackerRank_Python/powerModpower.py | 317 | 3.765625 | 4 | def calculatepow2(x,y):
return pow(x,y)
def calculatepow3(x,y,z):
return pow(x,y,z)
if __name__=='__main__':
a=int(input())
b=int(input())
m=int(input())
if 1<=a<=10 and 1<=b<=10 and 2<=m<1000:
print(calculatepow2(a,b))
print(calculatepow3(a,b,m))
else:
exit()
|
7be835039d09d1111d93208a09dadd70db8d9f83 | actcheng/leetcode-solutions | /1261_Find_Elements_in_a_Contaminated_Binary_Tree.py | 1,377 | 3.84375 | 4 | # Problem 1261
# Date completed: 2019/11/21
# 132 ms (11%)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class FindElements:
def __init__(self, root: TreeNode):
root.val = 0
queue = [root]
self.max = 0
def setNode(node,val):
if node:
node.val = val
queue.append(node)
self.max = max(self.max,val)
while queue:
node = queue.pop(0)
setNode(node.left, 2*node.val+1)
setNode(node.right, 2*node.val+2)
self.root = root
def find(self, target: int) -> bool:
if target > self.max: return False
isLeftArr = []
while target>0:
isLeftArr.append(target%2==1)
target = (target-1)//2
node = self.root
while isLeftArr:
isLeft = isLeftArr.pop()
if (isLeft and node.left) or ((not isLeft) and node.right):
node = node.left if isLeft else node.right
else:
return False
return True
# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target)
|
4403ac491e381ec22878981173df5903ff7fcc9f | mauro-20/The_python_workbook | /chap2/ex56.py | 598 | 4.53125 | 5 | # Frequency to Name
frequency = float(input('enter a frequency(hz): '))
name = ''
if frequency < 3e9:
name = 'radio waves'
elif 3e9 <= frequency < 3e12:
name = 'microwaves'
elif 3e12 <= frequency < 4.3e14:
name = 'infrared light'
elif 4.3e14 <= frequency < 7.5e14:
name = 'visible light'
elif 7.5e14 <= frequency < 3e17:
name = 'ultraviolet light'
elif 3e17 <= frequency < 3e19:
name = 'x-rays'
elif 3e19 <= frequency:
name = 'gamma rays'
if name == '':
print('please enter a valid frequency')
else:
print('this frequency is', name)
|
2bda9e7c78630644f681f8c054597c0c2b0c587a | N-bred/100-days-of-code | /Day_029/passwordManagerGUI/main.py | 3,864 | 3.796875 | 4 | import tkinter as tk
from tkinter import messagebox
import math
from passwordGenerator import create_random_password
import pyperclip
WIDTH, HEIGHT = 200, 200
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
def generate_password():
random_password = create_random_password(n_of_digits=int(length_of_password_input.get()),
allow_uppercase=allow_uppercase.get(),
allow_symbols=allow_symbols.get(),
allow_numbers=allow_numbers.get())
password_input.delete(0, tk.END)
password_input.insert(0, random_password)
# ---------------------------- SAVE PASSWORD ------------------------------- #
def save_password():
if validate_inputs() is False:
return
website = website_input.get()
email = email_input.get()
password = password_input.get()
text = '|'.join([website, email, password])
is_ok = messagebox.askokcancel(
title=website, message=f"These are the details entered: \nEmail: {email}\nPassword: {password}.\nIs it ok to save?")
if is_ok is False:
return
with open("saved_passwords.txt", "a+") as file:
file.writelines(text + "\n")
file.close()
clear_inputs()
pyperclip.copy(password)
messagebox.showinfo(
title="Copied!", message="Password copied to the clipboard!")
def validate_inputs():
if website_input.get() == "" or email_input.get() == "" or password_input.get() == "" or int(length_of_password_input.get()) < 1:
messagebox.showerror(title="Error", message="No empty inputs allowed")
return False
return True
def clear_inputs():
website_input.delete(0, tk.END)
email_input.delete(0, tk.END)
password_input.delete(0, tk.END)
# ---------------------------- UI SETUP ------------------------------- #
window = tk.Tk()
window.title = "Password Manager"
window.config(padx=20, pady=20, bg="#ffffff")
lock_image = tk.PhotoImage(file="logo.png")
canvas = tk.Canvas(width=WIDTH, height=HEIGHT, bg="#ffffff")
canvas.create_image(math.floor(WIDTH/2),
math.floor(HEIGHT/2), image=lock_image)
canvas.grid(column=1, row=0)
# Labels
website_label = tk.Label(text="Website")
website_label.grid(column=0, row=1)
email_label = tk.Label(text="Email/Username")
email_label.grid(column=0, row=2)
password_label = tk.Label(text="Password")
password_label.grid(column=0, row=3)
length_of_password = tk.Label(text="Length of Password")
length_of_password.grid(column=0, row=4)
# Entries
website_input = tk.Entry(width=35)
website_input.grid(column=1, row=1)
website_input.focus()
email_input = tk.Entry(width=35)
email_input.grid(column=1, row=2)
email_input.insert(tk.END, "dummyemail@gmail.com")
password_input = tk.Entry(width=35)
password_input.grid(column=1, row=3)
length_of_password_input = tk.Entry(width=35)
length_of_password_input.grid(column=1, row=4)
length_of_password_input.insert(0, "10")
# Buttons
generate_password_button = tk.Button(
text="Generate Password", command=generate_password)
generate_password_button.grid(column=2, row=3)
add_password_button = tk.Button(text="Add", width=35, command=save_password)
add_password_button.grid(column=1, row=8)
# Checkboxes
allow_numbers = tk.BooleanVar()
allow_numbers_checkbox = tk.Checkbutton(
text="Allow numbers? ", variable=allow_numbers)
allow_numbers_checkbox.grid(column=1, row=5)
allow_symbols = tk.BooleanVar()
allow_symbols_checkbox = tk.Checkbutton(
text="Allow symbols? ", variable=allow_symbols)
allow_symbols_checkbox.grid(column=1, row=6)
allow_uppercase = tk.BooleanVar()
allow_uppercase_checkbox = tk.Checkbutton(
text="Allow uppercase? ", variable=allow_uppercase)
allow_uppercase_checkbox.grid(column=1, row=7)
window.mainloop()
|
b7ea0d6141067119b39163ae70e1d56f153021af | faliona6/PythonWork | /OOP/characters.py | 615 | 3.59375 | 4 | class Character:
def __init__(self, health, name):
self.health = health
self.name = name
def __str__(self):
healthInfo = " Health: " + str(self.health)
nameInfo = "Name: " + self.name
return nameInfo + healthInfo
def changeName(self, newName):
self.name = newName
def eat(self, food):
self.health = self.health + food
def attack(self, player2):
player2.health = player2.health - 10
char1 = Character(90, "Sammy")
char2 = Character(90, "Mr.Cat")
print(char1)
print(char2)
char1.eat(5)
print(char1)
char1.attack(char2)
print(char2)
|
b629beeba3e2cd27857b32e54dc5d920b9257aef | EmeraldHaze/QFTSOM | /api/node.py | 3,454 | 3.953125 | 4 | from collections import OrderedDict
from api import Abstract
class Node(Abstract):
net = False
class AbstractNode(Node):
"""An abstract node used for conversations and other logical networks"""
def __init__(self, name, links=[], does=[], exit_=False, data=None):
self.name = name
self.links = links
self.does = does
self.exit_ = exit_
self.net = False
class Place(Node):
"""A node that represents a place"""
def __init__(self, name, links, info, beings=None, items=None,
named_links=False):
if items is None:
items = []
if type(items) is not list:
items = [items]
if beings is None:
beings = []
if type(beings) is not list:
beings = [beings]
self.name = name
if named_links is False:
named_links = links
self.links = OrderedDict(zip(named_links, links))
self.info = info
self.items = items
self.beings = beings
self.parent = None
def __repr__(self):
return "<{} with {} in it>".format(
self.name,
", ".join(map(repr, self.beings + self.items))
)
def alone(self):
"""
Returns True if there's nobody in this place, the Being if
their's one, and False if there's more than one
"""
if len(self.beings) is 0:
return True
elif len(self.beings) is 1:
return self.beings[0]
else:
return False
class Net(Abstract):
net = True
def __init__(self, name, nodes, does=[], start=None):
"""
Start is the starting possision upon arival.
Nodes are a dict of all nodes in this network.
Do is node commands
"""
self.name = name
if type(nodes) is list:
node_dict = OrderedDict()
for node in nodes:
node_dict[node.name] = node
nodes = node_dict
self.nodes = nodes
for node in nodes.values():
self.addnode(node)
self.does = does
self.start = start
def addnode(self, node):
if node.net:
newnodes = OrderedDict(back=self)
#this causes the 'back' to be the 'first' node in that net
newnodes.update(node.nodes)
node.nodes = newnodes
else:
links = OrderedDict()
for name, link in node.links.items():
links[name] = self.nodes[link]
node.links = links
self.nodes[node.name] = node
class PlaceNet(Net):
"""A network of Places"""
class AbstractNet(Net):
"""A network of AbstractNodes"""
def walk(self, chooser):
"""
Walk the network until you reach a node/state marked as end, which
is returned
"""
state = self.start
if not state:
state = chooser(self.nodes)
while state:
for do in state.does:
do(state)
if state.net:
return state.walk(chooser)
else:
if state.exit_:
return state
else:
try:
state = chooser(state.links, query=state.name)
except TypeError:
#no query argument
state = chooser(state.links)
|
bfd3e0c5583b9c358205181554c731890584f714 | wagnersistemalima/Exercicios-Python-URI-Online-Judge-Problems---Contests | /Pacote Dawload/Projeto progamas Python/ex1144 Sequencia logica.py | 338 | 4 | 4 | numero = int(input())
for c in range(1, numero + 1): # EX: A sequencia é de 1 a 5, porem ela se repete
print('{} {} {}'.format(c, c**2, c**3)) # na primeira repetição o contador**2 contador**3
print('{} {} {}'.format(c, c**2 + 1, c**3 + 1)) # na segunda repetção o contador**2 +1 contador**3 +1 |
3b97456fe81956df35480e2fe58f99d651aab90a | GabrielSlima/Adivinhe-o-numero | /TakeGuess.py | 785 | 4.0625 | 4 | import random
numeroSecreto = random.randint(1,20)
print('O numero que estou pensando esta entre 1 e 20')
#Dando ao usuario 6 oportunidades
for tentativa in range (1,7):
print('Tente adivinhar:')
entrada = input()
if entrada == '':
while True:
print('Tente adivinhar')
entrada = input()
if entrada != "":
break
try:
numero = int(entrada)
except ValueError:
print("Talvez o valor inserido não seja inteiro...")
if numero < numeroSecreto:
print('Seu numero está abaixo...')
elif numero > numeroSecreto:
print('Seu numero está acima...')
else:
break
if numero == numeroSecreto:
print('Parabens!!! O numero que pensei foi: ' + str(numeroSecreto) + '.')
else:
print('Você falhou soldado. O numero que pensei foi: ' + str(numeroSecreto) + '.')
|
422767c53169505c64a05ff346991117dbd11cc4 | chibitofu/Coding-Challenges | /date_conversion.py | 451 | 4 | 4 | # Given a date formatted as 9/23/2019 convert it to 092319
# All single digit numbers should be prepended with a 0
def date_convert(date_input):
split_date = date_input.split("/")
if int(split_date[0]) < 10:
split_date[0] = "0" + split_date[0]
if int(split_date[1]) < 10:
split_date[1] = "0" + split_date[1]
split_date[2] = split_date[2][-2:]
return ''.join(split_date)
print(date_convert("9/23/2019")) |
10323b90495a7a0a649114c28464d1724ef9451e | G-itch/Projetos | /backup/Ignorância Zero-backup/Ignorância Zero/026Exercício1.py | 115 | 3.953125 | 4 | lista = []
for i in range(1,6):
n =int(input("Digite o número %i de 5:" %i))
lista.append(n)
print(lista) |
feca03fa52ff6d9977412402a6345fb6b6461829 | Zuce124/Algorithm_Learning | /test_recursion.py | 405 | 3.890625 | 4 |
def countdown(x):
if x == 0:
print(x,"...\ndone!")
return
else:
print(x,"...")
countdown(x-1)
def factorial(x):
if x == 0:
return 1
else:
return x*factorial(x-1)
def exponent(x,y):
if y == 0:
return 1
else:
return x*exponent(x,y-1)
#countdown(4)
print(factorial(4))
print(exponent(2,5)) |
1f195a45050270f4608b722356b481899767a809 | ARAV0411/HackerRank-Solutions-in-Python | /Collections Most Common Moderate Problem.py | 421 | 3.890625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import *
s= raw_input()
string= [i for i in s]
counter= Counter(string)
string= sorted(set(string))
for i in range(3):
for j in string:
if counter[j]== max(counter.values()):
print j+" "+ str(max(counter.values()))
counter.pop(j)
break
print counter
|
104b8f058ab98f16471c5c9bed4178d07b453d1b | kmckinl/PacMan_Learner | /game/cell.py | 1,598 | 3.53125 | 4 | from coin import *
class CellMap:
def __init__(self):
self.map: Cell = self.getCells()
def getCells(self):
cells: Cell = []
lineCount = 0
rowCount = 0
walls = open("db/walls.txt", "r")
for line in walls:
if lineCount == 28:
lineCount = 0
rowCount += 1
if "row" not in line:
# remove \n off end of string
line = line.strip()
row = line.split(", ")
for cell in row:
cells.append(Cell(cell, (lineCount, rowCount)))
lineCount += 1
return cells
def getCell(self, pos):
for cell in self.map:
if cell.pos == pos:
return cell
def detectCollision(self, pos):
return self.getCell(pos).hasWall
def collectCoin(self, pos):
cell = self.getCell(pos)
if cell.hasCoin:
cell.hasCoin = False
return cell.coin.score
return 0
class Cell:
def __init__(self, hasWall, pos):
self.hasWall = self.toBool(hasWall)
self.pos = pos
self.hasCoin = not self.hasWall # essentially, if no collision, spawn coin
if self.hasCoin:
self.coin = Coin()
if pos == (6, 8) or pos == (21, 8) or pos == (6, 20) or pos == (21, 20):
self.coin = SuperCoin()
@staticmethod
def toBool(s):
if s == '1':
return True
elif s == '0':
return False
else:
raise ValueError
|
08603d03adb586deba6809e06eecb634c9a91ce6 | ferranpons/ccc_pumptrack_attack | /player.py | 3,212 | 3.5 | 4 | #!/usr/bin/env python
import pygame
from pygame.rect import Rect
class Player(pygame.sprite.Sprite):
max_speed = 8
speed = 8
boost = 2
acceleration = .1
screen_rect = Rect(0, 0, 1280, 768)
lap = 0
buffer = []
max_buffer_count = 3
start_ticks = 0
time_in_seconds = 0
previous_time_in_seconds = 0
pop_time = 0.15
containers = None
images = None
def __init__(self, new_rect, way_points, loop=False):
self.screen_rect = new_rect
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = self.images[0]
self.rect = self.image.get_rect(midbottom=self.screen_rect.midbottom)
self.reloading = 0
self.origtop = self.rect.top
self.facing = -1
self.loop = loop
self.speed = 0
self.way_points = way_points
self.next_point = 0
# set current position
# I use Vector2 because it keeps position as float numbers
# and it makes calcuations easier and more precise
self.current = pygame.math.Vector2(self.way_points[0])
# set position in rect to draw it
self.rect.center = self.current
# set end point if exists on list
self.target_index = 1
if self.target_index < len(self.way_points) - 1:
self.target = pygame.math.Vector2(self.way_points[self.target_index])
self.moving = True
else:
self.target = self.current
self.moving = False
def move(self):
if self.moving:
self.speed += self.acceleration * pygame.time.get_ticks() / 100
if self.speed >= self.max_speed:
self.speed = self.max_speed
# get distance to taget
distance = self.current.distance_to(self.target)
if distance > self.speed:
self.current = self.current + (self.target - self.current).normalize() * self.speed
self.rect.center = self.current
else:
# put player in tagert place,
# and find new target on list with waypoints
self.current = self.target
self.rect.center = self.current
# set next end point if exists on list
self.target_index += 1
if self.target_index < len(self.way_points):
self.target = pygame.math.Vector2(self.way_points[self.target_index])
else:
if self.loop:
self.lap += 1
self.target_index = 0
else:
self.moving = False
def add_pump(self):
if self.buffer.__len__() <= self.max_buffer_count:
self.buffer.append(1)
def pump(self):
print(self.buffer)
self.time_in_seconds = (pygame.time.get_ticks() - self.start_ticks) / 1000
if self.time_in_seconds - self.previous_time_in_seconds > self.pop_time:
self.previous_time_in_seconds = self.time_in_seconds
if self.buffer.__len__() > 0:
self.buffer.pop()
if self.buffer.__len__() > 0:
self.move()
|
09190e727d3e75ae20f3cac3a067b2923140b030 | Aditi-Billore/leetcode_may_challenge | /Week2/straightLineCheck.py | 844 | 3.84375 | 4 | # You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point.
# Check if these points make a straight line in the XY plane.
# (x2 - x1)(y3 - y1) - (x3 - x1) (y2- y1)
import numpy as np
def main():
coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
# coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
# coordinates = [[-3,-2],[-1,-2],[2,-2],[-2,-2],[0,-2]]
# coordinates = [[-1,1],[-6,-4],[-6,2],[2,0],[-1,-2],[0,-4]]
if(len(coordinates) == 1):
print(True)
for i in range(len(coordinates)-2):
if ((coordinates[i+1][0] -coordinates[i][0])*(coordinates[i+2][1] -coordinates[i][1])) - ((coordinates[i+2][0] -coordinates[i][0])*(coordinates[i+1][1] -coordinates[i][1])):
print(False)
print(True)
if __name__ == "__main__":
main()
|
651f8268095c0440f5fce2cd46ea7900017b70e8 | yangyu823/PythonPractice | /01/hello.py | 1,715 | 3.6875 | 4 | import random
import sys
import os
print("Hello world")
'''
Mulitilineafhsdjvkhakd
'''
name='Derek'
print(name)
# Number
print("5 + 2 = ",5+2)
print("5 - 2 = ",5-2)
print("5 * 2 = ",5*2)
print("5 / 2 = ",5/2)
print("5 % 2 = ",5%2)
print("5 ** 2 = ",5**2)
print("5 // 2 = ",5//2)
# String
quote ="\" Always remember you are unique"
multi_line_quote = ''' Just
like everyone else'''
print("%s %s %s" % ('I like the quote', quote, multi_line_quote))
print('\n' * 5)
print("I dont like ", end="")
print("newlines")
# Lists
grocery_list = ['Juice' , 'Tomatoes' , 'Potatoes',
'Bananas']
print('First Item', grocery_list[0])
grocery_list[0] ="Green Juice"
print('First Item', grocery_list[0])
other_events =['Wash Car' , 'Pick Up kids', 'Cash Check']
to_do_list = [other_events,grocery_list]
print(to_do_list)
print(to_do_list[1][1])
grocery_list.append('Onions')
print(to_do_list)
grocery_list.insert(3,'bapple')
print(to_do_list)
grocery_list.remove('bapple')
grocery_list.sort()
grocery_list.reverse()
print(to_do_list)
del grocery_list[4]
print(to_do_list)
to_do_list2=other_events+grocery_list
print(to_do_list2)
print(len(to_do_list2))
print(max(to_do_list2))
print(min(to_do_list2))
# Tuples
pi_tuple = (3,1,4,1,5,9)
new_tuple = list(pi_tuple)
new_list= tuple(new_tuple)
#print(type(new_tuple))
print(len(new_tuple))
print(min(new_list))
print(max(new_tuple))
# Dictionaries
super_bike ={'ducati' : 'panigale 1299',
'kawasaki' : 'ninja H2',
'yamaha' : 'r1m',
'honda' : 'cbr1000rr',
'suzuki' : 'gsx-1000'}
print(super_bike['ducati'])
del super_bike['suzuki']
print(super_bike.keys())
print(super_bike.values()) |
fdb5341e41edb0edbead0b274920586d12ce6ad6 | LyricLy/python-snippets | /properties/recursive.py | 372 | 3.890625 | 4 | #!/usr/bin/env python3
# encoding: ascii
class Factorial:
def __init__(self, n):
if n < 0:
raise ValueError
self.n = n
@property
def value(self):
if self.n == 0:
return 1
old_n = self.n
self.n -= 1
result = (self.n+1) * self.value
self.n = old_n
return result
if __name__ == '__main__':
import sys
print(Factorial(int(sys.argv[1])).value)
|
42e3aa09879dd849113a9289bf8baaa600ac21d0 | joshwestbury/Digital_Crafts | /python_exercises/py_part3_ex/turtle_ex/shapes.py | 924 | 4.1875 | 4 | #Extract all the code for the shapes in exercise 1 into functions. Move them all into a single file called shapes.py. Write a new .py program that imports the shapes module and use its functions to draw all the available shapes onto the screen.
from turtle import *
def triangle():
for i in range (3):
forward(300)
left(120)
def square():
for i in range (4):
forward(100)
left(90)
def pentagon():
for i in range (5):
forward(70)
right(360.0 / 5)
def hexagon():
for i in range(6):
forward(70)
right(360.0 / 6)
def octogon():
for i in range(8):
forward(70)
right(360.0 / 8)
def star():
for i in range(5):
forward(100)
right(144)
def circ():
for i in range(4):
up()
forward(60)
left(40)
down()
width(5)
circle(150)
#if __name__ = "__"main__":
#mainloop()
|
74eddb734cfb7332258e72b1747ff4b93d14535c | ramona-2020/Python-OOP | /04. Inheritance/Lab_ 4. Mixin Inheritance.py | 687 | 3.53125 | 4 | import math
from statistics import mean
class CalculateAverageMixin:
def get_average(self, data):
return math.floor(mean(data))
class Student(CalculateAverageMixin):
def __init__(self, name, age, grades=[]):
self.name = name
self.age = age
self.grades = grades
class Employee(CalculateAverageMixin):
def __init__(self, name, age, daily_working_hours=[]):
self.name = name
self.age = age
self.daily_working_hours = daily_working_hours
student = Student("Maria", 20, [5,6])
teacher = Employee("Gosho", 25, [10,17])
print(student.get_average(student.grades))
print(teacher.get_average(teacher.daily_working_hours))
|
2d3caac051ebe17ce5967c1e184c839dada0b163 | Aguu21/Python | /Ejercicio6.py | 951 | 3.796875 | 4 | def mayorProducto (primero, segundo, tercero, cuarto):
'''Encuentra el mayor producto entre dos numeros, dados cuatro numeros.'''
resultado = primero * segundo
resultadosegundo = primero * tercero
resultadotercero = primero * cuarto
if (resultado > resultadosegundo):
if (resultado > resultadotercero):
total = resultado
else:
total = resultadotercero
else:
if resultadosegundo > resultadotercero:
total = resultadosegundo
else:
total = resultadotercero
resultado = segundo * tercero
resultadosegundo = segundo * cuarto
if (resultado > resultadosegundo):
if (total < resultado):
total = resultado
else:
if (total < resultadosegundo):
total = resultadosegundo
resultado = tercero * cuarto
if resultado > total:
total = resultado
return total
|
650cc67cc2d813032cb81fafc01059e27f0c09c8 | LiaoTingChun/python_turtle | /turtle_q2.py | 1,362 | 4 | 4 | # !/usr/bin/env python
# coding: utf-8
# Q2: Plot stars with user requirements via turtle
import turtle as t
import random
# 2-(1) 用戶輸入7種顏色
color_check = ['red', 'orange', 'yellow', 'green', 'blue', 'skyblue', 'purple']
color_list = []
for i in range(7):
color = input("輸入7種顏色: ")
while color not in color_check:
print("請輸入正確顏色!")
color = input("輸入7種顏色: ")
color_list.append(color)
# 2-(2) 隨機生成10個(x, y)座標
'''
coordinate = []
for i in range(10):
x, y = random.randint(-300, 300), random.randint(-300, 300)
coordinate.append(tuple([x, y]))
'''
# 2-(3) 隨機設定10個線條長度
'''
line_length = []
for i in range(10):
length = random.randint(30, 200)
line_length.append(length)
'''
# 2-(5) draw_star fuction
def draw_star(length, color):
t.pendown()
t.pencolor('black')
t.fillcolor(color)
t.begin_fill()
for i in range(5):
t.forward(length)
t.right(144)
t.end_fill()
# 2-(6)繪製10個五角星
for i in range(10):
x, y = random.randint(-300, 300), random.randint(-300, 300) #生成隨機座標
length = random.randint(30, 200) #生成隨機線條長度
color = random.choice(color_list) #隨機選擇一種顏色
t.penup()
t.goto(x, y)
draw_star(length, color)
t.done() |
2282287a82c58f48e9adf88d1ac14f15feb6abfd | guzmanchris/SnakeAI | /main.py | 2,940 | 3.828125 | 4 | import sys
from agents import *
from environment import SnakeEnvironment
def run_benchmarks(n):
result = ''
agents = [ShortestPathSnakeAgent, HamCycleSnakeAgent, HamCycleWithShortcutsSnakeAgent]
for agent in agents:
result += f'{agent.verbose_name()}\n'
result += '%s %12s %22s %27s %22s\n' % ('n', 'PM', 'total_steps', 'avg_steps_to_app', 'completed?')
for i in range(n):
agnt = agent()
SnakeEnvironment(agnt, benchmark=True).run()
avg = agnt.total_steps//agnt.apples_eaten
result += '%s %12s %22s %27s %22s\n' % (i+1, agnt.performance, agnt.total_steps, avg, agnt.completed_game)
result += '\n'
return result
if __name__ == '__main__':
print('Welcome to the Snake AI game.')
while True:
option = int(input('''
What would you like to do?
1. Run and display a single game.
2. Run a benchmark.
3. Exit program.
:'''))
if option == 1:
while True:
option2 = int(input('''
Which strategy would you like your agent to follow?
1. Choose the coordinate with the minimum distance to the apple (Use a greedy algorithm which uses
the manhattan distance as a heuristic).
2. Always follow a predetermined hamiltonian cycle.
3. Follow a hamiltonian cycle with the possibility of taking shortcuts.
:'''))
if option2 == 1:
agent = ShortestPathSnakeAgent()
elif option2 == 2:
agent = HamCycleSnakeAgent()
elif option2 == 3:
agent = HamCycleWithShortcutsSnakeAgent()
else:
print('Please enter a number between 1 and 3\n')
continue
print('Press + to increase speed or - to decrease it.')
SnakeEnvironment(agent).run()
print('Successfully completed game?', 'Yes' if agent.completed_game else 'No')
print('Its performance measure for this game was:', agent.performance)
print('The total steps the snake took were:', agent.total_steps)
print('The average steps taken to reach the apple was:', agent.total_steps//agent.apples_eaten)
print('\n')
break
elif option == 2:
n = int(input('Enter the amount of simulations you want to run per agent (Try to keep the number small): '))
print('Please wait while the process completes...')
result = run_benchmarks(n)
print(result)
original = sys.stdout
sys.stdout = open('output.txt', 'wt')
print(result)
sys.stdout = original
print('The results have been stored in the output.txt file')
elif option == 3:
exit()
else:
print('Please enter a number between 1 and 3\n')
continue
|
c0977490789fd3291fda075b9675d7a5ecb8aa54 | BingyuSong/my_practice | /sum.py | 699 | 3.75 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
carry = 0
root = n =ListNode(0)
while l1 or l2 or carry:
v1 = v2 = 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
carry, val = divmod(v1+v2+carry,10)
n.next = ListNode(val)
n = n.next
return root.next
node1 = ListNode(2)
node2 = ListNode(4)
node3 = ListNode(3)
node1.next = node2
node2.next = node3
node4 = ListNode(5)
node5 = ListNode(6)
node6 = ListNode(4)
node4.next = node5
node5.next = node6
l1 = node1
l2 = node4
s = Solution()
ans = s.addTwoNumbers(l1,l2)
print(ans.next.val)
|
150c698eaec7a88a887a3992e1e3e43e99522057 | DashaChis/second | /hw1/hangman.py | 3,099 | 3.78125 | 4 | import random
hangmans = ['''
+---+
| |
|
|
|
|
=========''','''
+---+
| |
O |
|
|
|
=========''','''
+---+
| |
O |
| |
|
|
=========''','''
+---+
| |
O |
/| |
|
|
=========''','''
+---+
| |
O |
/|\ |
|
|
=========''','''
+---+
| |
O |
/|\ |
/ |
|
=========''','''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
def first_choice():
print('выберите тему: страны(1), созвездия(2) или направления в искусстве(3)')
a = input()
if a == '1':
return 'countries'
if a == '2':
return 'constellations'
if a == '3':
return 'art_movements'
def getword(a):
with open(a + '.txt', encoding='UTF-8') as f:
words = f.read()
words = words.split()
puzzle = random.choice(words)
return puzzle
def hangman(draw, wronglet, correctlet, puzzle):
print(draw[len(wronglet)])
print()
if 1 < len(wronglet) < 5:
print('осталось', 6-len(wronglet), 'попытки')
elif len(wronglet) == 5:
print('последняя попытка!')
else:
print('осталось', 6-len(wronglet), 'попыток')
none = '_'*len(puzzle)
for i in range(len(puzzle)):
if puzzle[i] in correctlet:
none = none[:i] + puzzle[i] + none[i+1:]
for letter in none:
print(letter, end=' ')
print()
def approve(twin):
while True:
alfabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'
print('Введите букву:')
guess = input()
guess = guess.lower()
if len(guess) != 1:
print('буква ')
elif guess in twin:
print ('было уже, выберите другую букву!')
elif guess not in alfabet:
print('введите букву кириллицы')
else:
return guess
def main():
wronglet = ''
correctlet = ''
puzzle = getword(first_choice())
finish = False
while True:
hangman(hangmans, wronglet, correctlet, puzzle)
abc = approve(wronglet + correctlet)
if abc in puzzle:
print('да, такая буква есть')
correctlet = correctlet + abc
foundall = True
for i in range(len(puzzle)):
if puzzle[i] not in correctlet:
foundall = False
break
if foundall:
print('Ура! Было загадано слово "' + puzzle + '"!')
finish = True
else:
wronglet = wronglet + abc
if len(wronglet) == len(hangmans) - 1:
hangman(hangmans, wronglet, correctlet, puzzle)
print('Эх... Загаданное слово:"' + puzzle + '"')
finish = True
if __name__ == '__main__':
main()
|
61e3447944b42639d5ff4cdb4d2c6a4be8577561 | r3corp/Detect-Faces-OpenCV | /faces_from_camera.py | 1,642 | 3.84375 | 4 | # This is a demo of running face recognition on a Raspberry Pi.
# This program will print out the names of anyone it recognizes to the console.
# To run this, you need a Raspberry Pi 2 (or greater) with face_recognition and
# the picamera[array] module installed.
# You can follow this installation instructions to get your RPi set up:
# https://gist.github.com/ageitgey/1ac8dbe8572f3f533df6269dab35df65
import face_recognition
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
# Initialize some variables
face_locations = []
face_encodings = []
while True:
# print("Capturing image.")
# Grab a single frame of video from the RPi camera as a numpy array
ret, frame = cap.read()
# Find all the faces and face encodings in the current frame of video
face_locations = face_recognition.face_locations(frame)
# print("Found {} faces in image.".format(len(face_locations)))
face_encodings = face_recognition.face_encodings(frame, face_locations)
# print(face_locations )
for face in face_locations:
cv2.rectangle(frame, (face[1],face[0]), (face[3],face[2]), (0,255,0),3)
cv2.imshow('frame',frame)
# Loop over each face found in the frame to see if it's someone we know.
# for face_encoding in face_encodings:
# See if the face is a match for the known face(s)
# match = face_recognition.compare_faces([obama_face_encoding], face_encoding)
# name = "<Unknown Person>"
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# if match[0]:
# name = "Barack Obama"
#print("I see someone named {}!".format(name))
cap.release()
cv2.destroyAllWindows()
|
f27ab9504d9691ce870a1746f0aa31eb60e1eaa7 | hwanyhee/mlearn_8 | /tensorflow2/cnn_mnist.py | 2,636 | 3.59375 | 4 | import tensorflow as tf
from tensorflow import keras
#https://www.tensorflow.org/tutorials/images/cnn
class CnnMnist:
def __init__(self):
(self.train_images, self.train_labels), (self.test_images, self.test_labels) = tf.keras.datasets.mnist.load_data()
self.train_images = self.train_images.reshape((60000, 28, 28, 1))
self.test_images = self.test_images.reshape((10000, 28, 28, 1))
# 픽셀 값을 0~1 사이로 정규화합니다.
self.train_images, self.test_images = self.train_images / 255.0, self.test_images / 255.0
self.model=None
def execute(self):
#self.create_model()
#self.train_model()
#self.eval_model()
#self.save_model()
#저장된 모델을을 가지고 평가
self.eval_model_after_load_model()
def create_model(self):
self.model = tf.keras.models.Sequential()
self.model.add(keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
self.model.add(keras.layers.MaxPooling2D((2, 2)))
self.model.add(keras.layers.Conv2D(64, (3, 3), activation='relu'))
self.model.add(keras.layers.MaxPooling2D((2, 2)))
self.model.add(keras.layers.Conv2D(64, (3, 3), activation='relu'))
self.model.add(keras.layers.Flatten())
self.model.add(keras.layers.Dense(64, activation='relu'))
self.model.add(keras.layers.Dense(10, activation='softmax'))
print(self.model.summary())
self.model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
def train_model(self):
self.model.fit(self.train_images, self.train_labels, epochs=5)
def eval_model(self):
test_loss, test_acc = self.model.evaluate(self.test_images, self.test_labels, verbose=2)
print(test_loss,test_acc)
def save_model(self):
self.model.save('./saved_models/my_model.h5')
def load_model(self):
new_model = keras.models.load_model('./saved_models/my_model.h5')
new_model.summary()
return new_model
def eval_model_after_load_model(self):
new_model = self.load_model()
new_model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 복원된 모델을 평가합니다
loss, acc = new_model.evaluate(self.test_images, self.test_labels, verbose=2)
print("복원된 모델의 정확도: {:5.2f}%".format(100 * acc))
if __name__ == '__main__':
c = CnnMnist()
c.execute() |
3843350bbe966f487566fde98252d9df92196bc6 | dbkaiser/EulerKaiser | /python/42.py | 320 | 3.796875 | 4 | #!/usr/bin/python
# though this is useless
def readfile():
f=file('../test.txt');
while True:
str = f.readline();
print ord(str[len(str)-1]);
if len(str)==0 :
break;
f.close();
def isPrime(num):
for x in range (1,num/2):
if num%x==0: return False;
return True;
print(isPrime(33))
|
914145bd5ab6f6d404b83ef91ca7f1a9c3e15f75 | santakd/PyEng | /Image_Video/edge_detect.py | 505 | 3.5625 | 4 | import cv2
import sys
# The first argument is the image
image = cv2.imread(sys.argv[1])
#conver to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#blur it
blurred_image = cv2.GaussianBlur(gray_image, (7,7), 0)
cv2.imshow("Orignal Image", image)
# Use low thresholds
canny = cv2.Canny(blurred_image, 10, 30)
cv2.imshow("Canny with low thresholds", canny)
# Use high thresholds
canny2 = cv2.Canny(blurred_image, 50, 150)
cv2.imshow("Canny with high thresholds", canny2)
cv2.waitKey(0) |
3d50bfd5a4fdfe9009bf470768daf96c283036bf | chenjunyuan1996/Java-Practice | /day30/greedAlgorithm/lastStoneWeight.py | 1,250 | 3.71875 | 4 | '''
有一堆石头,每块石头的重量都是正整数。
每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:
如果 x == y,那么两块石头都会被完全粉碎;
如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/last-stone-weight
'''
import heapq
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
maxHeap = []
for stone in stones:
heapq.heappush(maxHeap, -stone)
while len(maxHeap) > 1 and maxHeap[0] != 0:
head1 = heapq.heappop(maxHeap)
head2 = heapq.heappop(maxHeap)
heapq.heappush(maxHeap, head1 - head2)
return -maxHeap[0]
# class Solution:
# def lastStoneWeight(self, stones: List[int]) -> int:
# while len(stones) > 1:
# stones.sort(reverse=True)
# stones[0] -= stones.pop(1)
# return stones[0]
|
72b2c8e75e101cd113c4a58f8754a9138bccbd6c | lizprogrammer/python_samples | /list_duplicates.py | 318 | 3.59375 | 4 | import random
a = [random.randrange(0, 3)]
count = random.randrange(0,40)
i = 1
while i < count:
a.append( random.randrange(0, 10))
i += 1
print(a)
def get_set(a_list):
my_set = set(a_list)
return my_set
my_new_set = get_set(a)
print(sorted(my_new_set))
#def defaultArg( name, msg = "Hello!"):
|
e508afae8126b676e0b83fae4394f7a24a5d8fb6 | hayesall/i427-SearchInformatics | /Assignments/assignment1/problem1.py | 533 | 3.734375 | 4 | #!/bin/python
import sys
import os
def lastLetter(word):
lastletter = word[-1:]
lasttwo = word[-2:] #not elegant, but it works.
secondtolast = lasttwo[:1]
return lastletter + " " + secondtolast
print(lastLetter("APPLE"))
#should print: E L
print(lastLetter("EMACSRULES"))
#should print: S E
print(lastLetter("ILOVEBASH"))
#should print: H S
#commenting these out because strange behavior
#f = open(os.environ['OUTPUT_PATH'], 'w')
#_word = raw_input()
#res = lastLetter(_word);
#f.write(res + "\n")
#f.close()
|
1509e944246ce5e76bdc44d81f173f89f65de1b4 | roselller/myTkinterApplication | /main.py | 8,560 | 4.3125 | 4 | # Applications using Tkinter
# 1. Import tkinter
from tkinter import *
'''------------------------ Functions --------------------------'''
# function to compute and display Multiplcation Table
def multiplication_table():
txtTable_MT.delete("1.0", END)
try:
n = int(entNumber_MT.get())
except ValueError:
txtTable_MT.insert(END, 'Invalid input')
for i in range(1,13):
row = "{:3} x {:2} = {:3}\n".format(i, n, i * n)
txtTable_MT.insert(END, row)
# function to calculate and display BMI
def calc_bmi():
txtBMI_BMI.delete("1.0", END)
try:
weight = float(entWeight_BMI.get())
height = float(entHeight_BMI.get())
except ValueError:
txtBMI_BMI.insert(END, 'Invalid input')
if height > 5:
txtBMI_BMI.insert(END, 'Invalid input')
else:
bmi = weight / (height ** 2)
txtBMI_BMI.insert(END, round(bmi,2))
# function to calculate compound interest
def calc_CMPDINT():
txtAmount_CMPDINT.delete('1.0', END)
try:
p = float(entPrincipal_CMPDINT.get())
r = float(entInt_CMPDINT.get())
n = float(entRate_CMPDINT.get())
t = float(entTimes_CMPDINT.get())
except ValueError:
txtAmount_CMPDINT.insert(END, 'Invalid input')
if r > 1:
txtAmount_CMPDINT.delete('1.0', END)
txtAmount_CMPDINT.insert(END, 'Invalid input')
else:
amount = p * ((1 + (r/n)) ** (n*t))
txtAmount_CMPDINT.insert(END, round(amount,2))
# function to use caesar cipher (substitution cipher)
def caesar_cipher_SCCC():
txtCipher_SCCC.delete('1.0', END)
try:
plaintext = str(entPlain_SCCC.get()).upper()
pos_shift = int(entShift_SCCC.get())
except ValueError:
txtCipher_SCCC.insert(END, 'Invalid input')
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ciphertext = ''
mistake = False
for letter in plaintext:
if letter not in alphabet:
mistake = True
else:
key = ((alphabet.find(letter)) + pos_shift) % 26
letter = alphabet[key]
ciphertext += letter
if mistake == True:
txtCipher_SCCC.insert(END, 'Invalid input')
else:
txtCipher_SCCC.insert(END, ciphertext)
# function to show a frame
def raise_frame(frame):
frame.tkraise()
''' ------------------------------------------------------------ '''
''' Main Window '''
# Create main window
window = Tk()
window.title('Function Applications')
window.iconbitmap('c:/Personal Projects/Python/GUI Project/python.ico')
window.geometry('800x400')
''' ----------- '''
''' Frame 1 : Multiplcation Table '''
frame1 = Frame(window, bg='light yellow', width=500, height=300)
# Add widgets
lblTitle_MT = Label(frame1, text="Multiplcation Table", bg="light yellow", font=('Lucida Calligraphy', 12))
lblNumber_MT = Label(frame1, text="Enter number", width=10)
entNumber_MT = Entry(frame1, width=29)
btnDisplay_MT = Button(frame1, text="Display table", width=10, command=multiplication_table)
txtTable_MT = Text(frame1, fg='blue', width=22, height=12)
# Organize (lay out) the widgets using place() manager
lblTitle_MT.place(x=20, y=10)
lblNumber_MT.place(x=20, y=50)
btnDisplay_MT.place(x=20, y=90)
entNumber_MT.place(x=120, y=50)
txtTable_MT.place(x=120, y=90)
''' ------------------------------ '''
''' Frame 2 : BMI Calculator '''
frame2 = Frame(window, bg='light blue', width=500, height=300)
# Add widgets
lblTitle_BMI = Label(frame2, text="BMI Calculator", bg="light blue", font=('Lucida Calligraphy', 12))
lblWeight_BMI = Label(frame2, text="Weight (kg)", width=12)
lblHeight_BMI = Label(frame2, text="Height (m)", width=12)
entWeight_BMI = Entry(frame2, width=20)
entHeight_BMI = Entry(frame2, width=20)
lblBMI_BMI = Label(frame2, text="BMI", width=12)
txtBMI_BMI = Text(frame2, width=15, height=1, fg="blue")
btnCalculate_BMI = Button(frame2, text="Calculate", width=10, command=calc_bmi)
# Organize (lay out) the widgets using place() manager
lblTitle_BMI.place(x=20, y=10)
lblWeight_BMI.place(x=20, y=50)
lblHeight_BMI.place(x=20, y=90)
lblBMI_BMI.place(x=20, y=130)
entWeight_BMI.place(x=120, y=50)
entHeight_BMI.place(x=120, y=90)
txtBMI_BMI.place(x=120, y=130)
btnCalculate_BMI.place(x=260, y=130)
''' ------------------------- '''
''' Frame 3 : Compound Interest Calculator '''
frame3 = Frame(window, bg='light green', width=500, height=300)
# Add widgets
lblTitle_CMPDINT = Label(frame3, text='Compound Interest Calculator', bg='light green', font=('Lucida Calligraphy', 12))
lblPrincipal_CMPDINT = Label(frame3, text='Principal Amount ($)', width=30)
lblInt_CMPDINT = Label(frame3, text='Annual Interest Rate (decimal)', width=30)
lblRate_CMPDINT = Label(frame3, text='Number of times compounded per year', width=30)
lblTimes_CMPDINT = Label(frame3, text='Number of years to be compounded', width=30)
lblAmount_CMPDINT = Label(frame3, text='Final amount ($)', width=30)
entPrincipal_CMPDINT = Entry(frame3, width=20)
entInt_CMPDINT = Entry(frame3, width=20)
entRate_CMPDINT = Entry(frame3, width=20)
entTimes_CMPDINT = Entry(frame3, width=20)
txtAmount_CMPDINT = Text(frame3, width=15, height=1, fg='blue')
btnCalculate_CMPDINT = Button(frame3, text='Calculate', width=10, command=calc_CMPDINT)
# Organize (lay out) the widgets using place() manager
lblTitle_CMPDINT.place(x=20, y=10)
lblPrincipal_CMPDINT.place(x=20, y=50)
lblInt_CMPDINT.place(x=20, y=90)
lblRate_CMPDINT.place(x=20, y=130)
lblTimes_CMPDINT.place(x=20, y=170)
lblAmount_CMPDINT.place(x=20, y=210)
entPrincipal_CMPDINT.place(x=250, y=50)
entInt_CMPDINT.place(x=250, y=90)
entRate_CMPDINT.place(x=250, y=130)
entTimes_CMPDINT.place(x=250, y=170)
txtAmount_CMPDINT.place(x=250, y=210)
btnCalculate_CMPDINT.place(x=390, y=210)
''' -------------------------------------- '''
''' Frame 4 : Caesar Cipher '''
frame4 = Frame(window, bg='pale violet red', width=500, height=300)
# Add widgets
lblTitle_SCCC = Label(frame4, text='Caesar Cipher', bg='pale violet red', font=('Lucida Calligraphy', 12))
lblPlain_SCCC = Label(frame4, text='Plaintext', width=25)
lblShift_SCCC = Label(frame4, text='Number of positions to shift', width=25)
entPlain_SCCC = Entry(frame4, width=20)
entShift_SCCC = Entry(frame4, width=20)
txtCipher_SCCC = Text(frame4, width=15, height=1, fg='blue')
btnDisplay_SCCC = Button(frame4, text='Display Ciphertext', width=25, command=caesar_cipher_SCCC)
# Organize (lay out) the widgets using place() manager
lblTitle_SCCC.place(x=20, y=10)
lblPlain_SCCC.place(x=20, y=50)
lblShift_SCCC.place(x=20, y=90)
entPlain_SCCC.place(x=220, y=50)
entShift_SCCC.place(x=220, y=90)
txtCipher_SCCC.place(x=220, y=130)
btnDisplay_SCCC.place(x=20, y=130)
''' ---------------------- '''
''' Main window '''
# Menu framing
frmMenu = Frame(window, bg='light grey', width=300, height=300)
lblMenu = Label(frmMenu, text='Main Menu', width=9, fg='blue', bg='light grey', font=('Lucida Calligraphy', 12))
lblMenu.place(x=20, y=10)
frameMenu = Frame(window, bg='grey', width=500, height=300)
lblMenu1 = Label(frameMenu, text='Welcome! Click on a function to get started.', width=30, bg='light grey', font=('Lucida Calligraphy', 12))
lblMenu1.place(x=70, y=20)
creatorLabel = Label(window, text='Created by Roseller Armirola', width=32, bg='light grey', fg='black')
creatorLabel.place(x=20, y=300)
versionLabel = Label(window, text='v2.0', width=10, fg='black') # Change after every update
versionLabel.place(x=700, y=325)
# Menu navigation buttons
btn1 = Button(frmMenu, text='Multiplcation Table', width=25, fg='blue', command=lambda:raise_frame(frame1))
btn1.place(x=20, y=50)
btn2 = Button(frmMenu, text='BMI Calculator', width=25, fg='blue', command=lambda:raise_frame(frame2))
btn2.place(x=20, y=90)
btn3 = Button(frmMenu, text='Compound Interest Calculator', width=25, fg='blue', command=lambda:raise_frame(frame3))
btn3.place(x=20, y=130)
btn4 = Button(frmMenu, text='Caesar Cipher', width=25, fg='blue', command=lambda:raise_frame(frame4))
btn4.place(x=20, y=170)
# Menu layout
frmMenu.place(x=20, y=20)
frameMenu.place(x=250, y=20)
frame1.place(x=250, y=20)
frame2.place(x=250, y=20)
frame3.place(x=250, y=20)
frame4.place(x=250, y=20)
raise_frame(frameMenu)
''' ----------- '''
window.mainloop()
''' Future Changelogs (notes)
- Import functions from week 4 weekly exercises
''' |
b9367f2ad890b6548fe6043d92642b17292c0261 | AnthonyRChao/Scripts-and-Implementations | /test.py | 208 | 3.75 | 4 | # x = 1
# y = x
# x = x + 1
# print(x)
# print(y)
# x = [1, 2, 3]
# y = x
# x[0] = 4
# print(x)
# print(y)
x = ['foo', [1, 2, 3], 10.4]
y = list(x) # or x[:]
y[0] = 'foooooo'
y[1][0] = 4
print(x)
print(y)
|
a1b453399083ed740c5b64daf400388bcf559685 | laucavv/holbertonschool-machine_learning | /math/0x02-calculus/10-matisse.py | 462 | 4.15625 | 4 | #!/usr/bin/env python3
""" calculates the derivative of a polynomial """
def poly_derivative(poly):
""" calculates the derivative of a polynomial """
if type(poly) is list and len(poly) > 0:
if len(poly) == 1:
return [0]
derivative = [0 for a in range(len(poly) - 1)]
for d in range(1, (len(derivative) + 1)):
derivative[d - 1] = poly[d] * d
return derivative
else:
return None
|
6f9c705a3f0b9ea47b6ab0cd4c7a51909e3e8f1f | kamaliselvarajk/aspire | /Python/30-Jun-2021(if,while&functions)/for_shell.py | 1,108 | 3.71875 | 4 | a=[[1,2,3], ['Kamali', 'Dharshu', 'Papu'], 'Aspire']
for i in a:
print(i, len(i))
print('------------------------------------------')
sum = 0
for i in range(11):
sum = sum + i
print('Sum of first 10 numbers is: ', sum)
print('------------------------------------------')
sum = 0
for i in range(11):
if(i%2 == 0):
sum = sum + i
print('Sum of first 5 even numbers is ',sum)
print('------------------------------------------')
for i in range(11):
for j in range(2):
sum = sum + i + j
print(sum)
print('------------------------------------------')
s = ['Python', 'PHP', 'Java', 'HTML', 'CSS', 'JS', 'MySql']
for i in range(len(s)):
print(i, s[i], len(s[i]))
print('------------------------------------------')
for i in range(2,10):
for j in range(2,i):
if(i%j == 0):
print(i, 'not a prime number')
break
else:
print(i, 'is prime number')
print('-------------------------------------------')
for i in range(1,10):
if(i%2 == 0):
continue
else:
print(i)
print('-------------------------------------------')
|
0317be7f56d8112fbd94290c56369947035baecb | PythonZero/sklearn-dataschool | /06_linear_regression.py | 1,693 | 3.609375 | 4 | import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
def print_linear_regression_formula(model):
print(
f"y =",
" + ".join(
[f"({m:.3f} * {col})" for col, m in zip(feature_cols, linreg.coef_)]
),
f"+ {model.intercept_: .3f}",
)
def calculate_errors(true, pred):
mae = metrics.mean_absolute_error(true, pred)
mse = metrics.mean_squared_error(true, pred)
root_mse = np.sqrt(metrics.mean_squared_error(true, pred))
print(f"{mae=: .2f} {mse=: .2f} {root_mse=: .3f}")
if __name__ == "__main__":
df = pd.read_csv("advertising.csv", index_col=0)
feature_cols = ["TV", "Radio", "Newspaper"]
X = df[feature_cols]
y = df["Sales"]
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
# Linear Regression: y = m1x1 + m2x2+ ... + c (y = B1x1 + ... + B0)
# e.g. y = (TV * m1) + (Radio * m2) + (Newspaper * m3) + c
# where m1 (or B1) is the model coefficients (which are learnt from least squares)
linreg = LinearRegression() # Learn the coefficients
linreg.fit(X_train, y_train)
calculate_errors(y_test, linreg.predict(X_test))
# This tells us that for each $1000 increase in spend TV unit, we get 47 more sales (0.047 * TV)
print_linear_regression_formula(linreg)
# Testing different features (no Newspaper) -> smaller error -> Newspaper is not a good indicator
linreg_2features = linreg.fit(X_train[["TV", "Radio"]], y_train)
calculate_errors(y_test, linreg_2features.predict(X_test[["TV", "Radio"]]))
|
6e83533281dad63146b92dbc8a7e43f7841b225e | AltenArcade/ArcadeProject | /Emulator/Games/Tetris/Figure.py | 4,297 | 3.515625 | 4 | import pygame
from Games.Tetris.Block import Block
from random import randint
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
PINK = (255, 0, 142)
PURPLE = (182, 0, 251)
YELLOW = (251, 247, 5)
class Figure(pygame.sprite.Sprite):
def __init__(self, struct, width, height, block, prediction):
super().__init__()
self.board_width = width
self.board_height = height
self.block_size = block
self.color_list = [GREEN, RED, PURPLE, YELLOW, PINK]
self.matrix = struct
self.block_list = pygame.sprite.Group()
self.is_moving = True
self.SetBlocklist(prediction)
def AddPos(self, fig):
old_x = []
i = 0
for block in fig.block_list:
old_x.append(block.rect.x)
for block in self.block_list:
block.rect.x = old_x[i]
i += 1
def SetBlocklist(self, prediction):
if prediction:
fig_w = len(self.matrix[0]) * self.block_size
fig_h = len(self.matrix) * self.block_size
for i in range(len(self.matrix)):
for j in range(len(self.matrix[0])):
if self.matrix[i][j] != 0:
block = Block(self.block_size, color=self.color_list[randint(0, len(self.color_list)-1)])
block.rect.x = j * self.block_size + (self.board_width - fig_w) / 2
block.rect.y = i * self.block_size + (self.board_height - fig_h) / 2
self.block_list.add(block)
else:
for i in range(len(self.matrix)):
for j in range(len(self.matrix[0])):
if self.matrix[i][j] != 0:
block = Block(self.block_size, color=self.color_list[randint(0, len(self.color_list)-1)])
block.rect.x = j * self.block_size + self.board_width / 2
block.rect.y = i * self.block_size
self.block_list.add(block)
def GetShape(self):
return self.matrix
def CorrectSide(self):
for block in self.block_list.sprites():
if block.rect.x + self.block_size > self.board_width:
self.block_list.update("left")
if block.rect.x < 0:
self.block_list.update("right")
def IsMoving(self):
return self.is_moving
def CheckCollision(self, collision_list, case):
self.block_list.update(case)
if len(pygame.sprite.groupcollide(self.block_list, collision_list, False, False)) > 0:
self.block_list.update("reset " + case)
if case == "down":
self.is_moving = False
return False
else:
self.block_list.update("reset " + case)
return True
def CheckBottom(self):
for block in self.block_list.sprites():
if block.rect.y + self.block_size >= self.board_height:
self.is_moving = False
return False
return True
def flip(self):
old_y = self.block_list.sprites()[0].rect.y
old_x = self.block_list.sprites()[0].rect.x
self.block_list = pygame.sprite.Group()
self.matrix = [list(a) for a in zip(*self.matrix[::-1])]
for i in range(len(self.matrix)):
for j in range(len(self.matrix[0])):
if self.matrix[i][j] != 0:
block = Block(self.block_size, color=self.color_list[randint(0, len(self.color_list)-1)])
block.rect.x = j * self.block_size + old_x
block.rect.y = i * self.block_size + old_y
self.block_list.add(block)
def move_down(self):
self.block_list.update("down")
def move_left(self):
move = True
for block in self.block_list.sprites():
if block.rect.x <= 0:
move = False
break
if move:
self.block_list.update("left")
def move_right(self):
move = True
for block in self.block_list.sprites():
if block.rect.x + self.block_size >= self.board_width:
move = False
break
if move:
self.block_list.update("right") |
964c04bc27edee7dd4587fdf1a55f7d9d6eea319 | JiahengHu/Turtle-Run | /Turtle.py | 7,155 | 3.84375 | 4 | # Liwei Jiang, Yin Li, Kebing Li
# CS269 JP17
# Computer Game Design
# Turtle.py
# Jan. 15th 2017
import pygame
class Turtle:
'''the class of turtle'''
def __init__(self, screen, position = (0,0), color = 0, scale = 1, grid = -1):
self.screen = screen
self.position = position
self.color = color
self.image = None
self.imagePile = None
self.imageFlip = None
self.imagePhoto = None
self.scale = scale
self.immune = False
self.grid = grid
self.trap = False
self.trapTurn = None
self.setImage()
def setImage(self):
if self.color == 0:
self.image = pygame.image.load( "turtle1.png" )
self.image = pygame.transform.scale(self.image, (int(self.image.get_size()[0] * self.scale), int(self.image.get_size()[1] * self.scale)) )
self.imagePile = pygame.image.load( "pile1.png" )
self.imagePile = pygame.transform.scale(self.imagePile, (int(self.imagePile.get_size()[0] * self.scale), int(self.imagePile.get_size()[1] * self.scale)) )
self.imageFlip = pygame.image.load( "flip1.png" )
self.imageFlip = pygame.transform.scale(self.imageFlip, (int(self.imageFlip.get_size()[0] * self.scale), int(self.imageFlip.get_size()[1] * self.scale)) )
self.imagePhoto = pygame.image.load( "photo1.png" )
self.imagePhoto = pygame.transform.scale(self.imagePhoto, (int(self.imagePhoto.get_size()[0] * self.scale), int(self.imagePhoto.get_size()[1] * self.scale)) )
if self.color == 1:
self.image = pygame.image.load( "turtle2.png" )
self.image = pygame.transform.scale(self.image, (int(self.image.get_size()[0] * self.scale), int(self.image.get_size()[1] * self.scale)) )
self.imagePile = pygame.image.load( "pile2.png" )
self.imagePile = pygame.transform.scale(self.imagePile, (int(self.imagePile.get_size()[0] * self.scale), int(self.imagePile.get_size()[1] * self.scale)) )
self.imageFlip = pygame.image.load( "flip2.png" )
self.imageFlip = pygame.transform.scale(self.imageFlip, (int(self.imageFlip.get_size()[0] * self.scale), int(self.imageFlip.get_size()[1] * self.scale)) )
self.imagePhoto = pygame.image.load( "photo2.png" )
self.imagePhoto = pygame.transform.scale(self.imagePhoto, (int(self.imagePhoto.get_size()[0] * self.scale), int(self.imagePhoto.get_size()[1] * self.scale)) )
if self.color == 2:
self.image = pygame.image.load( "turtle3.png" )
self.image = pygame.transform.scale(self.image, (int(self.image.get_size()[0] * self.scale), int(self.image.get_size()[1] * self.scale)) )
self.imagePile = pygame.image.load( "pile3.png" )
self.imagePile = pygame.transform.scale(self.imagePile, (int(self.imagePile.get_size()[0] * self.scale), int(self.imagePile.get_size()[1] * self.scale)) )
self.imageFlip = pygame.image.load( "flip3.png" )
self.imageFlip = pygame.transform.scale(self.imageFlip, (int(self.imageFlip.get_size()[0] * self.scale), int(self.imageFlip.get_size()[1] * self.scale)) )
self.imagePhoto = pygame.image.load( "photo3.png" )
self.imagePhoto = pygame.transform.scale(self.imagePhoto, (int(self.imagePhoto.get_size()[0] * self.scale), int(self.imagePhoto.get_size()[1] * self.scale)) )
if self.color == 3:
self.image = pygame.image.load( "turtle4.png" )
self.image = pygame.transform.scale(self.image, (int(self.image.get_size()[0] * self.scale), int(self.image.get_size()[1] * self.scale)) )
self.imagePile = pygame.image.load( "pile4.png" )
self.imagePile = pygame.transform.scale(self.imagePile, (int(self.imagePile.get_size()[0] * self.scale), int(self.imagePile.get_size()[1] * self.scale)) )
self.imageFlip = pygame.image.load( "flip4.png" )
self.imageFlip = pygame.transform.scale(self.imageFlip, (int(self.imageFlip.get_size()[0] * self.scale), int(self.imageFlip.get_size()[1] * self.scale)) )
self.imagePhoto = pygame.image.load( "photo4.png" )
self.imagePhoto = pygame.transform.scale(self.imagePhoto, (int(self.imagePhoto.get_size()[0] * self.scale), int(self.imagePhoto.get_size()[1] * self.scale)) )
if self.color == 4:
self.image = pygame.image.load( "turtle5.png" )
self.image = pygame.transform.scale(self.image, (int(self.image.get_size()[0] * self.scale), int(self.image.get_size()[1] * self.scale)) )
self.imagePile = pygame.image.load( "pile5.png" )
self.imagePile = pygame.transform.scale(self.imagePile, (int(self.imagePile.get_size()[0] * self.scale), int(self.imagePile.get_size()[1] * self.scale)) )
self.imageFlip = pygame.image.load( "flip5.png" )
self.imageFlip = pygame.transform.scale(self.imageFlip, (int(self.imageFlip.get_size()[0] * self.scale), int(self.imageFlip.get_size()[1] * self.scale)) )
self.imagePhoto = pygame.image.load( "photo5.png" )
self.imagePhoto = pygame.transform.scale(self.imagePhoto, (int(self.imagePhoto.get_size()[0] * self.scale), int(self.imagePhoto.get_size()[1] * self.scale)) )
def setTrapTurn(self, turn):
self.trapTurn = turn
def getTrapTurn(self):
return self.trapTurn
def getImage(self):
return self.image
def getImagePile(self):
return self.imagePile
def getImageFlip(self):
return self.imageFlip
def getImagePhoto(self):
return self.imagePhoto
def getTrap(self):
return self.trap
def setTrap(self, trap):
self.trap = trap
def setColor(self, color):
self.color = color
def getColor(self):
return self.color
def setPosition(self, position):
self.position = position
def getPosition(self):
return self.position
def setGrid(self, grid):
self.grid = grid
def getGrid(self):
return self.grid
def setImmune(self,newImmune):
self.immune = newImmune
def getImmune(self):
return self.immune
def draw(self, position):
self.screen.blit( self.image, position )
def drawPile(self, position):
self.screen.blit( self.imagePile, position)
def drawFlip(self, position):
self.screen.blit( self.imageFlip, position )
def drawPhoto(self, position):
self.screen.blit( self.imagePhoto, position )
def ifSelected(self, mouse):
range = self.getDimension()
if range[0] < mouse[0] < range[1] and range[2] < mouse[1] < range[3]:
return True
else:
return False
def getDimension(self):
width = self.image.get_size()[0]
height = self.image.get_size()[1]
lowX = self.position[0]
highX = self.position[0] + int(width)
lowY = self.position[1]
highY = self.position[1] + int(height)
return [lowX, highX, lowY, highY, width, height]
|
492f53608a989edf505c149ba04bf3a99e022e2b | adk7/cs-review | /quick_sort.py | 943 | 3.71875 | 4 | def quick_sort(items):
return quick_sort_(items, 0, len(items) - 1)
def quick_sort_(items, low, high):
if(low < high):
p = partition(items, low, high)
quick_sort_(items, low, p - 1)
quick_sort_(items, p + 1, high)
def get_pivot(A, low, hi):
mid = (hi + low) // 2
s = sorted([A[low], A[mid], A[hi]])
if s[1] == A[low]:
return low
elif s[1] == A[mid]:
return mid
return hi
def partition(items, low, high):
pivot_index = get_pivot(items,low,high)
pivot_value = items[pivot_index]
items[pivot_index], items[low] = items[low], items[pivot_index]
border = low
for i in range(low, high+1):
if items[i] < pivot_value:
border += 1
items[i], items[border] = items[border], items[i]
print(items)
items[low], items[border] = items[border], items[low]
return(border)
|
edc6fa200bd33992ddb127cee544891480797c24 | cbrianhill/adventofcode | /2021/day4.py | 2,656 | 3.515625 | 4 | import re
def make_board(lines, start):
grid = []
for i in range(0, 5):
gridline = []
fileline = re.split(r'\s+', lines[start+i].strip())
for j in range(0, 5):
gridline.append(int(fileline[j]))
grid.append(gridline)
return grid
def print_board(board):
template = "{0:2} {1:2} {2:2} {3:2} {4:2}"
for line in board:
print(template.format(*line))
def mark_board(board, mark, num):
for row in range(0, 5):
for col in range(0, 5):
if board[row][col] == num:
mark[row][col] = 1
def check_marks(mark):
for row in range(0, 5):
matches = 0
for col in range(0, 5):
if mark[row][col] == 1:
matches += 1
if matches == 5:
return True
for col in range(0, 5):
matches = 0
for row in range(0, 5):
if mark[row][col] == 1:
matches += 1
if matches == 5:
return True
return False
def calc_score(board, mark, num):
base_score = 0
for row in range(0, 5):
for col in range(0, 5):
if mark[row][col] == 0:
base_score += board[row][col]
return base_score * num
with open('input/day4.txt') as file:
lines = file.readlines()
numbers_selected = [int(x) for x in lines[0].strip().split(',')]
boards = []
marks = []
starting_line = 2
while starting_line < len(lines):
boards.append(make_board(lines, starting_line))
marks.append([[0 for col in range(0, 5)] for row in range(0, 5)])
starting_line += 6
print(f'Numbers = {numbers_selected}')
for b in range(0, len(boards)):
print(f'Board {b}:')
print_board(boards[b])
print('')
winners = 0
winning_boards = []
winning_numbers = []
for n in range(0, len(numbers_selected)):
number = numbers_selected[n]
print(f'\n*** Number {number}')
for b in range(0, len(boards)):
if b in winning_boards:
continue
mark_board(boards[b], marks[b], number)
if check_marks(marks[b]):
print(f'Board {b} has won. Score = {calc_score(boards[b], marks[b], number)}')
winners += 1
winning_boards.append(b)
winning_numbers.append(number)
if len(winning_boards) == len(boards) or n == len(numbers_selected) - 1:
break
last_winner = winning_boards[-1]
print(f'Last winning board = {last_winner} with a score of {calc_score(boards[last_winner], marks[last_winner],winning_numbers[-1])}')
|
bab811386c28977e798fa08ef503e767699d9e61 | LiRamos/Kpop-Listening | /kpop_mood.py | 2,275 | 4.375 | 4 | user_sad = input("Are you sad? Please type 'yes' or 'no'.\n")
food_sadness = input("Are you sad because you are hungry? Please type 'yes' or 'no'.\n")
current_project = input("Do you have a project you should be doing for school Please type 'yes' or 'no'.\n")
work_rough = input("Was today a rough day at work for you? Please type 'yes' or 'no'.\n")
music_mixing = input("Do you feel like mixing today? Please type 'yes' or 'no'.\n")
print("So, should you watch a KPop video?\n")
if current_project == 'yes':
print("Work on your project.\n")
elif user_sad == 'yes' and food_sadness == 'yes':
print("You're hungry. Get some food.\n")
elif user_sad == 'yes' and food_sadness == 'no':
print("OK, go watch a KPop video\n")
elif user_sad == 'yes' and (work_rough == 'yes' and music_mixing == 'no'):
print("Yes, go watch some KPop to cheer you up\n")
elif user_sad == 'yes' and (current_project == 'yes' or food_sadness =='yes'):
print("If you're hungry, go eat food first, if you have work to do, you can only watch one KPop video, then work on your project.\n")
elif current_project == 'yes' and user_sad == 'yes':
print("Watch one video, then work on your project\n")
elif user_sad == 'yes' and (work_rough == 'yes' and music_mixing == 'yes'):
print("Try mixing some music then, it will probably cheer you up more.\n")
else:
print("You may watch a KPop video\n")
def kpop_music(): #Defining Python function
mood = input("What is your mood?\nPlease type 'happy' , 'sad', or 'tired'\nSong choices according to your mood will be displayed.\n") #User picks their mood out of the options given.
mood_music = {
"happy" : "'Wolf' by EXO, 'Running to You' by SVT, 'Go Go' by BTS, 'Into The New World' by SNSD",
"sad" : "'Don't Wanna Cry Acoustic Version' by SVT, 'Spring Day' by BTS, 'Breathe' by Lee Hi",
"tired" : " 'CLAP' by SVT, 'Mic Drop' by BTS,'Rising Sun' TVXQ"
}#Dictionary holding recommendations of kpop music based on mood.
if mood == "happy":
print (mood_music.get("happy", None)) #Gets the values of whichever key that the user types in
if mood == "sad":
print( mood_music.get("sad", None))
if mood == "tired":
print(mood_music.get("tired", None))
kpop_music()
|
27e569cf7783e836dc70c6f661945c94db0eb201 | MajetyPrashanth/My-Coding-Practice | /Stack.py | 670 | 3.75 | 4 | # class A(object):
# def __init__(self,ID,name):
# self.ID = ID
# self.name = name
# def display(self):
# return self.ID, self.name
# a = A(1,"Ram")
# print(a.display())
class Stack:
def __init__(self):
self.stack = []
pass
def push(self,item):
self.stack.append(item)
pass
def display(self):
print(self.stack)
pass
def pop(self):
print(self.stack.pop())
pass
if __name__ == "__main__":
stack = Stack()
stack.display()
stack.push(1)
stack.push(10)
stack.push(10)
stack.push(10)
stack.display()
stack.pop()
stack.display()
|
c803db11e4b3394db04feeac7d01ffee61507cfb | tatsuya999/Gakky_classwork | /Gakky.py | 379 | 3.71875 | 4 | n=input('正の整数を入力してください:')
x=int(n)
while x<=0:
n=input('正の整数を入力してください:')
x=int(n)
divisor=""
count = 0
for i in range(1,x+1):
if x%i==0:
divisor = divisor + " " + str(i)
count += 1
else:
pass
print(x,'の約数は',divisor,'です。')
print('全部で', count,'個あります') |
d84a9d909e5523a765467ca4c4eb0c34f76503ba | HeathLoganCampbell/UoA-CS-320 | /AssignmentOne/gen.py | 559 | 3.890625 | 4 | '''
THIS PROGRAM WILL GENERATE A RANDOM INPUT FOR
THE QUESTION OF ASSIGNMENT ONE.
YOU CAN RUN THE FILE WITH, WHICH WILL OUTPUT
THE FILE TO ./test/sample-answer.txt
RUN: Python ./gen.py > ./test/sample-answer.txt
Height Width
(0,0) (0,1) (0,2) .. (0, width)
(1,0) (1,1) (1,2) .. (1, width)
...
(height,0) (height,1) (height,2) .. (height, width)
'''
import random
height = 400
width = 400
for y in range(height):
line = []
for x in range(width):
line.append(str(random.randint(1,101)))
print(str(height), ' ', str(width))
print(' '.join(line)) |
17e89673f56b7ae9b42144458d1c888e88ed4a8d | 316112840/Programacion | /Tareas/Tarea07/Ejercicio1.py | 652 | 3.84375 | 4 | # -*- coding: utf-8 -*-
# Mariana Yasmin Martinez Garcia
# Correo: mariana_yasmin@ciencias.unam.mx
# Ejercicio 7.1: Practica con sets
def InterseccionConjuntos(lista):
a = lista[0]
for i in range( len(lista) ):
a = a.intersection( lista[i] )
return a
# PRUEBAS:
a = set()
b = set()
c = set()
d = set()
for i in range(10):
a.add(i)
for i in range(8):
b.add(i*2)
for i in range(15):
if i%2 != 0:
c.add(i)
for i in range(2,10):
d.add(i)
print(a, "\n", b, "\n", c , "\n", d, "\n" )
e = InterseccionConjuntos([ a, b, c, d ])
print( e, "\n" )
f = InterseccionConjuntos([ a, b, d])
print( f, "\n" )
|
1fb9cf4c005151481a074914c75dda6ad105a63c | vineetpathak/Python-Project2 | /initialize.py | 683 | 4.1875 | 4 | # -*- coding: UTF-8 -*-
# Program to initialize linked list
import linked_list as ll
# Initialize the following linked listaz
# 4 -> 5 -> 13 -> 6 -> 9 -> 41 -> 8 -> 27 -> 33
def initialize_linked_list():
lList = ll.LinkedList()
lList.insert(4)
lList.insert(5)
lList.insert(13)
lList.insert(6)
lList.insert(9)
lList.insert(41)
lList.insert(8)
lList.insert(4)
lList.insert(33)
lList.print_list()
return lList
# Initialize a linked list by taking elements from an array
def initialize_linked_list_by_array(elements):
lList = ll.LinkedList()
for element in elements:
lList.insert(element)
lList.print_list()
return lList.head
|
244f628540c82cf24245d1859103243ef4bd57d8 | Ligthert/4xMUD | /old/login.py | 505 | 3.65625 | 4 | #!/usr/bin/python
from getpass import getpass
user_id = 0
print "Login with your username and password. If you are new and wish to create a new account. Login with user 'create'";
while user_id == 0:
username = raw_input("Username:")
if username == "create":
print "Fun!\n"
user_id = 1
password = "*****"
else:
#password = raw_input("Password:")
password = getpass("Password:")
user_id = 2
print username,"/",password,"\n"
# print "Hello", name
# raw_input("Press any key to exit.")
|
fbb3974dd83f0882f27e0098e50d27b50f987392 | luismasuelli/mistra | /mistra/core/intervals.py | 3,553 | 3.84375 | 4 | from enum import IntEnum
class Interval(IntEnum):
"""
These values can be used as intervals for source (original data) or digested data.
They can also constrain/truncate a timestamp to be relevant for the interval being considered.
"""
SECOND = 1
MINUTE = 60*SECOND
MINUTE5 = 5*MINUTE
MINUTE10 = 10*MINUTE
MINUTE15 = 15*MINUTE
MINUTE20 = 20*MINUTE
MINUTE30 = 30*MINUTE
HOUR = 60*MINUTE
HOUR2 = 2*HOUR
HOUR3 = 3*HOUR
HOUR4 = 4*HOUR
HOUR6 = 6*HOUR
HOUR8 = 8*HOUR
HOUR12 = 12*HOUR
DAY = 24*HOUR
def allowed_as_source(self):
"""
Tells whether this interval can be used in a source frame.
"""
return self != Interval.DAY
def allowed_as_digest(self, for_source_interval=SECOND):
"""
Tells whether this interval can be used in a digest frame given a related source frame size.
Aside from being allowed, this interval size must be GREATER than the given, optional, one.
:param for_source_interval: The source frame size to compare.
"""
iself = int(self)
ifor = int(for_source_interval)
return iself % ifor == 0 and iself > ifor
def round(self, stamp):
"""
Rounds a timestamp down to the relevant interval. E.g. the MINUTE interval will round down,
removing the seconds (setting them to 0), while the MINUTE5 will, also, round down the minutes
in chunks of 5.
:param stamp: The stamp to round down.
:return: The rounded stamp.
"""
if self == self.SECOND:
return stamp.replace(microsecond=0)
elif self == self.MINUTE:
return stamp.replace(microsecond=0, second=0)
elif self == self.MINUTE5:
return stamp.replace(microsecond=0, second=0, minute=(stamp.minute // 5) * 5)
elif self == self.MINUTE10:
return stamp.replace(microsecond=0, second=0, minute=(stamp.minute // 10) * 10)
elif self == self.MINUTE15:
return stamp.replace(microsecond=0, second=0, minute=(stamp.minute // 15) * 15)
elif self == self.MINUTE20:
return stamp.replace(microsecond=0, second=0, minute=(stamp.minute // 20) * 20)
elif self == self.MINUTE30:
return stamp.replace(microsecond=0, second=0, minute=(stamp.minute // 30) * 30)
elif self == self.HOUR:
return stamp.replace(microsecond=0, second=0, minute=0)
elif self == self.HOUR2:
return stamp.replace(microsecond=0, second=0, minute=0, hour=(stamp.hour // 2) * 2)
elif self == self.HOUR3:
return stamp.replace(microsecond=0, second=0, minute=0, hour=(stamp.hour // 3) * 3)
elif self == self.HOUR4:
return stamp.replace(microsecond=0, second=0, minute=0, hour=(stamp.hour // 4) * 4)
elif self == self.HOUR6:
return stamp.replace(microsecond=0, second=0, minute=0, hour=(stamp.hour // 6) * 6)
elif self == self.HOUR8:
return stamp.replace(microsecond=0, second=0, minute=0, hour=(stamp.hour // 8) * 8)
elif self == self.HOUR12:
return stamp.replace(microsecond=0, second=0, minute=0, hour=(stamp.hour // 12) * 12)
elif self == self.DAY:
return stamp.replace(microsecond=0, second=0, minute=0, hour=0)
else:
raise AssertionError("An unexpected interval type (perhaps there's a bug or pending work here) tried "
"to round a timestamp")
|
687a678c13129f05b136eb770abde72a014824d5 | ChenCMadmin/study | /object/day2/super的使用.py | 1,683 | 3.75 | 4 | # 自定义类
class Master(object):
# 实例方法,方法
def make_cake(self):
print("按照 [古法] 制作了一份煎饼果子...")
# 父类是 Master类
class School(Master):
# 实例方法,方法
def make_cake(self):
print("按照 [现代] 制作了一份煎饼果子...")
# 执行父类的实例方法
super().make_cake()
# 父类是 School 和 Master
# 多继承,继承了多个父类
class Prentice(Master ,School):
# 实例方法,方法
def make_cake(self):
print("按照 [猫氏] 制作了一份煎饼果子...")
def make_all_cake(self):
# 方式1. 指定执行父类的方法(代码臃肿)
# School.make_cake(self)
# Master.make_cake(self)
# 方法2. super() 带参数版本,只支持新式类
# super(Prentice, self).make_cake()
# self.make_cake()
# 方法3. super()的简化版,只支持新式类
# 执行父类的 实例方法
super().make_cake()
damao = Prentice()
damao.make_cake()
damao.make_all_cake()
# print(Prentice.__mro__)
'''
子类继承了多个父类,如果父类类名修改了,那么子类也要涉及多次修改。而且需要重复写多次调用,显得代码臃肿。
使用super() 可以逐一调用所有的父类方法,并且只执行一次。调用顺序遵循 mro 类属性的顺序。
注意:如果继承了多个父类,且父类都有同名方法,则默认只执行第一个父类的(同名方法只执行一次,目前super()不支持执行多个父类的同名方法)
super() 在Python2.3之后才有的机制,用于通常单继承的多层继承。
''' |
363ca8016f7c45d74305dccf463cc427ae24d49c | tzyl/algorithms-python | /algorithms/dynamicprogramming/longest_palindrome_substring.py | 530 | 3.71875 | 4 | # O(n^2) DP solution.
def longest_palindrome_substring(s):
longest = ""
# P[i][j] is True if the substring s[i:j+1] is a palindrome.
P = [[False] * len(s) for _ in range(len(s))]
for i in range(len(s)):
P[i][i] = True
for l in range(2, len(s) + 1):
for i in range(len(s) + 1 - l):
j = i + l - 1
if s[i] == s[j] and (j == i + 1 or P[i + 1][j - 1]):
P[i][j] = True
longest = max(longest, s[i:j+1], key=len)
return longest
|
3fd31d6c5df189d06d76aae96be127f8645b899a | hbishnoi/SSW-810 | /HW07_Himanshu.py | 1,931 | 4.15625 | 4 | '''wroking with different type of methods to use dictionaries, tuples, list and set'''
from collections import defaultdict, Counter
from typing import DefaultDict, Counter, List, Tuple
def anagrams_lst(str1: str, str2: str) -> bool:
'''checking if two given strings are anagrams or not'''
return sorted(str1.lower()) == sorted(str2.lower())
def anagrams_dd(str1: str, str2: str) -> bool:
'''checking if two given strings are anagrams or not by method defaultdict'''
dd: DefaultDict[str, int] = defaultdict(int)
for i in str1.lower():
dd[i] += 1
for c in str2.lower():
dd[c] -= 1
return not any(dd.values())
def anagrams_cntr(str1: str, str2: str) -> bool:
'''checking if two given strings are anagrams or not by method Counter'''
return Counter(str1.lower()) == Counter(str2.lower())
def covers_alphabet(sentence: str) -> bool:
'''determine if input string contains all the alphabets'''
return set('abcdefghijklmnopqrstuvwxyz') <= set(sentence.lower()) # method 1
# return sorted('abcdefghijklmnopqrstuvwxyz') == sorted(set((''.join(e for e in sentence if e.isalpha())).lower())) # method 2
# return set("abcdefghijklmnopqrstuvwxyz").issubset(set(sentence.lower())) # method 3
def web_analyzer(weblogs: List[Tuple[str, str]]) -> List[Tuple[str, List[str]]]:
'''using defaultdict to determine which website is used by which person'''
dd_wa: DefaultDict[Tuple[str, List[str]]] = defaultdict(set)
for first, second in weblogs:
dd_wa[second] = dd_wa[second].union({first}) # method 1
# dd_wa[second].add(first) # method 2
return sorted([tuple([key, sorted(value)]) for key, value in dd_wa.items()])
|
91525fd00852b57c89915cb99815b5a838596d3e | jayendra-ram/columbia_hw | /e4040-2021fall-assign1-jcr2211/utils/classifiers/softmax.py | 4,035 | 3.8125 | 4 | import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
This adjusts the weights to minimize loss.
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: a numpy array of shape (D, C) containing weights.
- X: a numpy array of shape (N, D) containing a minibatch of data.
- y: a numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength. For regularization, we use L2 norm.
Returns a tuple of:
- loss: (float) the mean value of loss functions over N examples in minibatch.
- gradient: gradient wrt W, an array of same shape as W
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
#############################################################################
# START OF YOUR CODE #
#############################################################################
N = X.shape[0]
# loss
e = np.exp(np.dot(X, W))
h = e/np.sum(e, axis=1).reshape(len(e),1)
for n in range(N):
loss += -np.log(h[n][y[n]])/N
loss += 0.5 * reg*np.linalg.norm(W)
# dW
for n in range(N):
h[n][y[n]] -= 1
dW = np.dot(X.T, h)/N
#dW += reg * W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
This adjusts the weights to minimize loss.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using no explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
#############################################################################
# START OF YOUR CODE #
#############################################################################
#h = (np.exp(X)/np.sum(np.exp(X)))
#print("h shape",h.shape)
#loss = (-np.log(h[y])).mean() + reg*np.linalg.norm(W)
#dW = np.dot(X.T, (h - y)) / y.shape[0]
#rewrite
N = X.shape[0]
# loss
e = np.exp(np.dot(X, W))
h = e/np.sum(e, axis=1).reshape(len(e),1)
loss = -np.log(h[range(N), y]).mean()
loss += 0.5 * reg*np.linalg.norm(W)
# dW
h[range(N), y] -= 1
dW = np.dot(X.T, h)/N
#dW += reg * W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
|
a02411c22d8ba287dd4b0dc678cc97010cf29193 | AnacondaSL/Own-tiny-project | /phonebook.py | 992 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Filename: phonebook.py
# Author: SHUANG LUO
import os
path = os.path.expanduser(r"~/Desktop/myphonebook.txt")
phonebook_content = open(path).read()
c = phonebook_content.split('\n')
print (c) # this line is used to print out the context of myphonebook.text which can be removed
flag = 0 # means the user's name is not found
print ("This is a phonebook")
print ("Type into user name for searcing his/her TEL_NUMBER, in the form of (Last_name first_name)")
print ("'QUIT' for quit this phonebook")
user_input = input("Please, type a name: ")
if user_input == "QUIT" :
print ("Thank you for using this excellent phone number application!")
print ("Good Bye!")
flag = 2 # means the user want to quit
for element in c:
each_info = element.split(":")
if each_info[0] == user_input:
print(each_info[1])
flag = 1 # means the user's name is found
break
if flag == 0 :
print("Phone number is not available")
|
b2b1a2906b87726310da8df55a3b1a5a7db8afd8 | BolajiOlajide/python_learning | /beyond_basics/decorators.py | 460 | 4.125 | 4 | """
Decorators are a way to modify or enhance functions
w/o changing their definition.
"""
# functions as decorators
def escape_unicode(f):
def wrap(*args, **kwargs):
x = f(*args, **kwargs)
return ascii(x)
return wrap
@escape_unicode
def vegetable():
return "blomkåi"
@escape_unicode
def animal():
return "bjørn"
@escape_unicode
def mineral():
return "stål"
print(vegetable())
print(animal())
print(mineral())
|
9ec4431f8fa8b33436f0edecb985236c60923ef2 | tsuganoki/project_euler | /014.py | 589 | 4 | 4 | """n → n/2 (n is even)
n → 3n + 1 (n is odd)"""
def get_longest_seq(starting_num):
longest_seq = 0
ans = 0
for i in range(starting_num,1,-1):
seq = 0
result = i
print("i is: ", i)
while result > 1:
if result % 2 == 0:
result = int(result/2)
else:
result = (3*result)+1
seq +=1
if seq > longest_seq:
longest_seq = seq
ans = i
print(ans)
return [ans,longest_seq]
print(get_longest_seq(1000000))
print("done")
|
c735184ae91c85b051485e379e600f8dec358a90 | Meph1sto/Text_Problems | /pig_latin.py | 566 | 3.984375 | 4 | '''
Pig Latin - Pig Latin is a game of alterations played on the English language game.
To create the Pig Latin form of an English word the initial consonant sound is transposed to the end of the word and an ay is affixed
(Ex.: "sloppy" would yield loppy-say).
'''
def pig_latin(word):
vowels = ['a','e','i','o','u']
if word[0] not in vowels:
word = word[1:] + '-' + word[0] + 'ay'
return word
in_string = input('Please enter the word you wish to convert to Pig Latin: ')
print('The Pig Latin version of '+ str(in_string)+' is '+str(pig_latin(in_string)))
|
4e2c09068d42bc86ecdaf52708fb8ddc05416cda | sky-dream/LeetCodeProblemsStudy | /[0035][Easy][Search_Insert_Position][BinarySearch]/Search_Insert_Position.py | 496 | 3.84375 | 4 | # Time Complexity: O(logN)
# Space Complexity: O(1)
# solution 1, binary search
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if not nums:
return 0
start,end = 0,len(nums)-1
while(start<=end):
mid = start + (end-start)//2
if nums[mid]==target:
return mid
if nums[mid]<target:
start = mid+1
else:
end = mid-1
return start |
3028bf1fee341282434508fb1bf5a8225c80ee0d | Josh551/Kamikaze | /cobra2.py | 172 | 4.375 | 4 | #Program to check if number is negative or positive
a=int(input("Enter a no"))
if a>0:
print("the number is positive")
else:
print("the number is negative")
|
0b4cc7f6c6b7f676144caed7c668fd1880c55c38 | cszatmary/machine-learning-exercises | /Part 8 - Deep Learning/Section 40 - Convolutional Neural Networks (CNN)/cnn.py | 1,902 | 3.6875 | 4 | # Convolutional Neural Network
# Part 1 - Building the CNN
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Flatten, Dense
from keras.preprocessing.image import ImageDataGenerator
# Steps: Convolution -> Max Pooling -> Flattening -> Full Connection (ANN)
# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
# Add the Convolution layer
classifier.add(Convolution2D(filters=32, kernel_size=(3, 3), input_shape=(64, 64, 3), activation='relu'))
# Step 2 - Max Pooling
classifier.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
# Adding a second convolutional layer
classifier.add(Convolution2D(filters=32, kernel_size=(3, 3), activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full Connection (Create ANN)
classifier.add(Dense(units=128, activation='relu'))
# Output layer
classifier.add(Dense(units=1, activation='sigmoid'))
# Compiling the CNN
classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Part 2 - Fitting the CNN to the images
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
# Creating the training set
training_set = train_datagen.flow_from_directory(
'dataset/training_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
# Create the test set
test_set = test_datagen.flow_from_directory(
'dataset/test_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
# Fit the data to the CNN model
classifier.fit_generator(
training_set,
steps_per_epoch=8000,
epochs=25,
validation_data=test_set,
validation_steps=2000)
|
aaa77b1da87339f2ede526dd10f9622ba52c0754 | HeDefine/LeetCodePractice | /Q705.设计哈希集合.py | 1,483 | 4 | 4 | #!/usr/bin/env python3
# https://leetcode-cn.com/problems/design-hashset
# 不使用任何内建的哈希表库设计一个哈希集合
# 具体地说,你的设计应该包含以下的功能
# add(value):向哈希集合中插入一个值。
# contains(value) :返回哈希集合中是否存在这个值。
# remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
#
# 示例:
# MyHashSet hashSet = new MyHashSet();
# hashSet.add(1);
# hashSet.add(2);
# hashSet.contains(1); // 返回 true
# hashSet.contains(3); // 返回 false (未找到)
# hashSet.add(2);
# hashSet.contains(2); // 返回 true
# hashSet.remove(2);
# hashSet.contains(2); // 返回 false (已经被删除)
#
# 注意:
# 所有的值都在 [1, 1000000]的范围内。
# 操作的总数目在[1, 10000]范围内。
# 不要使用内建的哈希集合库。
class MyHashSet:
def __init__(self):
self.num = [False] * 1000000
def add(self, key: int) -> None:
self.num[key] = True
def remove(self, key: int) -> None:
self.num[key] = False
def contains(self, key: int) -> bool:
return self.num[key]
# Your MyHashSet object will be instantiated and called as such:
obj = MyHashSet()
obj.add(1)
obj.add(2)
print(obj.contains(1))
print(obj.contains(3))
obj.add(2)
print(obj.contains(2))
obj.remove(2)
print(obj.contains(2))
|
c5b7cac2173d0a767ec340e86ba30f12ed62a2f2 | ARXZ-soft/idea-board | /idea_board_jp.py | 787 | 3.5625 | 4 | # coding:utf-8
import tkinter as tk
import tkinter.messagebox as tmsg
import random
# ボタンがクリックされたときの処理
def ButtonClick():
tmsg.showinfo("ヘルプ", "一時的にドキュメントを保存するアプリです。終了すると同時に保存してあるドキュメントは削除されるのでご注意ください。 ")
# メインのプログラム
root = tk.Tk()
root.geometry("650x565")
root.title("アイディアボード Ver.0.1.2")
# 履歴表示のテキストボックスを作る
rirekibox = tk.Text(root, font=("Helvetica", 10))
rirekibox.place(x=10, y=0, width=630, height=500)
button1 = tk.Button(root, text = "ヘルプ", font=("Helvetica", 10), command=ButtonClick)
button1.place(x = 590, y = 530)
root.mainloop()
|
94268fd83330470506552e3439a23c35a1c7d1d1 | usmanchaudhri/azeeri | /sort_array_of_0_1_and_2/sort_array_of_0_1_and_2.py | 2,562 | 4.09375 | 4 | """
Given balls of these three colors (Red, Green and Blue) arranged randomly in a line (the actual. 8/18
number of balls does not matter), the task is to arrange them such that all balls of the same color are together and their
collective color groups are in the correct order (Red first, Green next and Blue last). These are the colors similar to
the Dutch National Flag, hence the name. This is a popular sorting problem.
Solution constraints
* Use array as your data-structure to represent the balls, not linked lists.
* Do this in ONE pass over the array - not two passes, just one pass
* Your solution can only use O(1) extra memory i.e. you have to do this in-place. (For Java/C#, it's okay to convert
incoming String to a character Array or a buffer/builder, but don't use any other memory for processing)
* Minimize the number of swaps.
Input: A string of letters, where each letter represents a ball with color. R = Red Ball, 'G' '= Green Ball. B = Blue Ball
Output: A string of letters, in sorted order
e.g.
Input: GBGGRBRG
Output: RRGGGGBB
"""
from collections import defaultdict
# time O(n) | space number of distinct colors in the array o(N)
def sortUsingCount(balls):
# count the number of balls and than rearrange the original array
# with the appropriate sorting order
rearrangeBalls = defaultdict(int)
for i in range(len(balls)):
rearrangeBalls[balls[i]] +=1
r = rearrangeBalls.get('R')
g = rearrangeBalls.get('G')
b = rearrangeBalls.get('B')
i = 0
while r > 0:
balls[i] = 'R'
r -=1
i +=1
while g > 0:
balls[i] = 'G'
g -=1
i +=1
while b > 0:
balls[i] = 'B'
b -=1
i +=1
print(balls)
"""
using mid as a pivot pointer we will compare mid to low and mid to high and sort appropriately.
all values which have a higher precedence than mid goes to the right of mid and all values
which have a lower precedence than mid goes to the left of mid.
"""
# time O(N) | space O(1)
def sortBallsByOrder(balls):
low = 0
mid = 0
hi = len(balls) - 1
while mid <= hi:
if balls[mid] == 'R':
balls[low], balls[mid] = balls[mid], balls[low]
low +=1
mid +=1
elif balls[mid] == 'G':
mid +=1
else:
balls[mid], balls[hi] = balls[hi], balls[mid]
hi -=1
return balls
if __name__ == "__main__":
balls = ['G', 'B', 'G', 'G', 'R', 'B', 'R', 'G']
# print(sortUsingCount(balls))
print(sortBallsByOrder(balls))
|
1a8d49ede10973475e59a34d9c34113f5892630d | alexanderraj478/TSH01 | /TSHTDM/DataNode1D.py | 1,414 | 3.609375 | 4 | class DataNode1D:
def __init__(self):
self.m_DataNode1D = []
@property
def NoneNode(self):
return self.__NoneNode
@NoneNode.setter
def NoneNode(self, NoneNode):
self.__NoneNode = NoneNode
def AddDataNode(self, DataNode):
self.m_DataNode1D.append (DataNode)
return len(self.m_DataNode1D)
def ReplaceDataNode(self, DataNode1DInd, DataNode):
if (DataNode1DInd < len(self.m_DataNode1D)):
self.m_DataNode1D[DataNode1DInd] = DataNode
def GetDataNode(self, DataNode1DInd):
if (DataNode1DInd < len(self.m_DataNode1D)):
return(self.m_DataNode1D[DataNode1DInd])
else:
print("Incorrect Index value:" + str(DataNode1DInd))
print("Needs to less than:" + str(len(self.m_DataNode1D)))
return None
def GetLastDataNode(self):
return self.m_DataNode1D[self.GetDataNode1DLen()-1]
def GetDataNode1D(self):
return (self.m_DataNode1D)
def GetDataNode1DLen(self):
return len(self.m_DataNode1D)
def ShowDataVals(self, methodToRun):
i = 0
while (i < len(self.m_DataNode1D)):
methodToRun.call()
#print(self.m_DataNode1D[i].GetDataVal())
i += 1
|
ffaefb5dbb07772e2271f0886dc3e4480272a44a | cromox1/KodPerang_kata | /4kyu_next_smaller_number_same_digits_2.py | 2,235 | 3.671875 | 4 | def next_smaller(n):
print(n)
chars = list(str(n))
print(chars)
print(sorted(chars))
print(sorted(chars, reverse=True))
uniq = list(set(chars))
print(uniq)
limit = int(''.join(sorted(chars))) - 1
for i in range(n - 1, limit, -1):
if sorted(list(str(i))) == sorted(chars) and i < n:
return i
break
return -1
########### TDD
class Test:
def assert_equals(value, expected):
from nose.tools import assert_equal
try:
assert_equal(value, expected)
print("EQUAL -- > Got = {} == Expected = {} ".format(value, expected))
except:
print("UNEQUAL -- > Got = {} != Expected = {} ".format(value, expected))
@classmethod
def describe(cls, param):
print(param)
@classmethod
def it(cls, param):
print(param)
########### TDD TESTING SECTION
Test.it("Smaller numbers")
# Test.assert_equals(next_smaller(907), 790)
# Test.assert_equals(next_smaller(531), 513)
# Test.assert_equals(next_smaller(135), -1)
# Test.assert_equals(next_smaller(2071), 2017)
# Test.assert_equals(next_smaller(414), 144)
# Test.assert_equals(next_smaller(123456798), 123456789)
# Test.assert_equals(next_smaller(123456789), -1)
# Test.assert_equals(next_smaller(1234567908), 1234567890)
# Test.assert_equals(next_smaller(9),-1)
# Test.assert_equals(next_smaller(111),-1)
# Test.assert_equals(next_smaller(513),351)
# #### failed (previously - now passed !! )
# Test.assert_equals(next_smaller(1234567890),1234567809)
# Test.assert_equals(next_smaller(59884848459853),59884848459835)
# Test.assert_equals(next_smaller(80852318796877),80852318796787)
# Test.assert_equals(next_smaller(25087654),25087645)
# Test.assert_equals(next_smaller(82174),82147)
# Test.assert_equals(next_smaller(2964),2946)
# Test.assert_equals(next_smaller(8890),8809)
# Test.assert_equals(next_smaller(21652),21625)
# Test.assert_equals(next_smaller(67651),67615)
Test.assert_equals(next_smaller(74965),74956)
# Test.assert_equals(next_smaller(284),248)
Test.assert_equals(next_smaller(911111112),291111111)
Test.assert_equals(next_smaller(900000001),190000000)
# Test.assert_equals(next_smaller(900000000001),190000000000)
|
3db5aa67b9dee910d5ce5a47fad35813ad723c93 | r3k4t/Python-Practice.github.io | /conditional-statement.py | 634 | 4.25 | 4 | # Conditional statement
# if
# elif(else if)
# else
# when if true and answer ==> ok,hello.
print('Condtional Statement: 1')
if 3>2:
print('ok')
elif 2<4:
print('hmm')
else:
print('1+1')
print('hello')
# When if false and answer ==> hmm,hello.
print('Condtional Statement: 2 ==>Example:Robot')
if 3<2:
print('ok')
elif 2<4:
print('hmm')
else:
print(1+1)
print("hello")
print("Conditional Statement 3")
print
print('Enter your command')
robot_move == input()
if robot_move == 'front':
print('Moving Front')
elif robot_move == 'back':
print('Moving Back')
else:
print('stand still')
|
11394f3928f8f2e005476ae15246b3bd5fa7a49b | cg-dv/project_euler | /46.py | 490 | 3.59375 | 4 | #!/usr/bin/env python
import sieve
def is_goldbach(n):
for prime in primes:
for square in squares:
if n == (prime + (2 * square)):
return True
return False
odds = set([(2 * i + 1) for i in range(100000)])
primes = set(sieve.eratosthenes(100000))
squares = set([i ** 2 for i in range(1,1000)])
for i in range(2,100000):
if i in odds and i not in primes:
print(i)
if not is_goldbach(i):
print(i, 'Not Goldbach')
|
29c17bf2b044a349ce48555b1f3f2079419ec58a | rohinisyed/GuessTheNumber | /main.py | 471 | 3.84375 | 4 | from random import randint
play_game=True
random_number = randint(1,100)
while play_game:
player_guess = int(input("Guess the number: "))
if player_guess > random_number:
print ("Too High, Try again!")
elif player_guess < random_number:
print ("Too low, Try Again!")
else:
play_again = input ("You won, Want to play again Y/N?:")
if play_again == "Y":
random_number = randint(1,100)
elif play_again == "N":
play_game=False |
252dd5a270dcd877885c4016b2981f3a76129c7d | zerynth/core-zerynth-stdlib | /examples/Serial_Port_Read-Write_Basics/main.py | 599 | 3.515625 | 4 | ################################################################################
# Serial Port Basics
#
# Created by Zerynth Team 2015 CC
# Authors: G. Baldi, D. Mazzei
################################################################################
import streams
# creates a serial port and name it "s"
s=streams.serial()
while True:
print("Write some chars on the serial port and terminate with \\n (new line)")
line=s.readline() # read and return any single character available on the serial port until a \n is found
print("You wrote:", line)
print()
sleep (300)
|
04713dff54915945494ae5438ed4a0b0cdb95c01 | RenegaDe1288/pythonProject | /lesson30/mission1.py | 342 | 3.65625 | 4 | from functools import reduce
floats = [12.3554, 4.02, 5.777, 2.12, 3.13, 2, 11.0001]
names = ["Vanes", "Alen", "Jana", "William", "Richards", "Joy"]
numbers = [22, 33, 10, 6894, 11, 2, 1]
print(list(map(lambda x: round((x ** 3), 3), floats)))
print(list(filter(lambda x: len(x) > 4, names)))
print(reduce(lambda x, y: x * y, numbers))
|
a6d01340ec8f516b4eff483a8c5a9526633907c6 | hatttruong/machine-learning-from-scratch | /util/helper.py | 212 | 3.5 | 4 | def extract_words(document):
"""Summary
Args:
document (str): document instance
Returns:
list: list of words
"""
words = document.lower().strip().split(' ')
return words
|
6e5180cdeac9e948734601c391442be97579e7ab | Leigan0/python_challenges | /fibonacci/app/fib_checker.py | 164 | 3.53125 | 4 | from fibonacci import FibonacciChecker
import argparse
i = input('Please enter a number ')
fib_checker = FibonacciChecker(i)
print('sum =')
print(fib_checker.sum()) |
2a04d196e19ae05e33286694314106e64d25812d | ritishadhikari/pandas | /pandas_merge.py | 1,897 | 3.734375 | 4 | import pandas as pd
df1 = pd.DataFrame({
"city": ["new york","chicago","orlando"],
"temperature": [21,14,35],
},index=[0,1,2])
df2 = pd.DataFrame({
"city": ["chicago","new york","orlando"],
"humidity": [65,68,75],
},index=[1,0,2])
df3 = pd.concat([df1,df2],axis=1)
print("The Concatenated DataFrame DF3 Looks Like :\n",df3,"\n")
df4 = pd.merge(left=df1,right=df2,on='city')
print("The Merged Dataframe DF4 looks like :\n", df4,"\n")
df5 = pd.DataFrame({
"city": ["new york","chicago","orlando",'baltimore'],
"temperature": [21,14,35,32]})
df6 = pd.DataFrame({
"city": ["chicago","new york","san fransisco"],
"humidity": [65,68,75]})
df7 =pd.merge(left=df5,right=df6,on='city')
print("The Updated DataFrame DF7 looks like :\n", df7,"\n")
df8 =pd.merge(left=df5,right=df6,on='city',how='outer',indicator=True)
print("The Updated Outer Join DataFrame DF8 looks like :\n", df8,"\n")
df9 =pd.merge(left=df5,right=df6,on='city',how='left')
print("The Updated Left Join DataFrame DF9 looks like :\n", df9,"\n")
df10 =pd.merge(left=df5,right=df6,on='city',how='right')
print("The Updated Right Join DataFrame DF10 looks like :\n", df10,"\n")
df11 = pd.DataFrame({
"city": ["new york","chicago","orlando", "baltimore"],
"temperature": [21,14,35,38],
"humidity": [65,68,71, 75]
})
df12 = pd.DataFrame({
"city": ["chicago","new york","san diego"],
"temperature": [21,14,35],
"humidity": [65,68,71]
})
df13 = pd.merge(left=df11,right=df12,on='city')
print("The Merged DataFrame DF13 Looks like :\n",df13,"\n")
df14 = pd.merge(left=df11,right=df12,on='city',suffixes=('_left','_right'))
print("The Merged DataFrame DF14 Looks like :\n",df14,"\n")
###df14.to_excel(r'C:\Users\ritis\PycharmProjects\CSV Files\Merged.xlsx',sheet_name='Merged Data',index=False,startrow=0,startcol=0) |
bf589df2e1b01a9bfe7a2943a60ae98323eebf41 | kasia-basia/advent-of-code | /02.py | 675 | 3.609375 | 4 | """https://adventofcode.com/2020/day/2"""
with open(r'02.txt') as data:
passwords = [row.split(' ') for row in data.read().splitlines()]
def check_passwords1():
i = 0
for [times, letter, password] in passwords:
min, max = times.split('-')
if password.count(letter[0]) in range(int(min), int(max)+1):
i = i+1
return i
def check_passwords2():
i = 0
for [times, letter, password] in passwords:
first, second = times.split('-')
if bool(password[int(first)-1] == letter[0]) ^ bool(password[int(second)-1] == letter[0]):
i += 1
return i
print(check_passwords1())
print(check_passwords2())
|
2d9c8d0200dc8f2eeba12abc764601b6fbf2bbd4 | jvugar/Intelligent-Atropos-Player | /jvugarPlayer.py | 4,985 | 3.515625 | 4 | #Vugar Javadov
#U66070335
#jvugar@bu.edu
#CS440: PA3
import sys
# print to stderr for debugging purposes
# remove all debugging statements before submitting your code
msg = "Given board " + sys.argv[1] + "\n";
sys.stderr.write(msg);
#parse the input string, i.e., argv[1]
s = sys.argv[1]
#s ="[13][302][1003][30002][100003][3000002][10000003][300000002][12121212]LastPlay:null"
(initBoard, lastPlay) = s.split("LastPlay:")
if lastPlay != "null":
lastPlay = lastPlay[1:]
lastPlay = lastPlay[:-1]
lastPlay = lastPlay.split(",")
lastPlay = [int(i) for i in lastPlay]
brd = []
rw = []
for character in initBoard:
if character == '[':
rw = []
elif character == ']':
brd.append(rw)
else:
rw.append(int(charecter))
brd.reverse()
#perform intelligent search to determine the next move
#define colors
nocolor = 0
red = 1
blue = 2
green = 3
#define size
size = len(brd)-2
#define depth
depth = 5
positiveNum = 1000 #upperbound for beta
negativeNum = -1000 #lowerbound for alpha
#find adjacent positions
def adjacent(board, lastPlay):
rght = lastPlay[2]
adjacent = []
hght = lastPlay[1]
if hght > 1:
adjacent = [(hght+1, rght -1), (hght+1, rght), (hght, rght+1), (hght-1, rght+1), (hght-1, rght), (hght, rght-1)]
else:
adjacent = [(hght+1, rght -1), (hght+1, rght), (hght, rght+1), (hght-1, rght), (hght-1, rght-1), (hght, rght-1)]
return adjacent
#find all available moves
def availableMoves(board, lastPlay):
adjacentList = adjacent(board, lastPlay)
options = []
for (h, r) in adjacentList:
if board[h][r] == 0:
options.append((h, r))
if options == []:
for irow, row in enumerate(board):
for icol, circle in enumerate(row):
if circle == 0:
options.append((irow, icol))
return options
#decide whether a move will lose the game
def gamedone(board, move):
clr = move[0]
adjacentList = adjacent(board, move)
for i, (h, r) in enumerate(adjacentList):
clrs = [color]
if brd[h][r] != 0:
clrs.append(board[h][r])
(H, R) = adjacentList[(i+1) % len(adjacentList)]
if brd[H][R] != 0:
clrs.append(board[H][R])
if len(set(clrs)) == 3:
return True
return False
#the static evaluator
def evaluator(board, move):
if (gamedone(board, move)):
return (negativeNum, [])
score = 0
#get 5 points for each adj with color
#get 2 points for each pair of adj that have the same color
#subtract 1 points for each adj that have the same color with move itself
adjacentList = adjacent(board, move)
color = move[0]
for i, (h, r) in enumerate(adjacentList):
fill = board[h][r]
if fill != 0:
score += 10
if fill == color:
score -= 1
(H, R) = adjList[(1+i) % len(adjList)]
if fill != board[H][R]:
score += 5
return (score, move)
#use minimax with alpha beta pruning to search best move
def alphaBetaPrune(board, lastPlay, depth, alpha, beta, isMax):
#if it is the first move, play it in the top of board
if lastPlay == "null":
return (0, [3, SIZE, 1, 1])
if depth == 0 or gamedone(board, lastPlay):
return evaluator(board, lastPlay)
else:
nodes = possibleMoves(board, lastPlay)
if isMax:
score = (negativeNum, [])
for (h, r) in nodes:
for color in range(1, 4):
board[h][r] = color
move = [color, h, r, SIZE+2-h-r]
nodeScore = alphaBeta(board, move, depth-1, alpha, beta, False)
board[h][r] = 0
if nodeScore[0] >= score[0]:
score = (nodeScore[0], move)
if score[0] > alpha:
alpha = score[0]
if beta <= alpha:
break
else:
score = (positiveNum, [])
for (h, r) in nodes:
for color in range(1, 4):
board[h][r] = color
move = [color, h, r, SIZE+2-h-r]
nodeScore = alphaBeta(board, move, depth-1, alpha, beta, True)
board[h][r] = 0
if nodeScore[0] >= score[0]:
score = (nodeScore[0], move)
if score[0] < beta:
beta = score[0]
if beta <= alpha:
break
return score
#best move
bstMv = alphaBetaPrune(brd, lastPlay, depth, negativeNum, positiveNum, True)
nxtMv = map(str, bstMv[1])
mkMv = ",".join(nxtMv)
#print to stdout for AtroposGame
sys.stdout.write("(" + mkMv + ")");
|
f2e4b6baed6c4317f5df5b95fc73ae8ee3c2dfda | twopiharris/230-Examples | /python/oop3/accessMethods.py | 372 | 3.703125 | 4 | """ accessMethods.py
demonstrates getters and setters
"""
class Critter(object):
def __init__(self, name = "Anonymous"):
self.name = name
def getName(self):
return self.name
def setName(self, name):
self.name = name
def main():
c = Critter()
c.setName("Marge")
print(c.getName())
if __name__ == "__main__":
main()
|
790cfbc5d6536879b9650d38f8df5ca6aa74bd9d | EmperoR1127/algorithms_and_data_structures | /PriorityQueue/MaxHeapPriorityQueue.py | 1,632 | 3.578125 | 4 | from HeapPriorityQueue import HeapPriorityQueue
class MaxHeapPriorityQueue(HeapPriorityQueue):
"""A max-oriented priority queue extends with a min-oriented priority queue"""
# -------- nonpublic utilities --------
def _upheap(self, i):
while i > 0:
idx_parent = self._parent(i)
if self._data[i] > self._data[idx_parent]:
self._swap(i, idx_parent)
i = idx_parent
else:
break
def _downheap(self, i):
while i <= len(self._data) - 1:
left, right, big_child = self._left(i), self._right(i), i
if left and self._data[left] > self._data[big_child]:
big_child = left
if right and self._data[right] > self._data[big_child]:
big_child = right
if big_child != i:
self._swap(i, big_child)
i = big_child
else:
break
# -------- public methods --------
def __init__(self, contents = ()):
super().__init__(contents)
def max(self):
if len(self._data) == 0:
raise ValueError("Empty Priority Queue")
return self._data[0]._key, self._data[0]._value
def remove_max(self):
self._swap(0, -1)
answer = self._data.pop()
self._downheap(0)
return answer._key, answer._value
if __name__ == "__main__":
pq = MaxHeapPriorityQueue([(3, "kb"), (2,"mj"), (5,"sd"), (4,"we")])
print(pq.max())
pq.add(1,"dfgdfg")
while len(pq) != 0:
print(pq.remove_max())
|
d78b7ef93cdd315e512294ebc3387aafbeb98a19 | Meet57/programming | /Basic Python/Tkinter/43_filedialog_box.py | 438 | 3.78125 | 4 | from tkinter import *
from tkinter import filedialog
def openfile():
result = filedialog.askopenfile(title="My file",filetype=(("text file",".txt"),("all files",".*")))
print(result)
text.delete(1.0,END)
for c in result:
text.insert(INSERT,c)
root = Tk()
button = Button(root, text='open file', command = openfile)
button.pack()
text = Text(root, wrap=WORD)
text.pack()
root.minsize(300,300)
root.mainloop()
|
ceba9d34a00337eafec9a71a3e353de90c563186 | jjason/RayTracerChallenge | /ray_tracer/patterns/checker_board.py | 1,737 | 4.34375 | 4 | import math
from patterns.pattern import Pattern
class CheckerBoard(Pattern):
"""
The checker board pattern. A checker board pattern has two colors and
changes in all three dimensions such that no two adjacent cubes are the
same color. The color is determined by:
+- color_a if (|px| + |py| + |pz|) mod 2 == 0
color @ point => |
+- color_b otherwise.
"""
def __init__(self,
color_a=None,
color_b=None,
transform=None):
"""
Initialize the stripe pattern object.
:param color_a: The color for the cubes with anchor point having zero
or two coordinates with odd values - (0, 0, 0), (1, 1, 0), etc.
If not provided, default is white.
:param color_b: The color for the cubes with anchor point having zero
or two coordinates with even values - (1, 1, 1), (1, 0, 0), etc.
If not provided, default is black
:param transform: The transform to be applied to the pattern. If None,
then the identity transform is used.
"""
super().__init__(color_a=color_a, color_b=color_b, transform=transform)
def color_at(self, position):
"""
Return the color (a or b) for the position provided. The color is
determined as described above.
:param position: The point for which color is to be determined.
:return: Color, the color for the point.
"""
return self.color_a if (math.floor(position.x) +
math.floor(position.y) +
math.floor(position.z)) % 2 == 0 else \
self.color_b
|
e37741f8c0297ff2e2b75284869d3a89dbdcf930 | HamzaRatrout/my_project | /python/square.py | 181 | 3.90625 | 4 | import turtle
turtle.shape("turtle")
for x in range(10):
for x in range(4):
turtle.forward(100)
turtle.left(90)
turtle.left(36)
turtle.hideturtle()
turtle.exitonclick()
|
6a11225f0f6646e70d86db7ca057260953afe5a0 | japarker02446/BUProjects | /CS521 Data Structures with Python/Homework3/japarker_hw_3_1.py | 1,998 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
japarker_hw_3_1.py
Jefferson Parker
Class: CS 521 - Spring 1
Date: February 3, 2022
Loop through the integers 2 - 130, inclusive
Count and report how many are:
Even
Odd
Squares
Cubes
For evens and odds, report the range.
For squares and cubes, report the list of values.
"""
# Initialize a few variables to hold values of interest.
first_even_int = 0
last_even_int = 0
count_even_int = 0
first_odd_int = 0
last_odd_int = 0
count_odd_int = 0
squares_list = []
cubes_list = []
# Use constants to hold the start and end values.
START_INT = 2
END_INT = 130
# Range from 2 to 130, inclusive
for i in range(START_INT,END_INT+1):
#print(i) #Make sure the loop is working, comment this out later.
'''
If i is even:
Increment the count of evens
Capture the first even value
Capture the last even value
'''
if(i % 2 == 0):
count_even_int += 1
if(first_even_int == 0):
first_even_int = i
if(i > last_even_int):
last_even_int = i
'''
If i is odd:
Increment the count of odds
Capture the first odd value
Capture the last odd value
'''
if(i % 2 == 1):
count_odd_int += 1
if(first_odd_int == 0):
first_odd_int = i
if(i > last_odd_int):
last_odd_int = i
# Capture the squares and the cubes.
if(i**2 <= END_INT):
squares_list.append(i**2)
if(i**3 <= END_INT):
cubes_list.append(i**3)
#end for loop
# Print the report.
print("Checking numbers from ", START_INT, " to ", END_INT)
print("Odd (", count_odd_int, "): ", first_odd_int, "...", last_odd_int, sep="")
print("Even (", count_even_int, "): ", first_even_int, "...", last_even_int, sep="")
print("Square (", len(squares_list), "): ", squares_list, sep="")
print("Cube (", len(cubes_list), "): ", cubes_list, sep="")
|
43f65417df793810d673e87d36aea7fb4aae1e84 | dlavareda/Inteligencia-Artificial | /Ficha 1/5.py | 1,436 | 4.25 | 4 | """
A biblioteca numpy é muito útil para processamento matemático de dados
(tipo matlab). Para a podermos usar devemos fazer o seguinte import:
import numpy as np
Agora podemos criar, por exemplo, um array 7x3 (7 linhas e 3 colunas)
inicializado a zero com:
a = np.zeros([7,3])
Escreva um programa um programa que peça ao utilizador duas matrizes
quadradas 2x2, A e B, e mostre no ecrã:
(a) o produto elemento a elemento A.B
(b) o produto matricial A ∗ B
(c) a diferença entre matrizes A − B
(d) o logaritmo dos elementos de A (se existirem elementos negativos, use
o seu valor absoluto)
(e) o maior valor da segunda linha de A vezes o menor valor da primeira
coluna de B.
"""
import numpy as np
def lerMatriz():
matriz = np.zeros([2, 2])
for i in range(2):
for j in range(2):
print("Posição " + str(i) + " x " + str(j))
matriz[i, j] = int(input())
return matriz
"""
(a)
"""
def produtoElementoaElementoMatriz(a, b):
z = a * b
return z
"""
(b)
"""
def diferencaMatriz(a, b):
z = a - b
return z
"""
(c)
"""
def multiplicacaoMatriz(a, b):
z = a.dot(b)
return z
"""
(d)
"""
def logMatriz(a):
a = np.absolute(a)
z = np.log(a)
return z
"""
(e)
"""
def maiorXmenor(a,b):
z = np.amax(matriz1, axis=1)
z2 = np.amin(matriz2, axis=0)
return z[1]* z2[0]
matriz1 = lerMatriz()
matriz2 = lerMatriz()
print(maiorXmenor(matriz1, matriz2)) |
70b402256e784e540a30eaa337cbb3c77f206484 | jonathanchiu/python-gpacalc | /gpa_calc.py | 1,387 | 4.03125 | 4 | class Course:
"""Contains information regarding a course
Parameters:
grade -- String representing letter grade received
credits -- Integer representing number of credits course has
name -- String representing the name of the course (optional)
"""
def __init__(self, grade, credits, name = "N/A"):
self.grade = letter_to_num[grade]
self.letter = grade
self.credits = credits
self.name = name
def __str__(self):
"""Return a string representing this course
self -- A Course object
"""
return (self.letter + "," + str(self.credits) + "," + self.name)
letter_to_num = {
'A' : 4.000,
'A-': 3.667,
'B+': 3.333,
'B' : 3.000,
'B-': 2.667,
'C+': 2.333,
'C' : 2.000,
'C-': 1.667,
'D+': 1.333,
'D' : 1.000,
'D-': 0.667,
'F' : 0.000
}
fall2014 = [
Course('A', 4, "Potato Theory"),
Course('B', 4, "History of Swag"),
Course('A-', 4, "Particle Physics"),
Course('A-', 4, "History of Chinese Culture")
]
def gpa(semester):
"""Given a list of Course objects, calculate the gpa for that semester
semester -- A list of Course objects representing courses taken in a semester
"""
total_qpt = 0
total_credits = 0
for course in semester:
qpt = course.grade * course.credits
total_qpt += qpt
total_credits += course.credits
gpa = total_qpt / total_credits
return gpa
|
5204fd16933d40e6b4881193f4b1960857741995 | george-hcc/py-euler | /044_pentagon_numbers.py | 578 | 3.5 | 4 | #!/usr/bin/python3
def main(upper_limit):
#return alt()
pentagon_list = [n*(3*n-1)//2 for n in range(1, upper_limit)]
pentagon_set = set(pentagon_list)
solution = 0
found = False
for idx, pj in enumerate(pentagon_list):
for pk in pentagon_list[idx+1:]:
if (pk+pj in pentagon_set) and (pk-pj in pentagon_set):
solution = pk-pj
found = True
break
if found:
break
print("The solution is:", solution)
return
if __name__ == '__main__':
main(2500)
|
6ace7e4ba422fed937a2bdfe30fbc90bcf2a8777 | eebmagic/algos_hw | /05/py_tests/three/script.py | 2,000 | 3.53125 | 4 | import matplotlib.pyplot as plt
class Line:
# y = mx + b
def __init__(self, m, b, name='line'):
self.m = m
self.b = b
self.name = name
def f(self, x):
return (self.m * x) + self.b
def solution(a, b):
'''
find solution of two lines
'''
try:
slopes = a.m - b.m
offsets = b.b - a.b
x = offsets / slopes
y = a.f(x)
return (x, y)
except AttributeError:
print(type(a))
print(type(b))
print(dir(a))
print(dir(b))
def graph(lines, start=-50, stop=50):
fig, ax = plt.subplots()
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
x = list(range(start, stop))
for line in lines:
y = [line.f(i) for i in x]
ax.plot(x, y, linewidth=2)
ax.set_aspect('equal')
plt.show()
def max_line(start, lines, x_min):
m_line = None
m_y = -float('inf')
for line in lines:
if line != start:
x, y = solution(start, line)
if y > m_y and x > x_min:
m_line = line
m_y = y
return m_line
def visible(lines):
print(f'{lines = }')
out = []
lines.sort(key=lambda x: x.m)
out.append(lines[0])
last_x = -float('inf')
for line in lines[1:-1]:
next_line = max_line(out[-1], lines, last_x)
if next_line == None:
break
last_x = solution(next_line, out[-1])[0]
print(f'adding {next_line.name} because it has the highest soln on {out[-1].name}')
out.append(next_line)
if lines[-1] not in out:
out.append(lines[-1])
return out
if __name__ == '__main__':
a = Line(-8, -20, name='a')
b = Line(-1/2, -3, name='b')
c = Line(-1/5, -3/2, name='c')
d = Line(3/2, -7, name='d')
e = Line(3, -14, name='e')
lines = [a, b, c, d, e]
# graph(lines, start=-10, stop=10)
visible = visible(lines)
print([x.name for x in visible])
print(len(visible))
|
af03b870e655e3dd855e77f638af1032a31b61a6 | Ash515/LeetCode-Solutions | /Arrays/Difficulty-Easy/PascalTriangle1.py | 658 | 3.890625 | 4 | '''
118. Pascal's Triangle
Given an integer numRows, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown
'''
class Solution:
def generate(self, numRows):
pas_tri = [[] for i in range(numRows)]
for i in range(numRows):
for j in range(i + 1):
if j == 0:
pas_tri[i].append(1)
elif j == i:
pas_tri[i].append(1)
else:
if i > 0:
pas_tri[i].append(pas_tri[i-1][j-1] + pas_tri[i-1][j])
return pas_tri |
c1468d5e32cd23adf86084120e1d3eecceddd55c | frimmy/LPTHW-exs | /ex14.py | 644 | 3.9375 | 4 | from sys import argv
script, user_name, user_ht = argv
what_say = '> '
print "Hi %s of %s, I'm the %s script." % (user_name, user_ht, script)
print " I'd like to ask you a few questions."
print "Do you like me %s of %s?" % (user_name, user_ht)
likes = raw_input(what_say)
print "Where do you live %s" % user_name
lives = raw_input(what_say)
print "What kind of computer do you have? And do they have them in %s" % user_ht
computer = raw_input(what_say)
print """
Alright, so you said %r about liking me.
You lives in %r. Not sure where that is..
And you have a %r computer. Nice. Have fun in the %s
""" % (likes, lives, computer, user_ht) |
f10c7c0742b6d9d971b1f62453faff84fd656636 | Phongwind002/baikiemtra | /bai3.py | 528 | 3.5 | 4 | def tinhgiaithua(n):
giaithua = 1;
if (n == 0 or n == 1):
return giaithua;
else:
for i in range(2, n + 1):
giaithua = giaithua * i;
return giaithua;
n = int(input("Nhập số nguyên dương n = "));
if (n<0):
print("Yêu cầu nhập lại số nguyên dương")
n = int(input("Nhập số nguyên dương n = "));
print("Giai thừa của", n, "là", tinhgiaithua(n));
else:
print("Giai thừa của", n, "là", tinhgiaithua(n)); |
fde6812d58c67a262948a43cd4f7e57975dd49cb | Szoul/Automate-The-Boring-Stuff | /Chapter 10/Organizing files.py | 2,947 | 3.640625 | 4 | import shutil, os
from pathlib import Path
dir1_path = Path("C:/Users/Acer PC/Desktop/Python/Automate-The-Boring-Stuff/Chapter 10/dir1")
dir2_path = Path("C:/Users/Acer PC/Desktop/Python/Automate-The-Boring-Stuff/Chapter 10/dir2")
filename = "a_moving_file_title.txt"
# shutil.copy(source, destination) copies a file (File_path, New_Directory_path [/new_filename])
# shutil.copytree(source, destination) will copy the whole folder, with anything it contains [or creates a new folder]
# if the file(name) already exists at destination it will overwrite the file
shutil.copy(dir1_path/filename, dir2_path/"wello, horld.txt")
# similar: shutil.move(source, destination)
# though be careful when moving to non-existing folders and with naming
# Deleting files with os
# os.unlink(Path) - delete file at path
# os.rmdir(Path) - delete an EMPTY folder at path
# os.rmtree(Path) - delete folder and its contents at path
''' ---> be careful with deleting files, better test with a simple [print(filename)] if you are targeting the right Path '''
dirname = Path("C:/Users/Acer PC/Desktop/Python/Automate-The-Boring-Stuff/Chapter 10/New_Directory/Even_Newer_Directory")
# os.makedirs(dirname)
# print (dirname)
# os.rmdir(dirname)
# print (dirname.parent)
# os.rmdir(dirname.parent)
''' alternative: sent2trash module (so files will get moved to trash instead of deleted permamently)'''
# using os.walk() to walk through a directory tree
# it returns the current folder name, its contents(subfolders + contents and files)
# cwd is not changed while running this function
for folderName, subfolders, filenames in os.walk(os.getcwd()):
print('\nThe current folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print('FILE INSIDE ' + folderName + ': '+ filename)
print ("")
print (list(os.walk(os.getcwd())))
print ("\n\n")
# compressing/creating an archive file with .zip with the zipfile module
import zipfile
cwd = Path("C:/Users/Acer PC/Desktop/Python/Automate-The-Boring-Stuff/Chapter 10")
exampleZip = zipfile.ZipFile(cwd/"example.zip")
print (exampleZip.namelist())
zip_info = exampleZip.getinfo("zip_file.txt")
print (zip_info.file_size)
print (zip_info.compress_size)
exampleZip.close()
# extract files
# exampleZip = zipfile.ZipFile(cwd/"example.zip")
# examleZip.extractall() // to current cwd or .extractall([directory])
# exampleZip.extract("[item in .namelist()], [directory/cwd])
# exampleZip.close()
# add files (new file, named <new.zip> with the contents of <a_random_file.txt>)
# newZip = zipfile.ZipFile("new.zip", "w") --> same as writing new files, "w" will replace, "a" will append
# newZip.write('a_random_file.txt', compress_type=zipfile.ZIP_DEFLATED)
# newZip.close() |
96d6cf3bc9777bb930d66426515b3acd487a815e | djangoearnhardt/Exercism | /luhn.py | 2,167 | 3.78125 | 4 | # Given a number, determine whether or not it is valid per Luhn formula
# Need at least two numbers, doubles every other digit from the right
# adds the two numbers of the double together to make new single digit
import numpy as np
print("Please enter a valid 16 digit CC#")
array = input()
counter = 0
max = 4
while array.isdigit() is False:
print("Please enter valid numbers")
array = input()
counter += 1
if counter == max:
print("You aren't cooperating, Goodbye...")
break
while len(array) < 15:
print("Please enter a valid 16 digit CC#")
array = input()
counter += 1
if counter == max:
print("You aren't cooperating, Goodbye...")
break
while len(array) > 16:
print("That's too many numbers, please enter a valid 16 digit CC#")
array = input()
counter += 1
if counter == max:
print("You aren't cooperating, Goodbye...")
break
# Give you 5 tries, then terminates the program
# Reverse array combined with turning strings to integers
array_rev = list(map(int, array[::-1]))
# print(array_rev)
# checks for AMEX 15 digit
if len(array_rev) == 15:
array_plucky = array_rev[1::2]
else:
# Takes every other for 16 digit
array_plucky = array_rev[::2]
# checks for AMEX 15 digit
if len(array_rev) == 15:
array_pluck = array_rev[::2]
else:
# Takes first and every other for 16 digit
array_pluck = array_rev[1::2]
# print(array_pluck)
# multiply removed numbers by 2
pluck_new = [2 * x for x in array_pluck]
# print(pluck_new)
# turn the double into single digits
pluck_minus = pluck_new.copy()
for i, v in enumerate(pluck_new):
if v >= 10:
pluck_minus[i] = v - 9
# WORKS but not necessary pluck_minus = [x - 9 for x in pluck_new]
# print(pluck_minus)
# interlace two arrays, zip() puts into tuples, then hstack joins them
pluck_joined = np.hstack(zip(array_plucky,pluck_minus))
#print(pluck_joined)
pj_rev = pluck_joined[::-1]
# print(pj_rev)
# find the sum of pluck_joined
sum = sum(pluck_joined)
# print(sum)
# check digit is sum * 9 mod 10
check_digit = (sum) % 10
# print(check_digit)
if check_digit == 0:
print("Your CC# is valid, please spend your savings.")
else:
print("That isn't a real CC#, we need cash from you.")
|
4e2ff85783c0c909b58e8e43a793700e4e3a9273 | FabioGUB/ExerciciosCursoEmVIdeo | /Ex040.py | 356 | 3.828125 | 4 | n1 = float(input('Nota da primeira prova: '))
n2 = float(input('Nota da segunda prova: '))
m = (n1 + n2) / 2
if m >= 7.0:
print('Parabéns você foi aprovado e já pode entrar de férias.')
elif m < 5.0:
print('Infelizmente você foi reprovado, estude mais.')
else:
print('Você está de recuperação, se esforce para passar de ano')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.