blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
799c1906da15ac1d452f3795901ac8c494769920 | shlee16/cit_shl | /20200722/variable.py | 363 | 3.65625 | 4 | santa = 80
rudolph = "giuliani"
print(santa +100)
print("rudolph" * 5)
santa = 800
print(santa)
name = "ryan"
print("Today's Diary by " + name )
print(name + " ate pancakes for morning")
print(name + " was not hungry")
print("Martha said Hi to " + name)
print(name + " got A+ on his exam.")
santa = santa + 300
santa -= 100 # santa = santa - 100
print(santa)
|
0497750dca9db0e6bb2f55a9790aee5f1b571a6f | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4144/codes/1800_2567.py | 151 | 3.75 | 4 | from numpy import *
a = int(input("digite o nro.: "))
for i in range(a):
print((a-i)*"*")
i = i - 1
for i in range(a+1):
print(i*"*")
i = i +1
|
8d3a345bbec06324517deb4c46e6c397c66af302 | FreeFlyXiaoMa/personal_project | /re_/test1.py | 1,006 | 3.734375 | 4 | #!/usr/bin/env python # -*- coding: utf-8 -*-
# @Author : Ma
# @Time : 2021/1/2 17:45
# @File : test1.py
# Input='aabcdbefgde'
#
# child_list=[]
# for i in range(len(Input)-1):
# for j in range(i+1,len(Input)):
# child_list.append(Input[i:j+1])
#
# list1=[]
# for k in child_list:
# if len(k) == len(set(k)):
# list1.append(k)
# del child_list
#
# hash_={}
# max_len=0
# for m in list1:
# hash_[m]=len(m)
# if len(m) > max_len:
# max_len=len(m)
#
# for key,val in hash_.items():
# if val == max_len:
# print(key)
class queue(object):
def __init__(self):
super(queue, self).__init__()
self.queue=[]
def push(self,x):
self.queue.append(x)
def pop(self):
if self.queue:
return self.queue.pop(0)
def length(self):
return len(self.queue)
queue=queue()
queue.push(2)
queue.push(3)
queue.push(19)
pop_val=queue.pop()
print('pop_val:',pop_val)
print('length:',queue.length())
|
9040f5ce7cd2c5061bd64eda2f1382957698c4f7 | vanch1n1/SoftUni-programming-projects-and-exercises | /Python-programming-fundamentals/functions_lecture/calcualte_reactangle_area.py | 186 | 3.890625 | 4 | def calculate_rectangle_area(width, height):
area = int(width * height)
return area
width = int(input())
height = int(input())
print(calculate_rectangle_area(width, height)) |
fdfb999efb42ecd020cb699359e30e7632a2de0e | Gijsbertk/afvinkblok1 | /5.21.py | 672 | 3.84375 | 4 | import random #importeert library
print('Je doet steen papier schaar, voor steen kies je 1 voor papier 2 en schaar 3') #print wat je moet doen
def main():
game() #roept functie aan
def game(): #functie
speler = int(input('Kies een nummer voor steen papier schaar: ')) #vraagt om functie
comp = random.randint(1, 3) # random getal wordt toegekend aan variabele
print(comp) #print varaiabele
while speler == comp: # als variabele gelijk is aan input
speler = int(input('Kies een nummer voor steen papier schaar: ')) #opnieuw
comp = random.randint(1, 3) # opnieuw
main()
#auteur gijsbert ekja
|
4de920758b2a75cf658d4e298a6fa07cfa9527d8 | Buorn/FDC | /Lista 2/L2_EX_5.py | 477 | 3.859375 | 4 | # -*- coding: cp1252 -*-
#UNIVERSIDADE DO ESTADO DO RIO DE JANEIRO - UERJ
#BRUNO BANDEIRA BRANDO
#LISTA 2: FUNDAMENTOS DA COMPURAO 2018/2
#EXERCCIO 5
a = float (input ('Digite a primeira nota:'))
b = float (input ('Digite a segunda nota:'))
c = float (input ('Digite a terceira nota:'))
m = (a + b + c)/3
dif = (12 - m)
if m >= 7:
print 'Aluno Aprovado'
elif m >= 4:
print 'Aluno em exame. Precisa de', dif, 'para ser aprovado'
else:
print 'Aluno reprovado'
|
8cf589d07f34ad6667e76428b5810550128d6e55 | GitXuY/data_analysis | /DataAnalysis/generate_dict.py | 221 | 3.578125 | 4 | # from itertools import zip
column = 1
column_name = []
while column !=199:
column_name.append(column)
column += 1
column_name2 = column_name
# print column2
zipped = zip(column_name, column_name2)
print(dict(zipped)) |
9e481265d0b9f5e87b861038752627063830dc83 | rolisz/examenfp | /213/UI/console.py | 371 | 3.734375 | 4 | __author__ = 'Roland'
def getNr(text="Dati un numar",max = 0):
while True:
try:
nr = int(input())
if nr not in range(1,max) and max != 0 :
print("Trebuie sa alegeti una din optiunile date")
else:
return nr
except TypeError:
print("Trebuie sa dati un numar intreg")
|
098ab54c7fb1fca74d2135a2b547c8cf7ced8c60 | SneakBug8/Python-tasks | /nod.py | 291 | 3.734375 | 4 | # Наименьшее общее кратное WIP
n1 = int(input())
n2 = int(input())
n = 0
while n==0:
t1=n1%n2
if t1==0:
if n1>n2:
print(n1)
elif n2>n1:
print(n2)
break
elif n1>n2:
n1=t1
elif n2>n1:
n2=t1
|
d6ac8a418ed26be6ca5bc4b57a6936457a8e6feb | Samie-mirghani/Python-Graphics | /Project 4.pyw | 4,978 | 4.3125 | 4 | #Project 4.pyw
#Shamsadean Mirghani
#This program will ask the user two draw two triangles and colors the
#the larger one red and will display the area under the triangles
#Where ever they are plotted
from graphics import *
import math
# Function to find the distance between two points
def distance(p1,p2):
x1= p1.getX()
x2= p2.getX()
y1= p1.getY()
y2= p2.getY()
x= x2-x1
y= y2-y1
d= math.sqrt(x**2 + y**2)
return d
# Function to find the area of the triangle
def area(s1, s2, s3):
s= (s1 + s2 + s3)/2
a= math.sqrt((s)*(s-s1)*(s-s2)*(s-s3))
return a
def main():
# Creates Graphic window to house other objects
win= GraphWin("Triangles", 600, 600)
# Set color to black
win.setBackground("pink")
# Sets coordinate system of window
win.setCoords(0, 0, 6, 6)
# Prompts the user to click three points
prompt= Text(Point(3, 0.5),
"Click the opposite edges to create a triangle")
# Draws the prompt in the window
prompt.draw(win)
# Accepts and draws the different points and then draws triangle 1
# in the window
p1= win.getMouse()
p1.draw(win)
p2= win.getMouse()
p2.draw(win)
p3= win.getMouse()
T1= Polygon(p1, p2, p3)
T1.setFill("cornflower blue")
T1.draw(win)
# Reuses the prompt and asks the user to click three more places
prompt.setText("Click the opposite"
" edges to create another triangle")
# Accepts and draws the different prompts and then draws another
# triangle in the window
p_1= win.getMouse()
p_1.draw(win)
p_2= win.getMouse()
p_2.draw(win)
p_3= win.getMouse()
T2= Polygon(p_1, p_2, p_3)
T2.setFill("cornflower blue")
T2.draw(win)
# Calling distance function for traingle 1
side_1= distance(p1,p2)
side_2= distance(p2, p3)
side_3= distance(p3, p1)
# Calling distance function for triangle 2
side_4= distance(p_1, p_2)
side_5= distance(p_2, p_3)
side_6= distance(p_3, p_1)
# Calls the area function twice for each area
area_1= area(side_1, side_2, side_3)
area_2= area(side_4, side_5, side_6)
# Reuses the prompt to ask the user to click to color the larger
# triangle red
prompt.setText("Click to change the color of the larger"
" one to red")
win.getMouse()
# If statements to determine which one should be colored red
if area_1 > area_2:
T1.setFill("red")
else:
T2.setFill("red")
# Saves the coordinates as variables
x1= p1.getX()
y1= p1.getY()
x2= p2.getX()
y2= p2.getY()
x3= p3.getX()
y3= p3.getY()
# To find left-most point
if x1<x2 and x1<x3:
leftx = x1
elif x2<x1 and x2<3:
leftx = x2
elif x3<x1 and x3<x2:
leftx = x3
# To find the right-most point
if x1>x2 and x1>x3:
rightx = x1
elif x2>x1 and x2>x3:
rightx = x2
elif x3>x1 and x3>x2:
rightx = x3
# Find the center of the triangle
X1 = (leftx + rightx)/2
# To find the bottom of the triangle
if y1<y2 and y1<y3:
bottom = y1
elif y2<y1 and y2<y3:
bottom = y2
elif y3<y1 and y3<y2:
bottom = y3
Y1 = bottom - 0.5
# Saves all the coordinates as variables
x4= p_1.getX()
y4= p_1.getY()
x5= p_2.getX()
y5= p_2.getY()
x6= p_3.getX()
y6= p_3.getY()
# To find left-most point
if x4<x5 and x4<x6:
leftx = x4
elif x5<x4 and x5<6:
leftx = x5
elif x6<x4 and x6<x5:
leftx = x6
# To find the right-most point
if x4>x5 and x4>x6:
rightx = x4
elif x5>x4 and x5>x6:
rightx = x5
elif x6>x4 and x6>x5:
rightx = x6
# Find the center of the triangle
X2 = (leftx + rightx)/2
# To find the bottom of the triangle
if y4<y5 and y4<y6:
bottom = y4
elif y5<y4 and y5<y6:
bottom = y5
elif y6<y4 and y6<y5:
bottom = y6
Y2 = bottom - 0.5
# Creates two new prompts and displays the area of both triangles
prompt2= Text(Point(X1, Y1), 'The area of this triangle is: '
'{0:0.2f} units'.format(area_1))
prompt2.draw(win)
prompt3= Text(Point(X2, Y2), 'The area of this triangle is: '
'{0:0.2f} units'.format(area_2))
prompt3.draw(win)
# If statements used to color the text of the larger triangle
if area_1 > area_2:
prompt2.setTextColor("red")
else:
prompt3.setTextColor("red")
# Undraws the previous prompt and reuses another prompt and changes
# the color of the text
prompt.undraw()
prompt.setText("Click in the window to exit program")
prompt.setTextColor("red")
prompt.setStyle("bold")
prompt.draw(win)
# Closes the window and exits the program
win.getMouse()
win.close()
main()
|
22a57dfde9ead8c1a8d60a3b54f134e245e95870 | pavelneda/Lab2 | /task2_6.py | 1,642 | 3.703125 | 4 | class Node:
price=[]
def __init__(self, data,quantity):
self.left = None
self.right = None
self.data = data
self.quantity=quantity
def set_price(self,*prices):
Node.price.append(None)
for price in prices:
if not(isinstance(price,(int,float)) and price>0):
raise ValueError
Node.price.append(price)
def insert(self, data,quantity):
if self.data:
if data < self.data:
if not self.left:
self.left = Node(data,quantity)
else:
self.left.insert(data,quantity)
elif data > self.data:
if not self.right:
self.right = Node(data,quantity)
else:
self.right.insert(data,quantity)
else:
self.data = data
self.quantity=quantity
def inorderTraversal(self, root):
res = []
if root:
res = self.inorderTraversal(root.left)
res.append(root.quantity*Node.price[root.data])
res = res + self.inorderTraversal(root.right)
return res
try:
code, qty = map(int, input().split())
if not(0<code<=10 and qty>0):
raise ValueError
root = Node(code,qty)
root.set_price(1,2,3,4,5,6,7,8,9,10)
for i in range(4):
code, qty = map(int, input().split())
if not(0<code<=10 and qty>0):
raise ValueError
root.insert(code,qty)
print(root.inorderTraversal(root))
except ValueError:
print("Value error")
|
fcd9c69701372c6b66e0588e41ab6f9f7259d567 | mixterjim/Learn | /Python/Basics/16 Subclass.py | 424 | 3.609375 | 4 | class Animal(object):
def run(self):
print('Animal is runing...')
Animal().run()
class Dog(Animal): # Inherit form Animal
def run(self):
print('Dog is running...')
Dog().run()
class Cat(Animal):
def run(self):
print('Cat is running...')
def sleep(self):
print('Cat is sleeping...')
cat = Cat()
cat.run()
def sleeping(f_animal):
f_animal.sleep()
sleeping(Cat())
|
ed2cf23aa4585706fd4176bc51ba1851d0d37a1f | swang2000/BinaryTree | /reverselevelordertraversal.py | 1,060 | 4.09375 | 4 | '''
Reverse Level Order Traversal
2.4
We have discussed level order traversal of a post in previous post. The idea is to print last level first, then second
last level, and so on. Like Level order traversal, every level is printed from left to right.
Example Tree
Example Tree
Reverse Level order traversal of the above tree is “4 5 2 3 1”.
Both methods for normal level order traversal can be easily modified to do reverse level order traversal.
'''
import CdataS.BT.BianrySearchTree as tree
def rlot(root):
q = []
t = []
s = []
temp_node = root
while temp_node:
s.append(temp_node.value)
if temp_node.right_child:
q.append(temp_node.right_child)
if temp_node.left_child:
q.append(temp_node.left_child)
if len(q) >0:
temp_node = q.pop(0)
else:
break
while len(s) >0:
t.append(s.pop())
return t
bst = tree.BST()
bst.insert(5)
bst.insert(3)
bst.insert(2)
bst.insert(2.5)
bst.insert(4)
bst.insert(8)
bst.insert(6)
rlot(bst.root)
|
146ccd212b13b9061cf16303166f0b55f8f21908 | LXYykdf/ichw | /pyassign2/currency.py | 4,555 | 4.09375 | 4 | '''
currency.py:
Module for currency exchange
This module provides several string parsing functions to implement a
simple currency exchange routine using an online currency service.
The primary function in this module is exchange.
Returns: amount of currency received in the given exchange.
__author__='Liuxinyi'
__pkuid__ ='1800011815'
__email__ ='1800011815@pku.edu.cn'
'''
from urllib.request import urlopen
def currency_response(currency_from,currency_to,amount_from):
'''
Returns: a JSON string that is a response to a currency query.
A currency query converts amount_from money in currency currency_from
to the currency currency_to. The response should be a string of the form
'{"from":"<old-amt>","to":"<new-amt>","success":true, "error":""}'
where the values old-amount and new-amount contain the value and name
for the original and new currencies. If the query is invalid, both
old-amount and new-amount will be empty, while "success" will be followed
by the value false.
Parameter currency_from: the currency on hand
Precondition: currency_from is a string
Parameter currency_to: the currency to convert to
Precondition: currency_to is a string
Parameter amount_from: amount of currency to convert
Precondition: amount_from is a float
'''
st = 'http://cs1110.cs.cornell.edu/2016fa/a1server.php?from='+\
currency_from + '&to=' + currency_to + '&amt=' + str(amount_from)
doc = urlopen(st)
docstr = doc.read()
doc.close()
jstr = docstr.decode('ascii')
return jstr
def iscurrency(currency):
'''
Returns: True if currency is a valid (3 letter code for a) currency.
It returns False otherwise.
Parameter currency: the currency code to verify
Precondition: currency is a string.
'''
response = currency_response(currency,'USD',5)
string = response.split('"')
if string[10] == ' : true, ':
return True
else:
return False
def exchange(currency_from,currency_to,amount_from):
'''
In this exchange, the user is changing amount_from money in
currency currency_from to the currency currency_to. The value
returned represents the amount in currency currency_to.
Parameter currency_from: the currency on hand;
Precondition: currency_from is a string for a valid currency code;
Parameter currency_to: the currency to convert to;
Precondition: currency_to is a string for a valid currency code;
Parameter amount_from: amount of currency to convert;
Precondition: amount_from is a float.
The value returned has type float.
'''
if iscurrency(currency_from) and iscurrency(currency_to):
response = currency_response(currency_from,currency_to,amount_from)
string = response.split('"')
amount_out = string[7]
out = amount_out.split(' ')
output = out[0]
return (float(output))
else:
response = currency_response(currency_from,currency_to,amount_from)
string = response.split('"')
return string[-2]
def test_currency_response():
'''
Unit test for module exchange
When run as a script, this module invokes several procedures that
test the function currency_response.
'''
assert(currency_response('USD','EUR',2) == '{ "from" : "2 United States Dollars", "to" : "1.727138 Euros", "success" : true, "error" : "" }')
assert(currency_response('s','s',8) == '{ "from" : "", "to" : "", "success" : false, "error" : "Source currency code is invalid." }')
assert(currency_response('USD','CNY',1) == '{ "from" : "1 United States Dollar", "to" : "6.8521 Chinese Yuan", "success" : true, "error" : "" }')
def test_iscurrency():
'''
Unit test for module exchange
When run as a script, this module invokes several procedures that
test the function iscurrency.
'''
assert(iscurrency('USD') is True)
assert(iscurrency('s') is False)
assert(iscurrency('CNY') is True)
def test_exchange():
'''
Unit test for module exchange
When run as a script, this module invokes several procedures that
test the function exchange.
'''
assert(exchange('USD','EUR',2) == 1.727138)
assert(exchange('s','s',8) == 'Source currency code is invalid.')
assert(exchange('USD','CNY',1) == 6.8521)
def testALL():
'''Test all cases.'''
test_currency_response()
test_iscurrency()
test_exchange()
print('All tests passed')
def main():
'''
main module
'''
currency_from = input('请输入起始货币英文简称:')
currency_to = input('请输入目标货币英文简称:')
amount_from = float(input('请输入起始货币金额:'))
print(exchange(currency_from,currency_to,amount_from))
testALL()
if __name__ == '__main__':
main()
|
c3228b54787ee6ba20de92d89ad475123bec3fa2 | rmopia/tokenize-parse-stackmachine | /stack_machine.py | 2,822 | 3.6875 | 4 | class StackMachine:
def __init__(self):
self.stack = []
self.currentLine = 0 # numerical iterator used during driver program
self.lst = [None] * 15 # empty list that will be used during the save and get functions
def push(self, value):
self.stack.append(int(value)) # string 'value' is casted as an integer into the stack to support stack operations
return None
def pop(self):
if len(self.stack) == 0: # if the stack is empty
raise IndexError("Invalid Memory Access")
else:
return self.stack.pop()
def add(self):
v1 = self.pop()
v2 = self.pop()
self.push(int(v1) + int(v2))
return None
def sub(self):
v1 = self.pop()
v2 = self.pop()
self.push(int(v1) - int(v2))
return None
def mul(self):
v1 = self.pop()
v2 = self.pop()
product = int(v1) * int(v2)
self.push(product)
return None
def div(self):
v1 = self.pop()
v2 = self.pop()
quotient = int(v1) / int(v2)
self.push(quotient)
return None
def mod(self):
v1 = self.pop()
v2 = self.pop()
self.push(int(v1) % int(v2))
return None
def skip(self): # increments currentLine iterator if the first popped value is zero (note: currentLine will still increment + 1 outside)
v1 = self.pop()
v2 = self.pop()
if v1 == 0:
self.currentLine += v2
return None
return None
def save(self, index): # saves popped value and is put into the specified index
self.lst[int(index)] = self.pop()
return None
def get(self, index): # gets a saved popped value from the specified index
got = self.lst[int(index)]
if got is None: # if the index specified doesn't return a value
raise IndexError("Invalid Memory Access")
else:
self.push(got)
return None
def execute(self, tokens): # takes a tokenized & parsed list from a list of lists from the driver program and starts required behavior
if tokens[0] == "push":
return self.push(tokens[1])
elif tokens[0] == "pop":
return self.pop()
elif tokens[0] == "add":
return self.add()
elif tokens[0] == "sub":
return self.sub()
elif tokens[0] == "mul":
return self.mul()
elif tokens[0] == "div":
return self.div()
elif tokens[0] == "mod":
return self.mod()
elif tokens[0] == "skip":
return self.skip()
elif tokens[0] == "save":
return self.save(tokens[1])
else:
return self.get(tokens[1])
|
cc759059428814b9ebedefe4a2fdc45446b81fea | PedroPaAl/EjerciciosPyPedro | /5.Ejercicios Ficheros/Ficheros 2.py | 242 | 3.71875 | 4 | prompt = '> '
print("Introduzca un numero")
numero = int(input(prompt))
try:
f = open("tabla-%d.txt"%numero, "r")
for i in range(11):
print(f.readline())
f.close()
except IOError:
print("El archivo no existe") |
cd3566af2cdde0776ba9709754d9252d3c6b7ac3 | Akshat111999/Python | /GUI/labels.py | 256 | 4.09375 | 4 | from tkinter import *
root = Tk() #creates a root window
Label(root, text="First Label").pack() #.pack() method is used to organise the blocks in rows and columns
root.mainloop() # it is an infinite loop and this method is used to run the application
|
ed39c3cba97c3652f9e94383135ef590bca343e5 | robertoweller/GUI-Chess-Implementation-in-Python | /Data_Conversion/difference_for_letter.py | 326 | 3.828125 | 4 | '''
This is to convert letters to numbers when calculations occur
'''
dictionar_of_letters_to_numbers = {
'a': 1, 'b': 2, 'c': 3, 'd':4, 'e': 5, 'f': 6, 'g':7, 'h': 8
}
'''
This is to save the corrdinates of where the user pressed, in order
to promote the pawn to the correct piece
'''
promotion_piece = []
|
30a2a5110947d77e08fe7f2aef644af5b887a72d | liangqiding/python-milestone | /04高级特性/2迭代.py | 324 | 3.9375 | 4 | # 迭代
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
# 判断是否可迭代
from collections.abc import Iterable
print('判断是否可迭代:',isinstance(d, Iterable) )
# Python内置的enumerate函数可以把一个list变成索引-元素对
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
|
14a355ed3fc9f249ad2668e12d4ad3278fafaa92 | karma-19/Algorithm-Visulizers | /bubblesort_visualizer.py | 1,872 | 4 | 4 | import pygame, sys, random
""" PYGAME PRACTICE
PROJECT NAME : BUBBLE SORT VISUALIZER
CREATED ON 08/21/2020 """
pygame.init()
#screen window
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH , HEIGHT))
#caption
pygame.display.set_caption('BUBBLE SORT - PRAVEEN VISHWAKARMA ')
#icon
#icon = pygame.image.load("C:/Users/LG/Desktop/college/pygame_icon.png")
#pygame.display.set_icon(icon)
#clock
clock = pygame.time.Clock()
#bar width
n = 8
w = WIDTH//n
height_arr = []
#color changing array
c_c = []
for i in range(w):
height_arr.append(random.randint(10, 550))
c_c.append(1)
counter = 0
while True:
#screen background
screen.fill((3, 252, 185))
#sorting
if counter<len(height_arr):
for j in range(len(height_arr)-1-counter):
if height_arr[j]>height_arr[j+1]:
c_c[j] = 0
c_c[j+1] = 0
temp = height_arr[j]
height_arr[j] = height_arr[j+1]
height_arr[j+1] = temp
else:
c_c[j] = 1
c_c[j+1] = 1
counter+=1
#changing color c_c array implementation
if len(height_arr)-counter >= 0:
c_c[len(height_arr)-counter] = 2
#printing the bar on the screen
for i in range(len(height_arr)):
if c_c[i] == 0:
color = (255, 0, 0)
elif c_c[i] == 2:
color = (52,174, 235)
else:
color = (235, 215, 52)
pygame.draw.rect(screen, color, (i*n, HEIGHT-height_arr[i], n, height_arr[i]))
#event
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
clock.tick(10)
pygame.display.update()
|
e33dda0d91628fcb0a7b5202695ce52ac02cfff1 | vovo1234/pepelats | /games/tiltedtowers/town.py | 3,355 | 3.859375 | 4 |
import turtle
def draw_house_anya( x, y, size, house_color, roof_color, door_color ):
# Move turtle to where we want to draw
turtle.up( )
turtle.setpos( x - size / 2.0, y )
turtle.setheading( 0 )
turtle.down( )
# draw box
turtle.color( house_color )
turtle.begin_fill()
for x in range(0,4):
turtle.forward( 100 * size / 100.0 )
turtle.left(90)
turtle.end_fill()
# move to the roof initial position
for x in range(0,2):
turtle.forward( 100 * size / 100.0 )
turtle.left(90)
# draw roof
turtle.color( roof_color )
turtle.begin_fill()
turtle.right(45)
turtle.forward( 70.71067811865475 * size / 100.0 )
turtle.left(90)
turtle.forward( 70.71067811865475 * size / 100.0 )
turtle.end_fill()
# go to the door
turtle.up( )
turtle.left(45)
turtle.forward(100 * size / 100.0)
turtle.left(90)
turtle.forward(33.333 * size / 100.0)
turtle.down( )
# draw door
turtle.color( door_color )
turtle.begin_fill()
turtle.left(90)
turtle.forward(65 * size / 100.0)
turtle.right(90)
turtle.forward(33.333 * size / 100.0)
turtle.right(90)
turtle.forward(65 * size / 100.0)
turtle.end_fill()
def draw_house_lex( x, y, size, house_color, roof_color, door_color ):
# Move turtle to where we want to draw
turtle.up( )
turtle.setpos( x - size / 2.0, y )
turtle.setheading( 0 )
turtle.down( )
turtle.color( house_color )
turtle.begin_fill( )
for x in range (0,6):
turtle.forward(100 * size / 100.0)
turtle.left(90)
turtle.end_fill( )
turtle.color( roof_color )
turtle.begin_fill( )
turtle.right(45)
turtle.forward(70 * size / 100.0)
turtle.left(90)
turtle.forward(71 * size / 100.0)
turtle.end_fill( )
turtle.up()
turtle.left(45)
turtle.forward(20 * size / 100.0)
turtle.left(90)
turtle.forward(20 * size / 100.0)
turtle.down()
turtle.color( roof_color, 'white' )
turtle.begin_fill( )
for x in range (0,4):
turtle.forward(60 * size / 100.0)
turtle.right(90)
turtle.forward(30 * size / 100.0)
turtle.right(90)
turtle.forward(60 * size / 100.0)
turtle.end_fill( )
def draw_house( x, y, size, type, house_color, roof_color, door_color ):
if type == 'anya':
draw_house_anya( x, y, size, house_color, roof_color, door_color )
if type == 'lex':
draw_house_lex( x, y, size, house_color, roof_color, door_color )
# Calculates on-screen scale from the world coordinates
def world_to_scale( x, y ):
k = 0.05
return (y + 100 ) * k
# World coordinates to screen. World visible area is approximatesly -50 to 50
# both x and y, y is pointed towards the camera
def world_to_screen( x, y ):
scale = world_to_scale( x, y )
x_screen = int( x * scale )
y_screen = int( -50 * scale ) + 200
return ( x_screen, y_screen )
def draw_field( ):
# green field!
turtle.up( )
turtle.setpos( world_to_screen( -55, -55 ) )
turtle.color( 'darkgreen' )
turtle.begin_fill( )
turtle.setpos( world_to_screen( -55, 55 ) )
turtle.setpos( world_to_screen( 55, 55 ) )
turtle.setpos( world_to_screen( 55, -55 ) )
turtle.setpos( world_to_screen( -55, -55 ) )
turtle.end_fill( )
|
2057806d53f725f04a31d73929804535e97e2d26 | cunyu1943/python-programming-instance | /src/4.py | 890 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @version : 1.0
# @Time : 2021/3/31 19:30
# @Author : cunyu
# @Email : 747731461@qq.com
# @Site : https://cunyu1943.site
# 公众号 : 村雨遥
# @File : 4.py
# @Software: PyCharm
# @Desc : 练习实例4
if __name__ == '__main__':
list1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
list2 = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
while True:
year = int(input('输入年份:'))
month = int(input('输入月份:'))
day = int(input('输入日期:'))
sum = 0
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
for i in range(month - 1):
sum += list2[i]
sum += day
else:
for i in range(month - 1):
sum += list1[i]
sum += day
print('这是第 %d 天' % sum)
|
e5a5ce550e9273ecde8f143880cfad55f1461aa9 | HuebnerC/DSIassignments | /DSI/OOP_pair_assigment.py | 4,177 | 3.796875 | 4 | from fractions import Fraction
class Polynomial():
# from fractions import Fraction
def __init__(self, lst):
self.lst = lst
self.degree = len(lst) - 1
def __repr__(self):
return f'Polynomial({self.lst})'
def __str__(self):
poly_lst = []
pol_str = ''
# build list of polynomial terms
for count, i in enumerate(self.lst):
if i == 0:
continue
elif i == 1 or i == -1:
if count == 0:
poly_lst.append(str(i))
elif count == 1:
poly_lst.append('x')
else:
poly_lst.append('x^' + str(count))
else:
if count == 0:
poly_lst.append(str(i))
elif count == 1:
poly_lst.append(str(i) + 'x')
else:
poly_lst.append(str(i) + 'x^' + str(count))
# reverse poly_lst and build polynomial string to return
poly_lst.reverse()
for count, i in enumerate(poly_lst):
if i[0] == '-' and count == 0:
pol_str += i
elif i[0] == '-' and count > 0:
pol_str += ' - ' + i[1:]
elif count == 0:
pol_str += i
else:
pol_str += ' + ' + i
# return the string
return pol_str
def evaluate(self, num):
ev = 0
for count, i in enumerate(self.lst):
ev += i * num ** count
return ev
def __add__(self, other):
# compare list length
add_lst = []
p1 = len(self.lst)
p2 = len(other.lst)
len_diff = abs(p1 - p2)
# if input list lengths vary, insert 0s into the shorter list to make the same len
if p1 > p2:
other.lst.insert(len(other.lst), 0 * len_diff)
elif p1 < p2:
self.lst.insert(len(self.lst), 0 * len_diff)
for a, b in zip(self.lst, other.lst):
add_lst.append(a + b)
return Polynomial(add_lst)
def __sub__(self, other):
# compare list length
sub_lst = []
p1 = len(self.lst)
p2 = len(other.lst)
len_diff = abs(p1 - p2)
# if input list lengths vary, insert 0s into the shorter list to make the same len
if p1 > p2:
other.lst.insert(len(other.lst), 0 * len_diff)
elif p1 < p2:
self.lst.insert(len(self.lst), 0* len_diff)
for a, b in zip(self.lst, other.lst):
sub_lst.append(a - b)
return Polynomial(sub_lst)
def __neg__(self):
neg_lst = []
for i in self.lst:
neg_lst.append(-i)
return Polynomial(neg_lst)
def __eq__(self, other):
eq_lst = []
other_lst = []
for i in self.lst:
if i == 0:
continue
else:
eq_lst.append(i)
for j in other.lst:
if j == 0:
continue
else:
other_lst.append(j)
if eq_lst == other_lst:
return True
else:
return False
def __mul__(self, other):
prod_dict = {}
prod_lst = []
for count_i, i in enumerate(self.lst):
for count_j, j in enumerate(other.lst):
if count_i + count_j not in prod_dict:
prod_dict[count_i + count_j] = i * j
else:
prod_dict[count_i + count_j] += i * j
for k in prod_dict:
prod_lst.append(prod_dict[k])
return Polynomial(prod_lst)
def differentiate(self):
deriv_lst = []
for count, i in enumerate(self.lst):
deriv_lst.append(i * count)
deriv_lst.pop(0)
return Polynomial(deriv_lst)
def integrate(self):
integ_lst = ['C']
for count, i in enumerate(self.lst):
integ_lst.append(Fraction(i,(count + 1)))
return Polynomial(integ_lst)
|
3c7c38312ec37f7308c092b5f5291ca842598ed9 | nishantchaudhary12/Leet_Code | /Python/437_pathSumIII.py | 1,227 | 3.78125 | 4 | '''You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.ans = 0
def pathSum(self, root: TreeNode, sum: int) -> int:
def _iterate(node, prevSum, target):
if not node:
return
currSum = prevSum + node.val
if currSum - target in cache:
self.ans += cache[currSum - target]
if currSum in cache:
cache[currSum] += 1
else:
cache[currSum] = 1
_iterate(node.left, currSum, sum)
_iterate(node.right, currSum, sum)
cache[currSum] -= 1
cache = {0: 1}
if root:
_iterate(root, 0, sum)
return self.ans
|
07c203e961cfad85d42fb87433c20cb7ff10ff40 | rexshang/hackerrank | /apple_and_orange.py | 644 | 3.53125 | 4 | '''
Created on Nov 8, 2016
@author: erexsha
'''
#!/bin/python
import sys
def count_fruit(s, t, tree, fruit):
count = 0
for i in fruit:
dist = i + tree
if dist >= s and dist <= t:
count = count + 1
return count
s,t = raw_input().strip().split(' ')
s,t = [int(s),int(t)]
a,b = raw_input().strip().split(' ')
a,b = [int(a),int(b)]
m,n = raw_input().strip().split(' ')
m,n = [int(m),int(n)]
apple = map(int,raw_input().strip().split(' '))
orange = map(int,raw_input().strip().split(' '))
print count_fruit(s, t, a, apple)
print count_fruit(s, t, b, orange)
|
4800e5d119ca9e1dfbf52b248f867939d0abd7e6 | camalot2011/data-science | /Python/py4e/Assignment3_3.py | 330 | 4.0625 | 4 | # Printing scores
score = input("Enter Score:")
try:
sc = float(score)
if sc>=0.9:
grade = "A"
elif sc>=0.8:
grade = "B"
elif sc>=0.7:
grade = "C"
elif sc>=0.6:
grade = "D"
elif sc<0.6:
grade = "F"
print(grade)
except:
print("Score is out of range!")
|
ca4779d7a2281d1c6ab3a85f33817a77ac35fbff | vuminhdiep/c4t--20 | /session1/session2/session7/capitalize_print.py | 113 | 3.828125 | 4 | items = ["Sport", "LOL", "BTS", "Death Note", "Netflix"]
for i in range(len(items)):
print(items[i].upper())
|
1d874547a537f0f13457b71182d7a6224bccd42d | harshi93/jupyterNotebooks | /Python-Practice/30-days-of-code/bubble-sort.py | 543 | 4.28125 | 4 | array = [8,5,2,9,5,6,3]
def bubbleSort(array):
# Write your code here.
array_length = len(array) - 1
for i in range(0, array_length):
j = i + 1
item1 = array[i]
item2 = array[j]
swapped = False
if (item1 > item2):
array[i] = item2
array[j] = item1
item1 = 0
item2 = 0
swapped = True
if (swapped == True):
bubbleSort(array)
return array
bubbleSort(array)
array = bubbleSort(array)
print(array)
|
22c4f6423784c80714d0910323a02831ba379782 | RyanHiatt/Becca_HW | /HW4/HW4b-stem.py | 4,038 | 4.125 | 4 | import numpy as np
import matplotlib.pyplot as pyplot
from scipy import linalg
from math import *
def RSquared(x, y, a):
'''
To calculate the R**2 value for a set of x,y data and a LeastSquares fit with polynomial having coefficients a
:param x:
:param y:
:param a:
:return:
'''
AvgY = np.mean(y) # calculates the average value of y
SSTot = 0
SSRes = 0
for i in range(len(y)):
SSTot += (y[i] - AvgY)**2
SSRes += (y[i] - Poly(x[i], a))**2
RSq = 1 - SSRes / SSTot
return RSq
def Poly(x, a):
'''
calculates the value for a polynomial given a value for x and the coefficients of the polynomial.
f(x)=y=a[0]+a[1]x+a[2]x**2+a[3]x**3+...
:param x: the x value for calculating the function
:param a: the coefficients of the polynomial
:return:
'''
y = 0
for i in range(len(a)):
y += a[i] * x**i
return y
def LeastSquares(x, y, power):
'''
Calculates the coefficients for a polynomial of degree power to best
fit a data set (x,y) using the least squares approach.
:param x: the independent variable of the data set
:param y: the value of the function evaluated at each value of x
:param power: the degree of the polynomial
:return: the array of coefficients (i.e., f(x)=a[0]+a[1]x+a[2]x**2+...)
'''
return np.polyfit(x, y, power)
def PlotLeastSquares(x, y, power, showpoints=True, npoints=500):
Xmin = min(x)
Xmax = max(x)
Ymin = min(y)
Ymax = max(y)
dX = 1.0 * (Xmax - Xmin) / npoints
a = LeastSquares(x, y, power) # calculate the coefficients of the fitting polynomial
xvals = np.linspace(Xmin, Xmax, len(x)) # &MISSING CODE HERE&#) #build the numpy array of xvals
yvals = np.polyval(a, xvals)
RSq = RSquared(x, y, a) # calculate an R^2 value
pyplot.plot(xvals, yvals, linestyle='dashed', color='black', linewidth='2')
pyplot.title(r'$R^2={:0.3f}$'.format(RSq))
pyplot.xlim(floor(Xmin * 10) / 10, ceil(Xmax * 10) / 10)
pyplot.ylim(floor(Ymin), ceil(Ymax * 10) / 10)
if showpoints:
pyplot.plot(x, y, linestyle='none', marker='o', markerfacecolor='white', markeredgecolor='black', markersize=10)
pyplot.xlabel('X values')
pyplot.ylabel('Y values')
pyplot.show()
return xvals, yvals
def main():
x = np.array([0.05, 0.11, 0.15, 0.31, 0.46, 0.52, 0.70, 0.74, 0.82, 0.98, 1.17])
y = np.array([0.956, 1.09, 1.332, 0.717, 0.771, 0.539, 0.378, 0.370, 0.306, 0.242, 0.104])
# 1. Call LeastSquares for a linear fit
ans1 = LeastSquares(x, y, 1)
print(ans1)
# 2. Call PlotLeastSquares for a linear fit
linx, liny = PlotLeastSquares(x, y, 1, showpoints=True, npoints=500)
RSqLin = RSquared(x, y, ans1) # calculate RSqured for linear fit
# 3. Call LeastSquares for a Cubic fit
ans2 = LeastSquares(x, y, 3)
RSqCub = RSquared(x, y, ans2) # calculate RSquared for cubic fit
print(ans2)
# 4. Call PlotLeastSquares for a Cubic fit
cubx, cuby = PlotLeastSquares(x, y, 3, showpoints=True, npoints=500)
# 5. Use results form 1 and 3 to plot the data points, the Linear fit and the Cubic fit all on one graph
pyplot.plot(linx, liny, linewidth=2, linestyle='dashed', color='black', label=r'Linear fit ($R^2={:0.3f}$)'.format(RSqLin)) #for the linear fit
pyplot.plot(cubx, cuby, linewidth=2, linestyle='dotted', color='black', label='Cubic fit ($R^2={:0.3f}$)'.format(RSqCub)) #for the cubic fit
pyplot.plot(x, y, linestyle='none', marker='o', markersize=10, markerfacecolor='white', markeredgecolor='black', label='Data') # the data points
pyplot.xlabel('X values')
pyplot.ylabel('Y values')
pyplot.legend()
pyplot.grid(axis='both')
pyplot.tick_params(axis='both', direction='in', grid_linewidth=1, grid_linestyle='dashed', grid_alpha=0.5)
pyplot.show()
x=np.array([[10, 20, 30], [40, 50, 60]])
y=np.array([[100], [200]])
print(np.append(x, y, axis=1))
# Use proper titles, labels and legends
main()
|
6bfd62a136462c01f5f28fa402b4abec0f42e7c6 | germandouce/AyP-1 | /Parciales/2021-C1-P1/ejercicio3 hecho en clase por franco.py | 4,981 | 4.125 | 4 |
MENU = {
"Baguette Clásica": 250,
"Baguette Rellena": 350,
"Baguette Vegana": 250,
"Baguette con Muzzarella (a la pizza)": 500,
"Merlot": 300,
"Vin rosé": 300,
"Borgoña blanc": 550
}
def altaCliente(clientes, dni_cliente):
nombre = input("Ingrese su nombre: ")
apellido = input("Ingrese su apellido: ")
clientes[dni_cliente] = nombre + " " + apellido
def mostrar_opciones_pedidos():
print("\nLista de productos")
for producto in MENU:
print(f"{producto}: ${MENU[producto]}")
def ingreso_pedido():
mostrar_opciones_pedidos()
producto_elegido = input("\nIngrese el nombre del producto: ")
cantidad = int(input("Ingrese la cantidad: "))
precio = cantidad * MENU[producto_elegido]
return (producto_elegido, cantidad, precio)
def agregar_pedido_a_compras(dni, compras):
pedido = ingreso_pedido()
if dni in compras:
compras[dni].append(pedido)
else:
compras[dni] = [pedido]
def realizar_pedido(clientes, compras):
dni_ingresado = int(input("Ingrese su DNI: "))
if dni_ingresado not in clientes:
altaCliente(clientes, dni_ingresado)
# dni_ingresado existe en clientes
seguir_pidiendo = True
while seguir_pidiendo:
agregar_pedido_a_compras(dni_ingresado, compras)
opcion_seguir_pidiendo = input("\nDesea agregar otro pedido? (S/N)")
if opcion_seguir_pidiendo != "S":
seguir_pidiendo = False
def ingresar_pago(pagos):
"""Asumo que el dni ingresado va a estar en la lista de clientes"""
dni = int(input("Ingrese su dni: "))
pago_actual = int(input("Ingrese el monto a pagar: "))
if dni in pagos:
pagos[dni].append(pago_actual)
else:
pagos[dni] = [pago_actual]
def actualizar_deudas(deudas, compras, pagos):
for dni_cliente in compras:
deuda_actual = 0
if dni_cliente in compras:
for pedido in compras[dni_cliente]:
deuda_actual += pedido[2]
if dni_cliente in pagos:
for pago in pagos[dni_cliente]:
deuda_actual -= pago
deudas[dni_cliente] = deuda_actual
def ranking_deudas(clientes, deudas) -> None:
"""
Muestra por pantalla el ranking de mayores deudoras hasta un maximo de 5.
:param clientes: diccionario que contiene los clientes del sistema
:param deudas: diccionario que contiene las deudas
:return: None
"""
lista_deudas = [] # [ [DEUDA, NOMBRE+APELLIDO] ]
for dni_cliente in deudas:
lista_deudas.append([deudas[dni_cliente], clientes[dni_cliente]])
lista_deudas.sort(reverse=True)
print("\nEl ranking de deudores es")
cantidad_maxima = 5 if (len(lista_deudas) > 5) else len(lista_deudas)
for i in range(cantidad_maxima):
print(f"{lista_deudas[i][1]} : ${lista_deudas[i][0]}")
def reporte_pedidos(pedidos):
dict_products = {}
for dni_cliente in pedidos:
for pedido in pedidos[dni_cliente]:
nombre_producto = pedido[0]
if nombre_producto in dict_products:
dict_products[nombre_producto] += 1
else:
dict_products[nombre_producto] = 1
for producto in dict_products:
print(f"{producto} - {dict_products[producto]}")
def pedidos_superiores_a(pedidos, monto = 1000):
pedidos_totales = 0
pedidos_superiores = 0
for dni_cliente in pedidos:
pedidos_totales += len(pedidos[dni_cliente])
for pedido in pedidos[dni_cliente]:
if (pedido[2] > monto):
pedidos_superiores += 1
if pedidos_totales > 0:
print(f"El porcentaje de pedidos superiores a: ${monto} es %{pedidos_superiores*100/pedidos_totales}")
else:
print("No hay pedidos registrados")
def mostrar_menu():
print("Opciones")
print("1- Realizar pedido")
print("2- Ingresar un pago")
print("3- Top 5 de deudas")
print("4- Reporte de pedidos")
print("5- Pedidos superiores a un monto")
def main():
clientes = {} #key = DNI : value = NOMBRE + APELLIDO
compras = {} #key = DNI : value = LISTA DE PEDIDOS
pagos = {} #key = DNI : value = LISTA DE PAGOS
deudas = {} #key = DNI : value = LISTA DE DEUDAS
continuar = True
while continuar:
mostrar_menu()
opcion = input("\nIngrese una opcion: ")
if opcion == "1":
realizar_pedido(clientes, compras)
actualizar_deudas(deudas,compras, pagos)
elif opcion == "2":
ingresar_pago(pagos)
actualizar_deudas(deudas, compras, pagos)
elif opcion == "3":
ranking_deudas(clientes, deudas)
elif opcion == "4":
reporte_pedidos(compras)
elif opcion == "5":
pedidos_superiores_a(compras, monto=4000)
opcion_continuar = input("Desea realizar otra operacion? (S/N)")
if opcion_continuar != "S":
continuar = False
main() |
fa78f4896abe6dbf6999d1cb51ce47f4b6020c6e | Francisco-Galeano/Programming | /FG-09-03/exc3.py | 706 | 3.734375 | 4 | def devolver_mayor(numero_1, numero_2):
if numero_1 > numero_2:
return numero_1
else:
return numero_2
numero_1 = int(input("Ingrese el 1er numero: "))
numero_2 = int(input("Ingrese el 2do numero: "))
print(devolver_mayor(numero_1, numero_2))
def pueder_votar(edad):
if edad >= 16:
return True
else:
return False
edad = int(input("Ingrese la edad: "))
if pueder_votar(edad) == True:
print("Puede votar")
else:
print("No puede votar")
otro_numero = input("Flotante: ")
print(otro_numero)
suma = otro_numero + otro_numero # cómo no le meti el float al input en línea 25 el print de abajo me va a concatenar el str del input de la línea 25
print(suma)
|
f6ba15e82314dae05524291cea4e42a9e57825bc | eeeeegor/Personal-expense-manager | /interface.py | 2,304 | 4.0625 | 4 | import banking
def get_month(month_number):
months = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December']
return months[month_number - 1]
def check_month_year_validness(date):
year = int(date[:4])
month = int(date[5:])
return 1 <= month <= 12 and year > 0
def check_month_year_format(date):
if len(date) != 7:
return False
for i in range(len(date)):
if i == 4 and date[i] != '-':
return False
elif i != 4 and date[i] not in '0123456789':
return False
return True
def check_number_correct(number):
for x in number:
if x not in '0123456789':
return False
return True
def get_date_by_user():
while True:
s = input('Give a date in format YYYY-MM:')
if not check_month_year_format(s):
print('Wrong format!')
elif not check_month_year_validness(s):
print('Uncorrect date!')
else:
return s
def get_option_from_menu():
option = -5
while True:
print('Select an option number:')
print('1: Current funds')
print('2: Monthly report')
print('3: Exit')
option = input('Your choice:').rstrip()
if check_number_correct(option):
option = int(option)
else:
option = -5
if 1 <= option <= 3:
return option
else:
print('Wrong choice! Please, try again.')
def get_card_option():
option = -5
size = len(banking.CARD_MENU_INDEX.keys())
while True:
print('Select card number:')
for index in banking.CARD_MENU_INDEX.keys():
card = banking.CARD_MENU_INDEX[index][1]
bank = banking.BANK_NAMES[banking.CARD_MENU_INDEX[index][0]]
print(str(index) + ': *' + str(card) + ' ' + bank)
print(size + 1, ': All cards')
print(size + 2, ': Back to the main menu')
option = input('Your choice:').rstrip()
if check_number_correct(option):
option = int(option)
else:
option = -5
if 1 <= option <= size + 2:
return option
else:
print('Wrong choice! Please, try again.')
|
095591dfb167bb0ea8371d07b5bf3798e54bfcc9 | hugechuanqi/Algorithms-and-Data-Structures | /other_code_programe/04.python实现一个二叉树类.py | 771 | 3.625 | 4 | class Tree:
def __init__(self, val = '#', left = None, right = None):
self.val = val
self.left = left
self.right = right
#前序构建二叉树
def FrontBuildTree(self):
temp = input('Please Input: ')
node = Tree(temp)
if(temp != '#'):
node.left = self.FrontBuildTree()
node.right = self.FrontBuildTree()
return node#因为没有引用也没有指针,所以就把新的节点给返回回去
#前序遍历二叉树
def VisitNode(self):
print(self.val)
if(self.val != '#'):
self.left.VisitNode()
self.right.VisitNode()
if __name__ == '__main__':
root = Tree()
root = root.FrontBuildTree()
root.VisitNode()
|
2e442e3dd9e9ef80c18517946c4d6ac82db7c795 | ave2407/CourseraPythonProjects | /week2/while/artist_splitter.py | 817 | 4.34375 | 4 | """Исполнитель “Раздвоитель” преобразует натуральные числа.
У него есть две команды:
“Вычесть 1” и “Разделить на 2”, первая команда уменьшает число на 1
, вторая команда уменьшает число в два раза, если оно чётное
Напишите алгоритм для Раздвоителя, который преобразует число A в число B
и при этом содержит минимальное число команд. """
a = int(input())
b = int(input())
while a > b:
if a % 2 == 0 and a / b >= 2:
a /= 2
print(":2")
continue
elif a % 2 != 0 or a / b < 2:
a -= 1
print("-1")
|
4ae13f978c1df2460f345d947dc43e3b80200235 | mikuna-xe/AoC_2019 | /Day3.py | 3,640 | 3.5625 | 4 | #!/usr/bin/env python3
def main():
# Day 3
with open('AoC_input.txt', 'r') as f:
input_str = f.readlines()
wire0 = input_str[0].strip().split(',')
wire1 = input_str[1].strip().split(',')
dir0 = []
dir1 = []
dist0 = []
dist1 = []
for cmd in wire0:
dir0.append(cmd[0])
dist0.append(int(cmd[1:]))
for cmd in wire1:
dir1.append(cmd[0])
dist1.append(int(cmd[1:]))
set0 = set()
dict0 = dict()
start = (0,0)
step_count = 0
for dir, dist in zip(dir0, dist0):
start, line, step_count, steps = add_coords(start, dir, dist, step_count, dict0)
set0.update(line)
dict0 = steps
set1 = set()
dict1 = dict()
start = (0,0)
step_count = 0
for dir, dist in zip(dir1, dist1):
start, line, step_count, steps = add_coords(start, dir, dist, step_count, dict1)
set1.update(line)
dict1 = steps
cross = set0.intersection(set1)
cross2 = set0.intersection(set1)
### Get closest manhattan distance ###
closest = (9999,9999)
for x in range(len(cross)):
point = cross.pop()
if get_dist(point) < get_dist(closest):
closest = point
print("Closest intersection point: {}\nDistance: {}".format(closest, get_dist(closest)))
## Get least steps ###
closest = (9999,9999)
least_steps = 9999999
for x in range(len(cross2)):
point = cross2.pop()
steps = steps_to_point(dict0, dict1, point)
if steps < least_steps:
least_steps = steps
closest = point
print("Least steps intersection point: {}\nDistance: {}".format(closest, least_steps))
def steps_to_point(dict0, dict1, point):
return dict0['({},{})'.format(point[0],point[1])] + dict1['({},{})'.format(point[0],point[1])]
def get_dist(point):
return abs(point[0]) + abs(point[1])
def add_coords(start, dir, dist, step_count, line_steps):
line = set()
ox = start[0]
oy = start[1]
if dir == 'U':
for y in range(oy+1, oy+1+dist):
step_count += 1
line.add((ox,y))
if '{},{}'.format(ox,y) in line_steps:
line_steps['({},{})'.format(ox,y)].append(step_count)
else:
line_steps['({},{})'.format(ox,y)] = step_count
return (ox,y), line, step_count, line_steps
elif dir == 'D':
for y in range(oy-1, oy-1-dist, -1):
step_count += 1
line.add((ox,y))
if '{},{}'.format(ox,y) in line_steps:
line_steps['({},{})'.format(ox,y)].append(step_count)
else:
line_steps['({},{})'.format(ox,y)] = step_count
return (ox,y), line, step_count, line_steps
elif dir == 'L':
for x in range(ox-1, ox-1-dist, -1):
step_count += 1
line.add((x,oy))
if '{},{}'.format(x,oy) in line_steps:
line_steps['({},{})'.format(x,oy)].append(step_count)
else:
line_steps['({},{})'.format(x,oy)] = step_count
return (x,oy), line, step_count, line_steps
elif dir == 'R':
for x in range(ox+1, ox+1+dist):
step_count += 1
line.add((x,oy))
if '{},{}'.format(x,oy) in line_steps:
line_steps['({},{})'.format(x,oy)].append(step_count)
else:
line_steps['({},{})'.format(x,oy)] = step_count
return (x,oy), line, step_count, line_steps
else:
raise AssertionError("sth fucked up. Bad dir: {}".format(dir))
if __name__== "__main__":
main()
|
1ad2a8231048522495c0bcbf23b9d310013d8c93 | osspuddles/py_course | /listsRangesTuples/listsRangesTuples2.py | 362 | 4.21875 | 4 | # #!/usr/bin/python3
#
# list_1 = []
# list_2 = list()
#
# print("List 1: {}".format(list_1))
# print("List 2: {}".format(list_2))
#
# if list_1 == list_2:
# print("The lists are equal.")
# else:
# print("The lists are not equal")
#
# print(list("The lists are equal"))
even = [2, 4, 6, 8]
another_even = even
another_even.sort(reverse=True)
print(even) |
4fd5b0dbf682654f4b35ca56e3cbfda3588b99e0 | AngryGrizzlyBear/PythonCrashCourseRedux | /Part 1/Ch.11 Testing Your Code/Testing A Class/Try_it_yourself_2.py | 575 | 4.0625 | 4 | # 11-3. Employee: Write a class called Employee. The __init__() method should
# take in a first name, a last name, and an annual salary, and store each of these
# as attributes. Write a method called give_raise() that adds $5000 to the
# annual salary by default but also accepts a different raise amount.
# Write a test case for Employee. Write two test methods, test_give_
# default_raise() and test_give_custom_raise(). Use the setUp() method so
# you don’t have to create a new employee instance in each test method. Run
# your test case, and make sure both tests pass. |
b63c786a919f9c4e3ef480328078a30b3f613880 | VictorSega/toxic-substances-ship | /Domain/User.py | 834 | 3.53125 | 4 | import sqlite3
import hashlib
conn = sqlite3.connect('Navio.db')
def InsertUser(username, password):
encodedPassword = hashlib.sha1(password.encode()).hexdigest()
cursor = conn.cursor()
cursor.execute(f"INSERT INTO User (Username, Password) VALUES ('{username}', '{encodedPassword}');")
conn.commit()
def GetUsers():
cursor = conn.cursor()
cursor.execute("SELECT Id, Username FROM User")
users = []
for user in cursor.fetchall():
users.append(str(user))
return users
def UpdateUser(username, userId):
cursor = conn.cursor()
cursor.execute(f"UPDATE User SET Username = '{username}' WHERE Id = '{userId}';")
conn.commit()
def DeleteUser(userId):
cursor = conn.cursor()
cursor.execute(f"DELETE FROM User WHERE Id = '{userId}';")
conn.commit() |
9d04bf5d26eb6be518f268ed0ace39cc0117cbd3 | DonatasNoreika/7paskaita | /main.py | 531 | 3.75 | 4 | class Irasas:
def __init__(self, suma):
self.suma = suma
class PajamuIrasas(Irasas):
pass
class IslaiduIrasas(Irasas):
pass
biudzetas = []
irasas1 = PajamuIrasas(2000)
irasas2 = IslaiduIrasas(20)
irasas3 = IslaiduIrasas(10)
biudzetas.append(irasas1)
biudzetas.append(irasas2)
biudzetas.append(irasas3)
for irasas in biudzetas:
if isinstance(irasas, PajamuIrasas):
print("Pajamos", irasas.suma)
if type(irasas) is IslaiduIrasas:
print("Išlaidos", irasas.suma)
# pakeitimas
|
59507422158111de630884c9f7d0819f7f397cf1 | micahwar/Project-Euler | /37.py | 944 | 3.828125 | 4 | import math
#Truncatable Primes
def isPrime(n):
if n == 2: return True
if (n % 2) == 0 or n == 1:
return False
y = 3
while y*y <= n:
if (n % y) == 0:
return False
y = y + 2
return True
def isTruncatable(n):
n = str(n)
return isTruncatableRec(n, 1) and isTruncatableRec(n, -1)
def isTruncatableRec(n, d):
if len(n) == 1:
if isPrime(int(n)):
return True
else:
return False
if not isPrime(int(n)):
return False
else:
if d == 1:
return isTruncatableRec(n[1:], d)
else:
return isTruncatableRec(n[:-1], d)
print(isTruncatable(3797))
foundCount = 0
found = []
x = 10
while foundCount < 11:
x += 1
if not isPrime(x):
continue
if isTruncatable(x):
foundCount += 1
found.append(x)
print(x)
|
0e3bcfd8097f9ca228b7b98a2c62cd80512bcd57 | manoznp/LearnPython-Challenge | /DAY4/homework1.py | 1,314 | 3.78125 | 4 | # Write the function that calculate the discount amount and discount %, and profit of an item.
def DiscountAmount():
return MP - SP
def DiscountPercentage():
return (DiscountAmount() / MP) * 100
def ProfitAmount():
return SP - AP
def ProfitPercentage():
return (ProfitAmount() / AP) * 100
def switch():
switcher = {
1: "The discount is {}".format(DiscountAmount()),
2: "The discount percentage is {}%".format(DiscountPercentage()),
3: "The Profit is {}".format(ProfitAmount()),
4: "The Profit percentage is {}%".format(ProfitPercentage())
}
return switcher.get(choice, "Invalid Queries!!")
AP = int(input("Enter ActualPrice: "))
MP = int(input("Enter MarketPrice: "))
SP = int(input("Enter SellingPrice: "))
print("*************************************")
print("1. Calculate Discount Amount")
print("2. Calculate Discount Percentage")
print("3. Calculate Profit Amount")
print("4. Calculate Profit Percentage")
choice = int(input("what you like ? : "))
print(switch())
print("*************************************")
# print("The discount is {}".format(DiscountAmount()))
# print("The discount % is {}%".format(DiscountPercentage()))
# print("The Profit is {}".format(ProfitAmount()))
# print("The Profit % is {}%".format(ProfitPercentage())) |
d0fc3cf5aea42fcfa34fae1d382a6c002b07c1cc | shiraz19-meet/yl1201718 | /lab 4/lab4.py | 861 | 3.890625 | 4 | #class Animal(object):
# def __init__(self,sound,name,age,favorite_color):
# self.sound = sound
# self.name = name
# self.age = age
# self.favorite_color = favorite_color
# def eat(self,food):
# print("yummy!!"+ self.name + "is eating" +food)
# def description(self):
# print(self.name + "is " + self.age +" years old and loves the color"
# + self.favorite_color)
# def make_sound(self):
# print(self.sound*3)
#dog = Animal ("barks","Lucky","2","red")
#dog.eat("pizza")
#dog.description()
#dog.make_sound()
class person(object):
def __init__(self,name,age,city,gender):
self.name = name
self.age = age
self.city= city
self.gender = gender
def eat(self,food):
print("eating " + food)
def sports(self,sports):
print("Im playing " + sports + " yaaaaaay")
j = person ("Tamara", 15, "Jerusalem", "female")
j.eat("pizza")
j.sports("soccer")
|
4d1fa3c2aacd6f114ef411b9f9ca7abf1768d7a1 | mrdc1790/python-_-recap-_beginner-concepts | /tutorials/recaps/newModules -easy02/08-regularExpressions-additionalSyntax-02.py | 1,311 | 4.34375 | 4 | import re
catOr = re.search(r'cat|dog', 'The cat is here') ## '|' stands for OR. very versatile
periodWild = re.findall(r'..at', 'The cat in the hat went splat.') ## '.' stands for an arbitrary value/wildcard, spaces mess it up
print(catOr)
print(periodWild)
beginsWith = re.findall(r'^\d', '1 is a number') ##the carrot represnents the expression starting w an \d==int
endsWith = re.findall(r'\d$', 'The number is 2')
print(beginsWith)
print(endsWith)
phrase = "there are 3 numbers 34 inside 5 this sentence"
pattern = r'[^\d]' ##removes numbers from above sentence
print(' '.join(re.findall(pattern, phrase)))
test_phrase = "This is a string! But it has punctuation. How can we remove it?"
patternExclusion = r'[^!.? ]+'
textExclusion = ' '.join(re.findall(patternExclusion, test_phrase))
print(textExclusion) ## more complex to read fast, uses brackets for exclusion
text = "Only find the hyphen-words in this sentence. But you do not know how long-ish these words are."
patternInclusion = r'[\w]+-[\w]+'
textInclusion = ' '.join(re.findall(patternInclusion, text))
print(textInclusion)
sent1 = "Hello, would you like some catfish?"
sent2 = "Hello, would yuou like to take a catnap?"
sent3 = "Hello, have you seen this caterpillar?"
multGroup = re.findall(r'cat(fish|nap|claw)', sent2)
print(multGroup) |
c1a7efd88b1c449916f7db70c49bcaad553f7fb1 | hebe3456/algorithm010 | /Week02/144.二叉树的前序遍历.py | 1,100 | 3.609375 | 4 | #
# @lc app=leetcode.cn id=144 lang=python3
#
# [144] 二叉树的前序遍历
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
# recursively
# 40ms
ans = []
self.dfs(root, ans)
return ans
def dfs(self, root, ans):
if root:
ans.append(root.val)
self.dfs(root.left, ans)
self.dfs(root.right, ans)
class Solution2:
def preorderTraversal(self, root: TreeNode) -> List[int]:
# 36ms
# iteratively
if not root: return [] # []
ans = []
stack = [root]
while stack:
node = stack.pop()
if node:
ans.append(node.val)
if node.right:
stack.append(node.right) # 后进先出
if node.left:
stack.append(node.left)
return ans
# @lc code=end
|
a204cb2e8c4e6d2204740ccbc33cbcb06faa527b | thankew/BTVN_Python | /pythonProject2/BTVN_Buoi17/hh.py | 1,901 | 3.90625 | 4 | class people:
full_name = ""
phone = []
email = []
address = ""
note = ""
tags = []
def __init__(self, full_name, phone, email, address, note, tags):
self.full_name = full_name
self.phone = phone
self.email = email
self.address = address
self.note = note
self.tags = tags
def set_name(self,full_name):
self.full_name = full_name
def set_phone(self,phone):
self.phone = phone
def set_email(self,email):
self.email = email
def set_address(self,address):
self.address = address
def set_note(self,note):
self.note = note
def set_tags(self,tags):
self.tags = tags
def show(self):
return f"""
* {"Name:":10}{self.full_name}
* {"Phone:":10}{self.phone}
* {"Email:":10}{self.email}
* {"Address:":10}{self.address}
* {"Note:":10}{self.note}
* {"Tag":10}{self.tags}
"""
def check_tag(self,tag):
return tag in self.tags
thanh = people("Thành","Thành Nguyễn",["0123","4533"],["thanhhh@gmail.com","thzzzz@yahoo.com"],"Hà Nội",["friend","work"])
#User_guide:
guide = '''
Quản lý danh bạ
1. Sửa danh bạ
2. Hiển thị danh bạ
3. Kiểm tra tag
'''
print(guide)
user_input = input("Nhập chức năng muốn thực hiện 1/2/3: ")
if user_input == "1":
print("""
1. Name
2. Phone
3. Email
4. Address
5. Note
6. Tags
""")
choice = input("Nhập thông tin muốn sửa 1/2/3/4/5/6: ").lower()
if choice == "1":
print(thanh.full_name)
new_choice = input("Giá trị sửa thành là: ")
print(thanh.set_name(new_choice))
elif choice ==
elif user_input == "2":
print(thanh.show())
elif user_input == "3":
input_tags = input("Nhập tag muốn check: ")
thanh.check_tag(input_tags)
|
07c9cbadb58598318b5bcade2640fc851fddb20a | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4011/codes/1635_2445.py | 199 | 3.703125 | 4 | e = input("Qual e a escala esta representada(C/F)? ")
t = int(input("Qual e a temperatura? "))
if (e == "C"):
F = (1.8 * t) + 32
print(round(F, 2))
else:
C = (5 / 9) * (t- 32)
print(round(C, 2)) |
1f4b5751a4761cf366f680dd430012c488ddb0d6 | InnocentSuta/python_bootcamp | /week_4_List & Loops/while_loops.py | 422 | 4.28125 | 4 |
health = 5
while health > 0:
print(health)
health -= 1 # forgetting this line will result in infinite loop
# using two or more loops together is called a nested loop
for i in range(2): # outside loop
for j in range(3): # inside loop
print( i, j )
sentinel = input("Enter quit to exit: ")
while sentinel != "quit":
print(sentinel)
sentinel = input("Enter quit to exit: ") |
7cca5cbc6d4594267807d5123bcd3730c4fc64d9 | christianesl/python-workspace | /Advanced Funtions/LongestCharSequence.py | 450 | 3.65625 | 4 | def method(input):
charS = ''
previous = ''
maxS = 0
dict1 = {}
for itr in input:
if(previous == itr):
dict1[itr] = dict1[itr] + 1
if(dict1[char] > maxS):
maxS = dict1[char]
charS = char
else:
dict1.clear()
dict1 = {itr, 1}
previous = dict1
print(charS*maxS)
my_string = 'aaabbddkwobkkkkkkdfasdnb'
method(my_string)
|
1793f50d87eb2d80f998a0103d2e8ad77dfb06d5 | CoderKn1ght/Algorithm-Implementations | /CH5_Bit_Manipulation/q3_longest_sequence_of_ones.py | 755 | 3.71875 | 4 | from CH5_Bit_Manipulation.basic_bit_functions import get_nth_bit
number = 0b11110111011001000000
# not solved
print(bin(number))
start_index = 0
current_index = 0
zero_index = 0
longest = 0
flag = False
while number != 0:
nth_bit = get_nth_bit(number,0)
if nth_bit == 0:
if flag == False:
flag = True
zero_index = current_index
else:
print("possible: ",current_index - start_index)
longest = max(longest,(current_index - start_index))
print("longest: ",longest)
flag = True
start_index = zero_index + 1
print("new start index: ",start_index)
zero_index = current_index
current_index += 1
number = number >> 1
|
fc15631fb41b441e7089c12c7a8877ee38fc68c1 | MihailTr/learningPythonSD | /m2l43.py | 234 | 3.671875 | 4 | a = []
nun = int(input("Введите число:"))
coun = 0
for i in range(nun):
if i == 0:
i += 3
if i % 2 == 0 and i % 3 == 0:
a.append(i)
elif i % 2 == 1 and i % 7 == 0:
a.append(i)
print(a)
|
b09d083bd2449e156a1736a89b0b2d3107694fd0 | computerMoMo/ForMyOffer | /pythonCode/robotMovingCount.py | 1,571 | 3.625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def getDigitSum(self, number):
total_sum = 0
while number//10 > 0:
total_sum += number % 10
number = number//10
total_sum += number
return total_sum
def movingCount(self, threshold, rows, cols):
# write code here
if threshold < 0 or rows <= 0 or cols <= 0:
return 0
visited_flag = [[False for _ in range(cols)] for _ in range(rows)]
count = self.moveCount(threshold, rows, cols,0,0,visited_flag)
return count
def moveCount(self, threshold, rows, cols, row_id, col_id, visited_flag):
count = 0
if self.checkNode(threshold, rows, cols, row_id, col_id, visited_flag):
visited_flag[row_id][col_id] = True
count = 1 + self.moveCount(threshold, rows, cols, row_id+1, col_id, visited_flag) + \
self.moveCount(threshold, rows, cols, row_id-1, col_id, visited_flag) + \
self.moveCount(threshold, rows, cols, row_id, col_id+1, visited_flag) + \
self.moveCount(threshold, rows, cols, row_id, col_id-1, visited_flag)
return count
return count
def checkNode(self, threshold, rows, cols, row_id, col_id, visited_flag):
if 0<=row_id<rows and 0<=col_id<cols and not visited_flag[row_id][col_id] \
and (self.getDigitSum(row_id)+self.getDigitSum(col_id))<=threshold:
return True
return False
if __name__ == "__main__":
print Solution().movingCount(345)
|
a71fec95e07d36b7ebfa6ea556a3c974dc6c32b0 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/3135/codes/1646_87.py | 143 | 3.90625 | 4 | p=int(input("Insira o primeiro numero:"))
s=int(input("Insira o segundo numero:"))
t=int(input("Insira o terceiro numero:"))
print(min(p,s,t)) |
5f6259212fcad9087d0886239e25c4ef2a339c07 | gshruti015/pyLab | /lab3/Gupta_Shruti_3.1.py | 2,958 | 4.5 | 4 | #!/usr/bin/env python
# coding: utf-8
# Exercise 1.
# ```
# A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT, and RIGHT with a given steps. The trace of robot movement is shown as the following:
# UP 7
# DOWN 5 LEFT 2 RIGHT 9 X
# The numbers after the direction are steps. Please write a Python program to compute the distance from the
# current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.
# Example:
# If the following movements obtained from the user input are given to the program:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# X
# Then the output of the program should be: 2
# Note: X means the end of movement.
# ```
# In[ ]:
movement_dict={}
movement = []
while (True):
l = input("Enter steps intereatevley, enter 'X'to stop ")
movement.append(l)
if l == 'X':
break
movement= movement[:-1] # remove the 'X'
for i in range(len(movement)):
val = movement[i].split(' ') # this splits the UP 2 into two values UP and 2, and stores them in a list called val
movement_dict[val[0]] = val[1] # this uses the indexes in val to assign key and value to the dictionory
origin = [0,0]
for k,v in movement_dict.items():
if(k=='UP'):
origin[1] = origin[1] + int(v)
if(k=='DOWN'):
origin[1] = origin[1] - int(v)
if(k=='LEFT'):
origin[0] = origin[0] - int(v)
if(k=='RIGHT'):
origin[0] = origin[0] + int(v)
dist = int((origin[0]**2 + origin[1]**2)**1/2) # computing euclidean
print(int(round(dist))) # rounding and printing to nearest integer
# Exercise 2.
# ```
# Write a Python program to compute the frequency of words from the article. The output should output after sorting the key alphanumerically. Suppose the article is obtained from the user. The input ends until the user sends a new line: X
# Example:
# Please provide the article:
# Beginner means someone who has just gone through an introductory Python course.
# He can solve some problems with 1 or 2 Python classes or functions.
# Normally, the answers could directly be found in the textbooks.
# Intermediate means someone who has just learned Python, but already has a relatively strong programming background from before.
# X
# Output:
# 1: 1
# 2: 1
# an: 1
# . . .
# ```
# In[ ]:
print("Please provide the article:")
article = []
while (True):
l = input("Enter lines intereatevley, enter 'X' to stop ")
l = l.lower()
val = l.split(" ")
article.append(val)
if l.upper().lower() == 'x':
break
article_new = [j.replace(".", "") for i in article for j in i] #list comprehsnion for nested loop, also replaces full stop
article_new = article_new[:-1]
unique_item = {}
for item in article_new:
unique_item[item]= unique_item.get(item,0)+1
d_keys = list(unique_item.keys())
d_keys.sort()
for k in d_keys:
print(k, unique_item[k])
|
512f98e1fe76066662c7c0ff9962a2c8fd470806 | garyholiday-umich/Connect-Four-Python-Coding-Challenge | /connect_four.py | 42,539 | 4.0625 | 4 | import random
class player:
def __init__(self, playername, playernum):
self.playername = playername
self.playernum = playernum
def getname(self):
"""This returns my username"""
return self.playername
def getnum(self):
"""This returns the number I am that game - 1 or 2"""
return self.playernum
def getenemynum(self):
"""This returns the number that my enemy is playing as - 1 or 2"""
if self.getnum() == 1:
return 2
else:
return 1
def possible_moves(self, board):
"""
Loop through the board and check if a column has an empty spot and make sure
the empty spot does not have an empty spot below it then add it to the possible
moves.
"""
moves = []
for row in range(len(board)):
for col in range(len(board[row])):
if row == 0 and board[row][col] == 0:
moves.append([row, col])
elif board[row][col] == 0 and (board[row - 1][col] != 0):
moves.append([row, col])
return moves
def do_i_have_three_vertical(self, board):
"""
Loop through the board and check if there are three of my tokens in a column and
there is an open spot above my third token. Make sure that the row is not higher
than the 2nd row or else we will go out of bounds.
"""
my_token = self.getnum()
for row in range(len(board)):
for col in range(len(board[row])):
if row < 3:
if (board[row][col] == my_token and
board[row + 1][col] == my_token and
board[row + 2][col] == my_token and
board[row + 3][col] == 0):
'''
return column plus 1 because if the column is number 0
then it will fail the if statement used to check if I have
three vertically. The one will be subtracted.
'''
return col + 1
return False
def do_i_have_three_horizontal(self, board):
"""
Loop through the board and check if there are three of my tokens in a row and
there is an open spot to the left/right of third token.
Make sure that the column is not higher than the 2nd column
or else we will go out of bounds.
"""
my_token = self.getnum()
moves = self.possible_moves(board)
'''loop through the board checking from left to right, check for three in a row'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 4:
if (board[row][col] == my_token and
board[row][col + 1] == my_token and
board[row][col + 2] == my_token and
[row, col + 3] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col + 3]
'''loop through the board checking from right to left, check for three in a row'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 2:
if (board[row][col] == my_token and
board[row][col - 1] == my_token and
board[row][col - 2] == my_token and
[row, col - 3] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col - 3]
'''
loop through the board checking from left to right, check for two tokens and then
an empty spot then a token
'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 4:
if (board[row][col] == my_token and
board[row][col + 1] == my_token and
[row, col + 2] in moves and
board[row][col + 3] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col + 2]
'''
loop through the board checking from right to left, check for two tokens and then
an empty spot then a token
'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 2:
if (board[row][col] == my_token and
board[row][col - 1] == my_token and
[row, col - 2] in moves and
board[row][col - 3] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col - 2]
'''
loop through the board checking from left to right, check for one token and then
an empty spot then two tokens
'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 4:
if (board[row][col] == my_token and
[row, col + 1] in moves and
board[row][col + 2] == my_token and
board[row][col + 3] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col + 1]
'''
loop through the board checking from right to left, check for one token and then
an empty spot then two tokens
'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 2:
if (board[row][col] == my_token and
[row, col - 1] in moves and
board[row][col - 2] == my_token and
board[row][col - 3] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col - 1]
return False
def do_i_have_three_diagonal(self, board):
"""
Loop through the board and check if there are three of my tokens in a diagonal and
there is an open spot to the top-left/right bottom-left/right.
"""
my_token = self.getnum()
moves = self.possible_moves(board)
'''loop through the board checking from left to right, bottom to top'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 4 and row < 3:
if (board[row][col] == my_token and
board[row + 1][col + 1] == my_token and
board[row + 2][col + 2] == my_token and
[row + 3, col + 3] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row + 3, col + 3]
'''
loop through the board checking from left to right, bottom to top for two
tokens then a blank spot and then a token
'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 4 and row < 3:
if (board[row][col] == my_token and
board[row + 1][col + 1] == my_token and
[row + 2, col + 2] in moves and
board[row + 3][col + 3] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row + 2, col + 2]
'''
loop through the board checking from left to right, bottom to top for one
token then a blank spot and then two token
'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 4 and row < 3:
if (board[row][col] == my_token and
[row + 1, col + 1] in moves and
board[row + 2][col + 2] == my_token and
board[row + 3][col + 3] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row + 1, col + 1]
'''loop through the board checking from right to left, top to bottom'''
for row in reversed(range(len(board))):
for col in reversed(range(len(board[row]))):
if col > 2 and row > 2:
if (board[row][col] == my_token and
board[row - 1][col - 1] == my_token and
board[row - 2][col - 2] == my_token and
[row - 3, col - 3] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row - 3, col - 3]
'''
loop through the board checking from right to left, top to bottom and check for
two tokens and open spot and then a token
'''
for row in reversed(range(len(board))):
for col in reversed(range(len(board[row]))):
if col > 2 and row > 2:
if (board[row][col] == my_token and
board[row - 1][col - 1] == my_token and
[row - 2, col - 2] in moves and
board[row - 3][col - 3] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row - 2, col - 2]
'''
loop through the board checking from right to left, top to bottom and check for
one token and open spot and then two tokens
'''
for row in reversed(range(len(board))):
for col in reversed(range(len(board[row]))):
if col > 2 and row > 2:
if (board[row][col] == my_token and
[row - 1, col - 1] in moves and
board[row - 2][col - 2] == my_token and
board[row - 3][col - 3] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row - 1, col - 1]
'''loop through the board checking from left to right, top to bottom'''
for row in reversed(range(len(board))):
for col in range(len(board[row])):
if col < 4 and row > 2:
if (board[row][col] == my_token and
board[row - 1][col + 1] == my_token and
board[row - 2][col + 2] == my_token and
[row - 3, col + 3] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row - 3, col + 3]
'''
loop through the board checking from left to right, top to bottom look for
two tokens and open spot and then one token
'''
for row in reversed(range(len(board))):
for col in range(len(board[row])):
if col < 4 and row > 2:
if (board[row][col] == my_token and
board[row - 1][col + 1] == my_token and
[row - 2, col + 2] in moves and
board[row - 3][col + 3] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row - 2, col + 2]
'''
loop through the board checking from left to right, top to bottom look for
one token and open spot and then two tokens
'''
for row in reversed(range(len(board))):
for col in range(len(board[row])):
if col < 4 and row > 2:
if (board[row][col] == my_token and
[row - 1, col + 1] in moves and
board[row - 2][col + 2] == my_token and
board[row - 3][col + 3] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row - 1, col + 1]
'''loop through the board checking from right to left, bottom to top'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 4 and row < 3:
if (board[row][col] == my_token and
board[row + 1][col - 1] == my_token and
board[row + 2][col - 2] == my_token and
[row + 3, col - 3] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row + 3, col - 3]
'''
loop through the board checking from right to left, bottom to top for two
tokens and then open spot and then one token
'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 4 and row < 3:
if (board[row][col] == my_token and
board[row + 1][col - 1] == my_token and
[row + 2, col - 2] in moves and
board[row + 3][col - 3] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row + 2, col - 2]
'''
loop through the board checking from right to left, bottom to top for two
tokens and then open spot and then one token
'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 4 and row < 3:
if (board[row][col] == my_token and
[row + 1, col - 1] in moves and
board[row + 2][col - 2] == my_token and
board[row + 3][col - 3] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row + 1, col - 1]
return False
def do_i_have_two_vertical(self, board):
"""
Loop through the board and check if there are two of my tokens in a column and
there is an open spot above my second token. Make sure that the row is not higher
than the 3rd row because there is no point in placing a token if I cant get 3
in a row
"""
my_token = self.getnum()
for row in range(len(board)):
for col in range(len(board[row])):
if row < 3:
if (board[row][col] == my_token and
board[row + 1][col] == my_token and
board[row + 2][col] == 0):
'''
return column plus 1 because if the column is number 0
then it will fail the if statement used to check if I have
three vertically. The one will be subtracted.
'''
return col + 1
return False
def do_i_have_two_horizontal(self, board):
"""
Loop through the board and check if there are two of my tokens in a row and
there is an open spot to the left/right of 2nd token.
Make sure that the column is not higher than the 5th column
or else we will go out of bounds.
"""
my_token = self.getnum()
moves = self.possible_moves(board)
'''loop through the board checking from left to right'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 5:
if (board[row][col] == my_token and
board[row][col + 1] == my_token and
[row, col + 2] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col + 2]
'''loop through the board checking from right to left'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 1:
if (board[row][col] == my_token and
board[row][col - 1] == my_token and
[row, col - 2] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col - 2]
'''
loop through the board checking from left to right for one token, blank spot,
then another token
'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 5:
if (board[row][col] == my_token and
[row, col + 1] in moves and
board[row][col + 2] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col + 1]
'''
loop through the board checking from right to left for one token, blank spot,
then another token
'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 1:
if (board[row][col] == my_token and
[row, col - 1] in moves and
board[row][col - 2] == my_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col - 1]
return False
def do_they_have_three_vertical(self, board):
"""
Loop through the board and check if there are three of my enemy's tokens in a col
and there is an open spot above their third token. Make sure that the row is not
higher than the 2nd row or else we will go out of bounds.
"""
enemy_token = self.getenemynum()
for row in range(len(board)):
for col in range(len(board[row])):
if row < 3:
if (board[row][col] == enemy_token and
board[row + 1][col] == enemy_token and
board[row + 2][col] == enemy_token and
board[row + 3][col] == 0):
'''
return column plus 1 because if the column is number 0
then it will fail the if statement used to check if the
enemy has three vertically. The one will be subtracted.
'''
return col + 1
return False
def do_they_have_three_horizontal(self, board):
"""
Loop through the board and check if there are three of my enemies tokens in
a row and there is an open spot to the left/right of the third token.
Make sure that the column is not higher than the 2nd column
or else we will go out of bounds.
"""
enemy_token = self.getenemynum()
moves = self.possible_moves(board)
'''loop through the board checking from left to right'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 4:
if (board[row][col] == enemy_token and
board[row][col + 1] == enemy_token and
board[row][col + 2] == enemy_token and
[row, col + 3] in moves):
'''
return the column and row that will give my enemy four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col + 3]
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 2:
if (board[row][col] == enemy_token and
board[row][col - 1] == enemy_token and
board[row][col - 2] == enemy_token and
[row, col - 3] in moves):
'''
return the column and row that will give my enemy four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col - 3]
'''
loop through the board checking from left to right, check for two tokens and then
an empty spot then a token
'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 4:
if (board[row][col] == enemy_token and
board[row][col + 1] == enemy_token and
[row, col + 2] in moves and
board[row][col + 3] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col + 2]
'''
loop through the board checking from right to left, check for two tokens and then
an empty spot then a token
'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 2:
if (board[row][col] == enemy_token and
board[row][col - 1] == enemy_token and
[row, col - 2] in moves and
board[row][col - 3] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col - 2]
'''
loop through the board checking from left to right, check for one token and then
an empty spot then two tokens
'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 4:
if (board[row][col] == enemy_token and
[row, col + 1] in moves and
board[row][col + 2] == enemy_token and
board[row][col + 3] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col + 1]
'''
loop through the board checking from right to left, check for one token and then
an empty spot then two tokens
'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 2:
if (board[row][col] == enemy_token and
[row, col - 1] in moves and
board[row][col - 2] == enemy_token and
board[row][col - 3] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col - 1]
return False
def do_they_have_three_diagonal(self, board):
"""
Loop through the board and check if there are three of my enemy tokens in a
diagonal and there is an open spot to the top-left/right bottom-left/right.
"""
enemy_token = self.getenemynum()
moves = self.possible_moves(board)
'''loop through the board checking from left to right, bottom to top'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 4 and row < 3:
if (board[row][col] == enemy_token and
board[row + 1][col + 1] == enemy_token and
board[row + 2][col + 2] == enemy_token and
[row + 3, col + 3] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row + 3, col + 3]
'''
loop through the board checking from left to right, bottom to top for two
tokens then a blank spot and then a token
'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 4 and row < 3:
if (board[row][col] == enemy_token and
board[row + 1][col + 1] == enemy_token and
[row + 2, col + 2] in moves and
board[row + 3][col + 3] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row + 2, col + 2]
'''
loop through the board checking from left to right, bottom to top for one
token then a blank spot and then two token
'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 4 and row < 3:
if (board[row][col] == enemy_token and
[row + 1, col + 1] in moves and
board[row + 2][col + 2] == enemy_token and
board[row + 3][col + 3] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row + 1, col + 1]
'''loop through the board checking from right to left, top to bottom'''
for row in reversed(range(len(board))):
for col in reversed(range(len(board[row]))):
if col > 2 and row > 2:
if (board[row][col] == enemy_token and
board[row - 1][col - 1] == enemy_token and
board[row - 2][col - 2] == enemy_token and
[row - 3, col - 3] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row - 3, col - 3]
'''
loop through the board checking from right to left, top to bottom and check for
two tokens and open spot and then a token
'''
for row in reversed(range(len(board))):
for col in reversed(range(len(board[row]))):
if col > 2 and row > 2:
if (board[row][col] == enemy_token and
board[row - 1][col - 1] == enemy_token and
[row - 2, col - 2] in moves and
board[row - 3][col - 3] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row - 2, col - 2]
'''
loop through the board checking from right to left, top to bottom and check for
one token and open spot and then two tokens
'''
for row in reversed(range(len(board))):
for col in reversed(range(len(board[row]))):
if col > 2 and row > 2:
if (board[row][col] == enemy_token and
[row - 1, col - 1] in moves and
board[row - 2][col - 2] == enemy_token and
board[row - 3][col - 3] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row - 1, col - 1]
'''loop through the board checking from left to right, top to bottom'''
for row in reversed(range(len(board))):
for col in range(len(board[row])):
if col < 4 and row > 2:
if (board[row][col] == enemy_token and
board[row - 1][col + 1] == enemy_token and
board[row - 2][col + 2] == enemy_token and
[row - 3, col + 3] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row - 3, col + 3]
'''
loop through the board checking from left to right, top to bottom look for
two tokens and open spot and then one token
'''
for row in reversed(range(len(board))):
for col in range(len(board[row])):
if col < 4 and row > 2:
if (board[row][col] == enemy_token and
board[row - 1][col + 1] == enemy_token and
[row - 2, col + 2] in moves and
board[row - 3][col + 3] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row - 2, col + 2]
'''
loop through the board checking from left to right, top to bottom look for
one token and open spot and then two tokens
'''
for row in reversed(range(len(board))):
for col in range(len(board[row])):
if col < 4 and row > 2:
if (board[row][col] == enemy_token and
[row - 1, col + 1] in moves and
board[row - 2][col + 2] == enemy_token and
board[row - 3][col + 3] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row - 1, col + 1]
'''loop through the board checking from right to left, bottom to top'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 4 and row < 3:
if (board[row][col] == enemy_token and
board[row + 1][col - 1] == enemy_token and
board[row + 2][col - 2] == enemy_token and
[row + 3, col - 3] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row + 3, col - 3]
'''
loop through the board checking from right to left, bottom to top for two
tokens and then open spot and then one token
'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 4 and row < 3:
if (board[row][col] == enemy_token and
board[row + 1][col - 1] == enemy_token and
[row + 2, col - 2] in moves and
board[row + 3][col - 3] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row + 2, col - 2]
'''
loop through the board checking from right to left, bottom to top for two
tokens and then open spot and then one token
'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 4 and row < 3:
if (board[row][col] == enemy_token and
[row + 1, col - 1] in moves and
board[row + 2][col - 2] == enemy_token and
board[row + 3][col - 3] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row + 1, col - 1]
return False
def do_they_have_two_horizontal(self, board):
"""
Loop through the board and check if there are two of my enemies tokens
in a row and there is an open spot to the left/right of 2nd token.
Make sure that the column is not higher than the 5th column
or else we will go out of bounds.
"""
enemy_token = self.getenemynum()
moves = self.possible_moves(board)
'''loop through the board checking from left to right'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 5:
if (board[row][col] == enemy_token and
board[row][col + 1] == enemy_token and
[row, col + 2] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col + 2]
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 1:
if (board[row][col] == enemy_token and
board[row][col - 1] == enemy_token and
[row, col - 2] in moves):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col - 2]
'''
loop through the board checking from left to right for one token, blank spot,
then another token
'''
for row in range(len(board)):
for col in range(len(board[row])):
if col < 5:
if (board[row][col] == enemy_token and
[row, col + 1] in moves and
board[row][col + 2] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col + 1]
'''
loop through the board checking from right to left for one token, blank spot,
then another token
'''
for row in range(len(board)):
for col in reversed(range(len(board[row]))):
if col > 1:
if (board[row][col] == enemy_token and
[row, col - 1] in moves and
board[row][col - 2] == enemy_token):
'''
return the column and row that will give me four in a row.
This will be compared to the moves I am allowed to make
'''
return [row, col - 1]
return False
def do_they_have_two_vertical(self, board):
"""
Loop through the board and check if there are two of my enemies tokens in a column
and there is an open spot above my second token. Make sure that the row is not
higher than the 3rd row because there is no point in placing a token if I cant
get 3 in a row
"""
enemy_token = self.getenemynum()
for row in range(len(board)):
for col in range(len(board[row])):
if row < 3:
if (board[row][col] == enemy_token and
board[row + 1][col] == enemy_token and
board[row + 2][col] == 0):
'''
return column plus 1 because if the column is number 0
then it will fail the if statement used to check if I have
three vertically. The one will be subtracted.
'''
return col + 1
return False
def requestmovement(self, board, height):
"""
This function is the function that returns the column that I am going to place
my token.
"""
'''Get all the possible moves'''
moves = self.possible_moves(board)
'''If I have three in a col with one open on top then play that spot'''
if self.do_i_have_three_vertical(board):
'''
read the return statement comment form this function to know why we subtract
one
'''
return self.do_i_have_three_vertical(board) - 1
elif self.do_i_have_three_horizontal(board) in moves:
return self.do_i_have_three_horizontal(board)[1]
elif self.do_i_have_three_diagonal(board) in moves:
return self.do_i_have_three_diagonal(board)[1]
elif self.do_they_have_three_vertical(board):
'''
read the return statement comment form this function to know why we subtract
one
'''
return self.do_they_have_three_vertical(board) - 1
elif self.do_they_have_three_horizontal(board) in moves:
return self.do_they_have_three_horizontal(board)[1]
elif self.do_they_have_three_diagonal(board) in moves:
return self.do_they_have_three_diagonal(board)[1]
elif self.do_i_have_two_horizontal(board) in moves:
return self.do_i_have_two_horizontal(board)[1]
elif self.do_i_have_two_vertical(board):
return self.do_i_have_two_vertical(board) - 1
elif self.do_they_have_two_horizontal(board) in moves:
return self.do_they_have_two_horizontal(board)[1]
elif self.do_they_have_two_vertical(board):
return self.do_they_have_two_vertical(board) - 1
elif [0, 3] in moves:
return 3
elif [1, 3] in moves:
return 3
else:
length = len(moves)
return moves[random.randrange(0, length)][1] |
b8999109342be0f5aa9c8ddb8d582ba8f070707e | NH1922/Arithematic-Game | /main.py | 2,525 | 4.125 | 4 | # simple maths game
import random
import time
# Function to generate expressions
def generate_expression(no_of_operators):
operations = ['+', '-', '*', '/']
expression = []
expression.append(random.randint(0, 20))
for _ in range(no_of_operators):
expression.append(random.choice(operations))
expression.append(random.randint(0, 20))
expression = ''.join(str(term) for term in expression)
return expression
# Function to calculate the solution
def result(expression):
return int(eval(expression))
def main():
# Display Message
print("""Welcome to the maths game !!!
-----------------------------
Test your basic arithematic skills by playing this simple game. With every 5 correct answers, the level increase
increasing the difficulty of the questions.
Remember :
----------
1. Write only the integral part of the answer
2. Operator precedence applies
3. You have 3 lives.
4. Total of 60 seconds will be provided.
5. The timer starts after the first answer is entered """)
input("Are you ready ?? Press any key to begin ! ")
# Variables on which the game operates
score = 0
level = 1
lives = 3
start = time.time()
finish_time = time.time() + 60 # for the timed mode, 60 seconds are needed
# While loop to drive the game
while lives != 0 and time.time() < finish_time:
print("LEVEL : ", level)
no_of_operands = level + 1
question_expression = generate_expression(no_of_operands)
print(question_expression, end='')
# Checking for any divide by zero or numerical errors that may show up
try:
correct_answer = result(question_expression)
except:
print("OOPS ! I messed up ! Lets do it again !")
continue
answer = int(input(" = "))
if correct_answer == answer:
print("CORRECT ! ", end='')
score = score + 1
print("SCORE = ", score, "LIVES = ", lives)
# Increase the level of difficulty every 5 questions.
if score != 0 and score % 5 == 0:
level = level + 1
else:
print("WRONG ! CORRECT ANSWER WAS ",correct_answer, end='')
lives = lives - 1
print("SCORE = ", score, "LIVES = ", lives)
print("GAME OVER !!!")
print("Maximum Level = ", level, "SCORE = ", score)
if __name__ == "__main__":
main()
|
0b8333949d8b4a32573cd24b8c83cedd9585e25e | pancham2016/ScubaAdventure | /bubble.py | 1,042 | 3.921875 | 4 | import pygame
from pygame.sprite import Sprite
class Bubble(Sprite):
"""A class that manages bubbles released from the diver."""
def __init__(self, sa_game):
"""create a bubble object at the diver's current position."""
super().__init__()
self.screen = sa_game.screen
self.settings = sa_game.settings
# import the bubble image
self.image = pygame.image.load("images/bubble.bmp")
self.bubble_rect = self.image.get_rect()
self.bubble_rect.topright = sa_game.diver.rect.topright
# Store the bubble's position as a decimal value
self.y = float(self.bubble_rect.y)
def update(self):
"""Move the bubble up the screen."""
# Update the decimal position of the bubble
self.y -= self.settings.bubble_speed
# Update the rect position.
self.bubble_rect.y = self.y
def blit_bubble(self):
"""Draw the bubble at the diver's current location"""
self.screen.blit(self.image, self.bubble_rect.topright) |
7209d2d72d91bf7ed11ca0731d36409d3e65cc73 | xCraudin/ORUS-RPG | /ORUS_RPG.py | 69,994 | 4 | 4 | import random
import time
print("╔══════════════════════════════════════════════════════════════════╗")
print("║ SEJA BEM-VINDO AO MUNDO DE ORUS! ║")
print("║ Aqui você encontrará uma aventura muito imersante e desafiadora! ║")
print("╚══════════════════════════════════════════════════════════════════╝\n\n")
score = 0
genero = input("Digite o seu gênero ->(m ou f) : ")
if genero == 'm' or genero == 'M' or genero == 'f' or genero == 'F' :
nome = input("Digite o nome do seu personagem: ")
time.sleep(0.8)
print("\nÓtimo, continuaremos com a criação da ficha de", nome,"\n\n" "Neste mundo você tera 3 opções de guardiões, eles definirão a dificulade do jogo, então escolha com sabedoria!")
time.sleep(1.6)
divindade = input(('''
╔══════════════════════════════════════════╗
║[1] - Deus da Ordem (Dificuldade: Fácil) ║
║[2] - Deus da Justiça (Dificuldade: Média)║
║[3] - Deus do Caos (Dificuldade: Difícil) ║
╚══════════════════════════════════════════╝
\nDigite sua escolha: '''))
print("")
time.sleep(0.8)
print("Muito bem, agora vamos para a classe!\n")
time.sleep(1)
classe = input("[1] - Paladino\nDigite sua escolha: ")
time.sleep(0.8)
print("\nAgora estamos prontos! Vamos para a história! Que a sorte esteja com você!\n")
print(nome,"se encontra na Catedral da Capital do Reino humano, na sua frente está o Sumo Sacerdote\n")
time.sleep(0.8)
print("Ele vira em sua direção e diz...")
print("\n(Sumo Sarcedote) -Bravo servo de nossa Igreja!, tenho uma missão a vós, Preciso que faças uma peregrinação para vossa graça.\n")
mapa = input("[1] - País dos demônios\nEscolha o país destino: ")
if mapa == '1' and classe == '1':
print("\n(Sumo Sarcedote) -Fez uma escolha perigosa nobre paladino..\n Receberas tua missão quando chegar na fronteira do País dos Demônios.\n Tenha discrição e se mantenha em sigilo!")
time.sleep(3)
print("\nEssas foram as últimas palavras do Sumo Sacerdote para",nome,", então começaremos sua Aventura!\n",nome,"sai da catedral e segue seu destino depois de terminar os preparativos para as Estradas.\n")
print(nome,"avista dois caminhos na estrada e escolhe a ...")
time.sleep(1)
estrada = input("[1] - estrada do rei (estrada mais movimentada e segura)\n[2] - estrada rural (menos popular e mais perigosa)\nEstrada da sua escolha: ")
if estrada == '1':
time.sleep(0.8)
print("\nEstrada segura e movimentada, com isso vamos para o seu dilema:\nAlguns minutos depois..\nUma carroça se encontra na encosta da estrada com a roda quebrada, O que você faz?")
time.sleep(2)
escolha=input("\n[1] - ajudar no conserto (+Fama)\n[2] - Ignorar (neutro)\nSeu escolha: ")
if escolha == '1':
score = score -2
dado = int(random.randrange(1,21))
print("Seu dado foi:", dado, "")
if dado == 20:
time.sleep(0.8)
print("\nSeu conserto foi perfeito, os comerciantes ficaram muito agredecidos\ne vão propagar o teu nome por todos os 4 cantos do mundo por sua gentileza")
score = score + 5
elif dado <=19 and dado >= 16:
time.sleep(0.8)
print("\nSeu conserto foi muito bom, porém houve pequenas falhas.\nOs comerciantes ficaram sastifeitos e vão lembrar do teu nome por um bom tempo")
score = score + 3
elif dado >= 8 and dado <= 15:
time.sleep(0.8)
print("\nSeu conserto foi mediocre e os comerciantes fizeram o trabalho junto com você,\neles te agradecem mas não vão se lembrar do Paladino nos proximos 3 dias")
score = score + 1
elif dado >= 2 and dado <= 7:
time.sleep(0.8)
print("\nVocê tentou ajudar mas só atrasou os comerciantes,\neles ficaram bravos com",nome,"e o mandam embora!")
score = score -1
else :
time.sleep(0.8)
print("\nEm vez de você ajudar, acabou quebrando mais a carroça.\nOs comerciantes fizeram o Paladino picar a mula com as espadas empunhadas pela raiva!")
score = score -4
if escolha == '2' :
score = score -2
print(nome,"ignorou os comerciantes e seguiu seu caminho até os reinos dos Demônios")
elif estrada =='2' :
print("\nEstrada perigosa e com pouca movimentação")
score = score +2
time.sleep(1.6)
print("\nAo chegar na metade do caminho do Reino dos Demônios",nome,"se depara com uma situação normal numa estrada não vigiada\n")
print("Uma Família Aldeã está sendo assaltada por um Bandido!, o que",nome,"vai fazer?\n[1] - Combater o bandido\n[2] - Fugir em uma disparada para o portão do Reino dos Demônios")
time.sleep(1.6)
assalto = input("\nQual é sua escolha: ")
if assalto == '1':
dado = int(random.randrange(1,21))
print("Seu dado foi:", dado, "\n")
if divindade == '1':
dado = dado +3
elif divindade == '2':
dado = dado +1
elif divindade == '3':
dado= dado -1
else:
print("Erro de digitação, preste atenção na proxima!")
exit()
print("Seu dado depois do bonificador: ", dado)
if dado >= 20:
time.sleep(0.8)
print("\nVocê faz uma luta épica contra o bandido! fixando essa imagem na memória da familía,\nque depois falarão para todos sobre o seu feito pelo resto de suas vidas")
score = score + 9
elif dado <=19 and dado >= 16:
time.sleep(0.8)
print("\nVocê vence, sem ferimentos, foi uma luta longa..., você sai cansado da batalha fazendo impacto na mente da família, com eles ficando muito agradecidos\ne irão comentar por esse feito por um bom tempo")
score = score + 5
elif dado >= 8 and dado <= 15:
time.sleep(0.8)
print("\nVocê ganha o combate incapacitando o bandido mas você sai levemente ferido")
score = score + 3
elif dado >= 2 and dado <= 7:
time.sleep(0.8)
print("\n",nome,"sai gravemente ferido mas mata o bandido e em agradecimento a humilde familía o leva para casa deles e o curam.\nO paladino espera estar 100% para voltar a estrada")
score = score +1
else :
time.sleep(0.8)
print("\nVocê Morreu")
score = score -100
print("Seu resultado ao final da história foi:",score)
exit()
print(nome,"chegou ao Reino dos Demônios e lhe é oferecido dois caminhos de entrada")
time.sleep(2)
portao = input("[1] - Portão principal do Reino\n[2] - Portão auxiliar\nSua escolha: ")
if portao == '1':
score = score -2
print("Os guardas te revistam e lhe perguntam qual é seu objetivo entrando no reino dos Demônios\n")
fala = input("[1] - Estou a Turismo nas férias de serviço da igreja\n[2] - Apenas Por peregrinação\n[3] - Para investigar uma história do ducado atual\nSua escolha: ")
if fala =='1':
score = score -1
print("O guarda desconfia de você mas te deixa entrar e coloca um olheiro atrás de você\n",nome,"se dirige para a praça principal da cidade fronteriça")
time.sleep(2)
elif fala == '2':
score = score +1
print("O guarda recebe bem a sua fala e abre o portão do reino para você lhe desejando boa sorte na peregrinação\n",nome,"se dirige para a praça principal da cidade fronteriça")
time.sleep(2)
elif fala == '3':
score = score -3
print("O guarda abre com receio o portão do reino e coloca 2 guardas para segui-lo escondidos durante sua permanencia no local\n",nome,"se dirige para a praça principal da cidade fronteriça")
time.sleep(2)
else :
print("Escolha inválida, preste atenção na próxima")
exit()
elif portao == '2':
score = score + 2
print("O paladino se depera com um guarda roncando depois do almoço\ne entra no reino sem que ninguém saiba de sua presença\n",nome,"se dirige para a praça principal da cidade fronteriça")
else:
print("Escolha inválida, preste atenção na próxima")
exit()
print("Ao chegar na praça o paladino senta-se próximo da fonte e um homem com uma capa com capuz lhe entraga um bilhete\n")
time.sleep(1)
print(nome,'abre o bilhete e lá estava a mensagem... "RESGATE A PRINCESA DAS GARRAS DO REI DEMÕNIO"\n')
time.sleep(1)
print('O homem encapuzado sussura ao seu lado "Boa sorte" e lhe dá as costas e desaparece entre a multidão')
time.sleep(1)
print("O paladino se levanta e vai em direção à Capital do Reino,\n",nome,"vai em uma marcha rápida....................\n")
time.sleep(1)
print("Adentrando a capital qual caminho ",nome,"escolheu até o castelo?\n")
time.sleep(1)
caminho = input("[1] - Avenida principal\n[2] - Vielas da periferia\nSua escolha: ")
if caminho == '1':
print("")
print(nome,"escolheu a Avenida Principal e todos ali reconheceram você como estrangeiro e\nse perguntavam o porquê de um Servo da Igreja estar vagando por ali.\nChegando nas portas do castelo...")
score = score -3
time.sleep(2)
invasao = input("O paladino, ao ver que foi descoberto por ter chamado atenção demais naquela avenida,\npartiu em frente ao portão principal do lorde demônio e lhe vem na mente uma ideia\n\n[1] - Lutar com os guardas do portão e entrar a força no Castelo\n[2] - Fugir do local e tentar uma nova empreitada no dia seguinte pelas vielas\nQual sua escolha: ")
if invasao == '1':
score = score - 1
dado = int(random.randrange(1,21))
print("")
print("Seu dado foi:", dado)
if divindade == '1':
dado = dado +3
elif divindade == '2':
dado = dado +1
elif divindade == '3':
dado= dado -1
else:
dado = dado
print("Seu dado após o bonificador:", dado)
if dado >= 20:
time.sleep(0.8)
print("\nVocê mata os guardas com eximia destreza antes que qualquer alarme fosse disparado")
score = score + 15
print("O Paladino anda com glória em direção ao castelo e segue indo para o Hall de entrada do castelo que dava passagem para a sala do trono\ne quando abre essa porta lá estava a princesa ao lado do Rei Demônio\n\n")
print("(Rei Demônio) -Olá nobre paladino, o que o traz nessa tarde de Domingo?\n(Paladino) -Me devolva a princesa! e espero que não tenha derramamento de sangue desnecessário aqui Demônio!\n(Rei Demônio) -Muita audácia sua projeto de cavaleiro, me responda uma coisa...\n O Rei Demônio Respira fundo e olho nos olhos do paladino com desprezo\n(Rei Demônio) -Depois de todo o esforço que tive para captua-la. Por que a devolveria-a pra você de mão beijada?")
resposta = input("[1] - Porque você é sábio e gosta de viver\n[2] - Porque isso vai causar uma guerra entre os reinos\n[3] - Porque isso é o certo a se fazer\nQual a sua resposta: ")
if resposta == '1' or resposta == '3' or resposta == '2':
print("(Rei Demônio) -Então vamos lutar projeto de guerreiro!, me cansei de VOCÊ!\n\nO Rei se levanta do seu trono e pega sua espada e caminha lentamente em sua direção")
postura=input("\nRESPOSTA RÁPIDA O QUE VOCÊ FAZ?\n[1] - Fica em posição de batalha com a espada em mãos\n[2] - Corre em direção ao rei demônio\n[3] - Você puxa a garrafa de rum e chama o Rei demônio pro x1 de shots\nQual sua escolha? ")
if postura == '1' or postura == '2':
print("Sua confiança te ajuda nesse momento e a luta será definida em um golpe,\no seu dado será bonificado por sua luta anterior")
paladino = int(random.randrange(1,21))
if divindade == '1':
paladino = paladino +5
elif divindade == '2':
paladino = paladino +3
elif divindade == '3':
paladino = paladino +1
else:
print("Escolha inválida")
demonio = int(random.randrange(1,21))
if divindade == '1':
demonio = demonio -4
elif divindade == '2':
demonio = demonio - 2
elif divindade == '3':
demonio = demonio
else:
print("Escolha inválida")
print("Dado do Rei Demônio: ", demonio)
print("\nDado do Paladino: ", paladino)
if paladino > demonio:
print("O paladino mata o Rei demônio numa batalha épica e longa de apenas um golpe. Parabéns bravo herói!,\nmesmo ferido você mostrou do que é feito e fez o Rei Demônio ser chacota pelo resto dos séculos.\n",nome,"se casa com a princesa e após a morte de seu sogro vira Rei do reino humano e será lembrado para sempre")
score = score + 80
elif paladino == demonio:
print("Ocorreu um empate na batalha épica do paladino contra o rei demônio, cada um crava sua espada no coração do oponente,\ndando um final dramático para nossa história\nR.i.p bravo herói que será lembrado para sempre nos séculos que virão")
score = score + 40
else :
print("No fim da batalha épica o rei demônio prevaleceu, o nome do Herói não será lembrado, a princesa é forçada a casar-se com o rei demônio e os dois reinos travarão uma guerra sangrenta que nunca terá desfexo claro")
score = score + 10
if postura == '3':
print("Você chamou o Rei demônio pra um x1 de shots de Rum")
paladino = int(random.randrange(1,11))
demonio = int(random.randrange(1,11))
print("O Rei demônio deu: ",demonio," shots")
print("O Paladino deu: ",paladino," shots")
if paladino > demonio:
print("Mostra a sua soberania humana em cachaças perante o demônio e o humilha deixando o mesmo vivo.\nLevando a princesa com a qual se casa para o Reino Humano")
score = score + 80
elif paladino == demonio:
print("O duelo lendário termina em empate o Rei demônio se sente humilhado por ter empatado com um mero humano ele se torna um vassalo do Reino Humano,\nvocê retorna com a princesa a qual você protegerá para sempre como seu guarda pessoal")
score = score + 120
else :
print("Você perde para o Rei Demônio na batalha de shots e o mesmo o toma como escravo. A princesa é forçada a casar com o Rei Demônio e os reinos entram em guerra pela eternidade")
score = score - 15
elif dado <=19 and dado >= 16:
time.sleep(0.8)
print("\nVocê mata os guardas com destreza mas o alarme foi tocado")
score = score + 7
print("Após o alarme ser disparado o Paladino corre em direção ao castelo indo para o Hall de entrada do castelo que dava passagem para a sala do trono e quando abre essa porta lá estava a princesa ao lado do Rei Demônio\n\n")
print("(Rei Demônio) -Olá nobre paladino, o que o traz nessa tarde de Domingo?\n(Paladino) -Me devolva a princesa espero que não tenha derramamento de sangue desnecessário Demônio\n(Rei Demônio) -Muita audácia sua projeto de cavaleiro, me responda uma coisa.\nO Demônio Respira fundo e olha nos olhos do paladino com desprezo\n(Rei Demônio) -Depois de todo o esforço que tive para captua-la. Por que a devolveria pra você de mão beijada?")
resposta = input("[1] - Porque você é sábio e gosta de viver\n[2] - Porque isso vai causar uma guerra entre os reinos\n[3] - Porque isso é o certo a se fazer\nQual a sua resposta: ")
if resposta == '1' or resposta == '3' or resposta == '2':
print("(Rei Demônio) -Então vamos lutar projeto de guerreiro, me cansei de VOCÊ!\n\nO Rei se levanta do seu trono e pega sua espada e caminha lentamente na sua direção")
postura=input("\nRESPOSTA RÁPIDA O QUE VOCÊ FAZ?\n[1] - Fica em posição de batalha com a espada em mãos\n[2] - Corre em direção ao rei demônio\n[3] - Você puxa a garrafa de rum e chama o Rei demônio pro x1 de shots\nQual sua escolha? ")
if postura == '1' or postura == '2':
print("Seu status não te atrapalham nem te ajudam nesse momento e a luta será definida em um golpe definido pelo dado")
paladino = int(random.randrange(1,21))
if divindade == '1':
paladino = paladino +3
elif divindade == '2':
paladino = paladino +1
elif divindade == '3':
paladino = paladino -1
else:
print("Escolha inválida")
demonio = int(random.randrange(1,21))
if divindade == '1':
demonio = demonio -2
elif divindade == '2':
demonio = demonio
elif divindade == '3':
demonio = demonio +2
else:
print("Escolha inválida")
print("Dado do Rei Demônio: ", demonio)
print("\nDado do Paladino: ", paladino)
if paladino > demonio:
print("O paladino mata o Rei demônio numa batalha épica e longa de apenas um golpe. Parabéns bravo herói, mesmo ferido você mostrou do que é feito e fez o rei demônio ser chacota pelo resto dos séculos.\n",nome,"se casa com a princesa e após a morte de seu sogro vira Rei do reino humano e será lembrado para sempre")
score = score + 80
elif paladino == demonio:
print("Ocorreu um empate na batalha épica do paladino contra o rei demônio, cada um crava sua espada no coração do oponente, dando um final dramático para nossa história\nRip bravo herói que será lembrado para sempre nos séculos que virão")
score = score + 40
else :
print("No fim da batalha épica o rei demônio prevaleceu, seu nome não será lembrado, a princesa é forçada a casar-se com o rei demônio e os dois reinos travarão uma guerra sangrenta que nunca terá desfexo claro")
score = score + 10
if postura == '3':
print("Você chamou o Rei demônio pra um x1 de shots de Rum")
paladino = int(random.randrange(1,11))
demonio = int(random.randrange(1,11))
print("O Rei demônio deu: ",demonio," shots")
print("O Paladino deu: ",paladino," shots")
if paladino > demonio:
print("Mostra a sua soberania humana em cachaças perante o demônio e o humilha deixando o mesmo vivo.\nLevando a princesa com a qual se casa para o Reino Humano")
score = score + 80
elif paladino == demonio:
print("O duelo lendário termina em empate o Rei demônio se sente humilhado por ter empatado com um mero humano ele se torna um vassalo do Reino Humano, você retorna com a princesa a qual você protegerá para sempre como seu guarda pessoal")
score = score + 120
else :
print("Você perde para o Rei Demônio na batalha de shots e o mesmo o toma como escravo. A princesa é forçada a casar com o Rei Demônio e os reinos entram em guerra pela eternidade")
score = score - 15
elif dado >= 8 and dado <= 15:
time.sleep(0.8)
print("\nMata os guardas mas foi ferido na batalha e com isso sua aventura terá uma maior dificultade daqui pra frente")
score = score -1
print("Após o alarme ser disparado o Paladino corre em direção ao castelo indo para o Hall de entrada do castelo que\ndava passagem para a sala do trono e quando abre essa porta lá estava a princesa ao lado do Rei Demônio\n\n")
print("(Rei Demônio) -Olá nobre paladino, o que o traz nessa tarde de Domingo?\n(Paladino) -Me devolva a princesa! Espero que não tenha derramamento de sangue desnecessário Demônio!\n(Rei Demônio) -MUITA AUDÁCIA SUA SEU PROJETO DE CAVALEIRO!, mas me responda uma coisa...\nO Demônio respira fundo e olha nos olhos do paladino com desprezo\n(Rei Demônio) -Depois de todo o esforço que tive para captura-la. Por que a devolveria pra você de mão beijada?")
resposta = input("[1] - Porque você é sábio e gosta de viver\n[2] - Porque isso vai causar uma guerra entre os reinos\n[3] - Porque isso é o certo a se fazer\nQual a sua resposta: ")
if resposta == '1' or resposta == '3' or resposta == '2':
print("(Rei Demônio) -Então vamos lutar projeto de guerreiro, me cansei de VOCÊ!\n\nO Rei se levanta do seu trono e pega sua espada e caminha lentamente na sua direção")
postura=input("\nRESPOSTA RÁPIDA O QUE VOCÊ FAZ?\n[1] - Fica em posição de batalha com a espada em mãos\n[2] - Corre em direção ao rei demônio\n[3] - Você puxa a garrafa de rum e chama o Rei demônio pro x1 de shots\nQual sua escolha? ")
if postura == '1' or postura == '2':
print("Seus ferimentos te atrapalham nesse momento e a luta será definida em um golpe seu dado será penalizado por sua luta anterior")
paladino = int(random.randrange(1,21))
if divindade == '1':
paladino = paladino +1
elif divindade == '2':
paladino = paladino -1
elif divindade == '3':
paladino = paladino -3
else:
print("Escolha inválida")
demonio = int(random.randrange(1,21))
if divindade == '1':
demonio = demonio -2
elif divindade == '2':
demonio = demonio
elif divindade == '3':
demonio = demonio +2
else:
print("Escolha inválida")
print("Dado do Rei Demônio: ", demonio)
print("\nDado do Paladino: ", paladino)
if paladino > demonio:
print("O paladino mata o Rei demônio numa batalha épica e longa de apenas um golpe. Parabéns bravo herói, mesmo ferido você mostrou do que é feito e fez o rei demônio ser chacota pelo resto dos séculos.\n",nome,"se casa com a princesa e após a morte de seu sogro vira Rei do reino humano e será lembrado para sempre")
score = score + 80
elif paladino == demonio:
print("Ocorreu um empate na batalha épica do paladino contra o rei demônio, cada um crava sua espada no coração do oponente, dando um final dramático para nossa história\nRip bravo herói que será lembrado para sempre nos séculos que virão")
score = score + 40
else :
print("No fim da batalha épica o rei demônio prevaleceu, seu nome não será lembrado, a princesa é forçada a casar-se com o rei demônio e os dois reinos travarão uma guerra sangrenta que nunca terá desfexo claro")
score = score + 10
if postura == '3':
print("")
print("Você chamou o Rei demônio pra um x1 de shots de Rum")
paladino = int(random.randrange(1,11))
demonio = int(random.randrange(1,11))
print("\nO Rei demônio deu: ",demonio," shots")
print("\nO Paladino deu: ",paladino," shots")
if paladino > demonio:
print("Mostra a sua soberania Humana em cachaças perante ao Demônio e o humilha deixando o mesmo vivo.\nLevando a princesa para o Reino Humano e casando-se!")
score = score + 80
elif paladino == demonio:
print("O duelo lendário termina em empate e o Rei Demônio se sente humilhado por ter empatado com um mero humano, ele se torna um vassalo do Reino Humano,\nja você retorna com a princesa a qual você protegerá para sempre como seu guarda pessoal")
score = score + 120
else :
print("Você perde para o Rei Demônio na batalha de shots e o mesmo o toma como escravo. A princesa é forçada a casar com o Rei Demônio e os reinos entram em guerra pela eternidade")
score = score - 15
else :
time.sleep(0.8)
print("\nVocê Morreu")
score = score -100
print("Seu resultado ao final da história foi:",score)
exit()
elif invasao =='2':
score = score + 3
print("\nEscolheu as vielas e chegou a porta dos fundos do castelo e começa a observar o muro e os arredores")
dado = int(random.randrange(1,21))
print("Seu dado de percepção foi: ",dado)
if dado >= 15:
score = score +5
print("Você encontrou a passagem secreta nos fundos do castelo! Tu és um sortudo!\n")
print("O Paladino anda com glória pelo Hall de entrada do castelo que dava passagem para a sala do trono e quando abre essa porta lá estava a princesa ao lado do Rei Demônio\n\n")
print("(Rei Demônio) -Olá nobre paladino, o que o traz nessa tarde de Domingo?\n(Paladino) -Me devolva a princesa espero que não tenha derramamento de sangue desnecessário Demônio\n(Rei Demônio) -Muita audácia sua projeto de cavaleiro, me responda uma coisa.\nO Demônio Respira fundo e olha nos olhos do paladino com desprezo\n(Rei Demônio) -Depois de todo o esforço que tive para captua-la. Por que a devolveria pra você de mão beijada?")
resposta = input("[1] - Porque você é sábio e gosta de viver\n[2] - Porque isso vai causar uma guerra entre os reinos\n[3] - Porque isso é o certo a se fazer\nQual a sua resposta: ")
if resposta == '1' or resposta == '3' or resposta == '2':
print("Você pega um caminho subterrâneo e vai direto para a sala do trono assustando o Rei Demônio que estava bajulando a princesa\n")
print("(Rei Demônio) -Então vamos lutar projeto de guerreiro, me cansei de VOCÊ!\n\nO Rei se levanta do seu trono e pega sua espada e caminha lentamente na sua direção")
postura=input("\nRESPOSTA RÁPIDA O QUE VOCÊ FAZ?\n[1] - Fica em posição de batalha com a espada em mãos\n[2] - Corre em direção ao rei demônio\nQual sua escolha? ")
if postura == '1' or postura == '2':
print("Sua chegada assusta o Rei Demônio que não consegue se concentrar na batalha e será penalizado em seus dados")
paladino = int(random.randrange(1,21))
if divindade == '1':
paladino = paladino +3
elif divindade == '2':
paladino = paladino +1
elif divindade == '3':
paladino = paladino -1
else:
print("Escolha inválida")
demonio = int(random.randrange(1,21))
if divindade == '1':
demonio = demonio -4
elif divindade == '2':
demonio = demonio -2
elif divindade == '3':
demonio = demonio +1
else:
print("Escolha inválida")
print("Dado do Rei Demônio: ", demonio)
print("\nDado do Paladino: ", paladino)
if paladino > demonio:
print("O paladino mata o Rei demônio numa batalha épica e longa de apenas um golpe. Parabéns bravo herói, mesmo ferido você mostrou do que é feito e fez o rei demônio ser chacota pelo resto dos séculos.\n",nome,"se casa com a princesa e após a morte de seu sogro vira Rei do reino humano e será lembrado para sempre")
score = score + 80
elif paladino == demonio:
print("Ocorreu um empate na batalha épica do paladino contra o rei demônio, cada um crava sua espada no coração do oponente, dando um final dramático para nossa história\nRip bravo herói que será lembrado para sempre nos séculos que virão")
score = score + 40
else :
print("No fim da batalha épica o rei demônio prevaleceu, seu nome não será lembrado, a princesa é forçada a casar-se com o rei demônio e os dois reinos travarão uma guerra sangrenta que nunca terá desfexo claro")
score = score + 10
else:
print("Você começa a escalar e conforme sobe fica mais confiante, e quando estava quase alcançando o topo escorrega no pé de apoio e acaba caindo de cabeça no chão acabando ali a nobre aventura do Paladino \n:( RIP...")
score = score - 100
print("Seu resultado ao final da história foi: ",score)
exit()
else:
print("Você se depara com um muro alto do castelo e tenta a escalada nas pedras com anuancias, vamos ver como foi tua proeficiencia *_*")
if dado == 14:
print("Subiu como se tivesse nascido para aquele momento\n")
print("O Paladino anda com glória em direção ao castelo indo para o Hall de entrada do castelo que dava passagem para a sala do trono e\nquando abre essa porta lá estava a princesa ao lado do Rei Demônio\n\n")
print("(Rei Demônio) -Olá nobre paladino, o que o traz nessa tarde de Domingo?\n(Paladino) -Me devolva a princesa espero que não tenha derramamento de sangue desnecessário Demônio\n(Rei Demônio) -Muita audácia sua projeto de cavaleiro, me responda uma coisa...\nO Rei Demônio respira fundo e olho nos olhos do paladino com desprezo\n(Rei Demônio) -Depois de todo o esforço que tive para captua-la. Por que a devolveria pra você de mão beijada?")
resposta = input("[1] - Porque você é sábio e gosta de viver\n[2] - Porque isso vai causar uma guerra entre os reinos\n[3] - Porque isso é o certo a se fazer\nQual a sua resposta: ")
if resposta == '1' or resposta == '3' or resposta == '2':
print("(Rei Demônio) -Então vamos lutar projeto de guerreiro!, me cansei de VOCÊ!\n\nO Rei se levanta do seu trono e pega sua espada e caminha lentamente na sua direção")
postura=input("\nRESPOSTA RÁPIDA O QUE VOCÊ FAZ?\n[1] - Fica em posição de batalha com a espada em mãos\n[2] - Corre em direção ao rei demônio\nQual sua escolha? ")
if postura == '1' or postura == '2':
print("Seus ferimentos te atrapalham nesse momento e a luta será definida em um golpe seu dado será penalizado por sua luta anterior")
paladino = int(random.randrange(1,21))
if divindade == '1':
paladino = paladino +3
elif divindade == '2':
paladino = paladino +1
elif divindade == '3':
paladino = paladino -1
else:
print("Escolha inválida")
demonio = int(random.randrange(1,21))
if divindade == '1':
demonio = demonio -2
elif divindade == '2':
demonio = demonio
elif divindade == '3':
demonio = demonio +2
else:
print("Escolha inválida")
print("Dado do Rei Demônio: ", demonio)
print("\nDado do Paladino: ", paladino)
if paladino > demonio:
print("O paladino mata o Rei demônio numa batalha épica e longa de apenas um golpe. Parabéns bravo herói, mesmo ferido você mostrou do que é feito e fez o rei demônio ser chacota pelo resto dos séculos.\n",nome,"se casa com a princesa e após a morte de seu sogro vira Rei do reino humano e será lembrado para sempre")
score = score + 80
elif paladino == demonio:
print("Ocorreu um empate na batalha épica do paladino contra o rei demônio, cada um crava sua espada no coração do oponente, dando um final dramático para nossa história\nRip bravo herói que será lembrado para sempre nos séculos que virão")
score = score + 40
else :
print("No fim da batalha épica o rei demônio prevaleceu, seu nome não será lembrado, a princesa é forçada a casar-se com o rei demônio e os dois reinos travarão uma guerra sangrenta que nunca terá desfexo claro")
score = score + 10
elif dado >=8 and dado <= 13:
print("Subiu com dificuldade e para um pouco no topo muralha para respirar fundo e recuperar o folêgo\n")
print("O Paladino anda em direção ao castelo indo para o Hall de entrada do castelo que dava passagem para a sala do trono e quando abre essa porta lá estava a princesa ao lado do Rei Demônio\n\n")
print("(Rei Demônio) -Olá nobre paladino, o que o traz nessa tarde de Domingo?\n(Paladino) -Me devolva a princesa espero que não tenha derramamento de sangue desnecessário Demônio\n(Rei Demônio) -Muita audácia sua projeto de cavaleiro, me responda uma coisa \nO Rei Demônio respira fundo e olho nos olhos do paladino com desprezo\n(Rei Demônio) -Depois de todo o esforço que tive para captua-la. Por que a devolveria pra você de mão beijada?")
resposta = input("[1] - Porque você é sábio e gosta de viver\n[2] - Porque isso vai causar uma guerra entre os reinos\nQual a sua resposta: ")
if resposta == '1' or resposta == '3' or resposta == '2':
print("(Rei Demônio) - Então vamos lutar projeto de guerreiro, me cansei de VOCÊ!\n\nO Rei se levanta do seu trono e pega sua espada e caminha lentamente na sua direção")
postura=input("\nRESPOSTA RÁPIDA O QUE VOCÊ FAZ?\n1 - Fica em posição de batalha com a espada em mãos\n2 - Corre em direção ao rei demônio\n3 - Você puxa a garrafa de rum e chama o Rei demônio pro x1 de shots\nQual sua escolha? ")
if postura == '1' or postura == '2':
print("Seus ferimentos te atrapalham nesse momento e a luta será definida em um golpe seu dado será penalizado por sua luta anterior")
paladino = int(random.randrange(1,21))
if divindade == '1':
paladino = paladino +3
elif divindade == '2':
paladino = paladino +1
elif divindade == '3':
paladino = paladino -1
else:
print("Escolha inválida")
demonio = int(random.randrange(1,21))
if divindade == '1':
demonio = demonio -2
elif divindade == '2':
demonio = demonio
elif divindade == '3':
demonio = demonio +2
else:
print("Escolha inválida")
print("Dado do Rei Demônio: ", demonio)
print("\nDado do Paladino: ", paladino)
if paladino > demonio:
print("O paladino mata o Rei demônio numa batalha épica e longa de apenas um golpe. Parabéns bravo herói, mesmo ferido você mostrou do que é feito e fez o rei demônio ser chacota pelo resto dos séculos.\n",nome,"se casa com a princesa e após a morte de seu sogro vira Rei do reino humano e será lembrado para sempre")
score = score + 80
elif paladino == demonio:
print("Ocorreu um empate na batalha épica do paladino contra o rei demônio, cada um crava sua espada no coração do oponente, dando um final dramático para nossa história\nRip bravo herói que será lembrado para sempre nos séculos que virão")
score = score + 40
else :
print("No fim da batalha épica o rei demônio prevaleceu, seu nome não será lembrado, a princesa é forçada a casar-se com o rei demônio e os dois reinos travarão uma guerra sangrenta que nunca terá desfexo claro")
score = score + 10
if postura == '3':
print("Você chamou o Rei demônio pra um x1 de shots de Rum")
paladino = int(random.randrange(1,11))
demonio = int(random.randrange(1,11))
print("O Rei demônio deu: ",demonio," shots")
print("O Paladino deu: ",paladino," shots")
if paladino > demonio:
print("Mostra a sua soberania humana em cachaças perante o demônio e o humilha deixando o mesmo vivo.\nLevando a princesa com a qual se casa para o Reino Humano")
score = score + 80
elif paladino == demonio:
print("O duelo lendário termina em empate o Rei demônio se sente humilhado por ter empatado com um mero humano ele se torna um vassalo do Reino Humano, você retorna com a princesa a qual você protegerá para sempre como seu guarda pessoal")
score = score + 120
else :
print("Você perde para o Rei Demônio na batalha de shots e o mesmo o toma como escravo. A princesa é forçada a casar com o Rei Demônio e os reinos entram em guerra pela eternidade")
score = score - 15
elif dado >= 5 and dado <=7:
print("Depois de ter subido 2 metros no muro você escorregou e caiu de bunda no chão e depois de passar vergonha o Paladino se levanta e escala o muro nervoso e com êxito dessa vez\n")
print("O Paladino anda com vergonha em direção ao castelo indo para o Hall de entrada do castelo que dava passagem para a sala do trono e quando abre essa porta lá estava a princesa ao lado do Rei Demônio\n\n")
print("(Rei Demônio) -Olá nobre paladino, o que o traz nessa tarde de Domingo?\n(Paladino) -Me devolva a princesa espero que não tenha derramamento de sangue desnecessário Demônio\n(Rei Demônio) -Muita audácia sua projeto de cavaleiro, me responda uma coisa...\nO Rei Demônio Respira fundo e olho nos olhos do paladino com desprezo\n(Rei Demônio) -Depois de todo o esforço que tive para captua-la. Por que a devolveria pra você de mão beijada?")
resposta = input("[1] - Porque você é sábio e gosta de viver\n[2] - Porque isso vai causar uma guerra entre os reinos\n[3] - Porque isso é o certo a se fazer\nQual a sua resposta: ")
if resposta == '1' or resposta == '3' or resposta == '2':
print("(Rei Demônio) -Então vamos lutar projeto de guerreiro, me cansei de VOCÊ!\n\nO Rei se levanta do seu trono e pega sua espada e caminha lentamente na sua direção")
postura=input("\nRESPOSTA RÁPIDA O QUE VOCÊ FAZ?\n[1] - Fica em posição de batalha com a espada em mãos\n[2] - Corre em direção ao rei demônio\nQual sua escolha? ")
if postura == '1' or postura == '2':
print("Seus ferimentos te atrapalham nesse momento e a luta será definida em um golpe seu dado será penalizado por sua luta anterior\n")
paladino = int(random.randrange(1,21))
if divindade == '1':
paladino = paladino +3
elif divindade == '2':
paladino = paladino +1
elif divindade == '3':
paladino = paladino -1
else:
print("Escolha inválida")
demonio = int(random.randrange(1,21))
if divindade == '1':
demonio = demonio -2
elif divindade == '2':
demonio = demonio
elif divindade == '3':
demonio = demonio +2
else:
print("Escolha inválida")
print("Dado do Rei Demônio: ", demonio)
print("\nDado do Paladino: ", paladino)
if paladino > demonio:
print("O paladino mata o Rei demônio numa batalha épica e longa de apenas um golpe. Parabéns bravo herói, mesmo ferido você mostrou do que é feito e fez o rei demônio ser chacota pelo resto dos séculos.\n",nome,"se casa com a princesa e após a morte de seu sogro vira Rei do reino humano e será lembrado para sempre")
score = score + 80
elif paladino == demonio:
print("Ocorreu um empate na batalha épica do paladino contra o rei demônio, cada um crava sua espada no coração do oponente, dando um final dramático para nossa história\nRip bravo herói que será lembrado para sempre nos séculos que virão")
score = score + 40
else :
print("No fim da batalha épica o rei demônio prevaleceu, seu nome não será lembrado, a princesa é forçada a casar-se com o rei demônio e os dois reinos travarão uma guerra sangrenta que nunca terá desfexo claro")
score = score + 10
else:
print("Você começa a escalar e conforme sobe fica mais confiante, e quando estava quase alcançando o topo escorrega no pé de apoio e acaba caindo de cabeça no chão acabando ali a nobre aventura do Paladino \n:( RIP...")
score = score - 100
print("Seu resultado ao final da história foi: ",score)
exit()
elif caminho == '2':
score = score + 3
print("\nEscolheu as vielas e chegou a porta dos fundos do castelo e começa a observar o muro e os arredores")
dado = int(random.randrange(1,21))
print("Seu dado de percepção foi: ",dado)
if dado >= 15:
score = score +5
print("Você encontrou a passagem secreta nos fundos do castelo! Tu és um sortudo!\n")
print("O Paladino anda com glória pelo Hall de entrada do castelo que dava passagem para a sala do trono e quando abre essa porta lá estava a princesa ao lado do Rei Demônio\n\n")
print("(Rei Demônio) -Olá nobre paladino, o que o traz nessa tarde de Domingo?\n(Paladino) -Me devolva a princesa espero que não tenha derramamento de sangue desnecessário Demônio\n(Rei Demônio) -Muita audácia sua projeto de cavaleiro, me responda uma coisa.\nO Demônio Respira fundo e olha nos olhos do paladino com desprezo\n(Rei Demônio) -Depois de todo o esforço que tive para captua-la. Por que a devolveria pra você de mão beijada?")
resposta = input("[1] - Porque você é sábio e gosta de viver\n[2] - Porque isso vai causar uma guerra entre os reinos\n[3] - Porque isso é o certo a se fazer\nQual a sua resposta: ")
if resposta == '1' or resposta == '3' or resposta == '2':
print("Você pega um caminho subterrâneo e vai direto para a sala do trono assustando o Rei Demônio que estava bajulando a princesa\n")
print("(Rei Demônio) -Então vamos lutar projeto de guerreiro, me cansei de VOCÊ!\n\nO Rei se levanta do seu trono e pega sua espada e caminha lentamente na sua direção")
postura=input("\nRESPOSTA RÁPIDA O QUE VOCÊ FAZ?\n[1] - Fica em posição de batalha com a espada em mãos\n[2] - Corre em direção ao rei demônio\nQual sua escolha? ")
if postura == '1' or postura == '2':
print("Sua chegada assusta o Rei Demônio que não consegue se concentrar na batalha e será penalizado em seus dados")
paladino = int(random.randrange(1,21))
if divindade == '1':
paladino = paladino +3
elif divindade == '2':
paladino = paladino +1
elif divindade == '3':
paladino = paladino -1
else:
print("Escolha inválida")
demonio = int(random.randrange(1,21))
if divindade == '1':
demonio = demonio -4
elif divindade == '2':
demonio = demonio -2
elif divindade == '3':
demonio = demonio +1
else:
print("Escolha inválida")
print("Dado do Rei Demônio: ", demonio)
print("\nDado do Paladino: ", paladino)
if paladino > demonio:
print("O paladino mata o Rei demônio numa batalha épica e longa de apenas um golpe. Parabéns bravo herói, mesmo ferido você mostrou do que é feito e fez o rei demônio ser chacota pelo resto dos séculos.\n",nome,"se casa com a princesa e após a morte de seu sogro vira Rei do reino humano e será lembrado para sempre")
score = score + 80
elif paladino == demonio:
print("Ocorreu um empate na batalha épica do paladino contra o rei demônio, cada um crava sua espada no coração do oponente, dando um final dramático para nossa história\nRip bravo herói que será lembrado para sempre nos séculos que virão")
score = score + 40
else :
print("No fim da batalha épica o rei demônio prevaleceu, seu nome não será lembrado, a princesa é forçada a casar-se com o rei demônio e os dois reinos travarão uma guerra sangrenta que nunca terá desfexo claro")
score = score + 10
else:
print("Você começa a escalar e conforme sobe fica mais confiante, e quando estava quase alcançando o topo escorrega no pé de apoio e acaba caindo de cabeça no chão acabando ali a nobre aventura do Paladino \n:( RIP...")
score = score - 100
print("Seu resultado ao final da história foi: ",score)
exit()
else:
print("Você se depara com um muro alto do castelo e tenta a escalada nas pedras com anuancias, vamos ver como foi tua proeficiencia *_*")
if dado == 14:
print("Subiu como se tivesse nascido para aquele momento\n")
print("O Paladino anda com glória em direção ao castelo indo para o Hall de entrada do castelo que dava passagem para a sala do trono e\nquando abre essa porta lá estava a princesa ao lado do Rei Demônio\n\n")
print("(Rei Demônio) -Olá nobre paladino, o que o traz nessa tarde de Domingo?\n(Paladino) -Me devolva a princesa espero que não tenha derramamento de sangue desnecessário Demônio\n(Rei Demônio) -Muita audácia sua projeto de cavaleiro, me responda uma coisa...\nO Rei Demônio respira fundo e olho nos olhos do paladino com desprezo\n(Rei Demônio) -Depois de todo o esforço que tive para captua-la. Por que a devolveria pra você de mão beijada?")
resposta = input("[1] - Porque você é sábio e gosta de viver\n[2] - Porque isso vai causar uma guerra entre os reinos\n[3] - Porque isso é o certo a se fazer\nQual a sua resposta: ")
if resposta == '1' or resposta == '3' or resposta == '2':
print("(Rei Demônio) -Então vamos lutar projeto de guerreiro!, me cansei de VOCÊ!\n\nO Rei se levanta do seu trono e pega sua espada e caminha lentamente na sua direção")
postura=input("\nRESPOSTA RÁPIDA O QUE VOCÊ FAZ?\n[1] - Fica em posição de batalha com a espada em mãos\n[2] - Corre em direção ao rei demônio\nQual sua escolha? ")
if postura == '1' or postura == '2':
print("Seus ferimentos te atrapalham nesse momento e a luta será definida em um golpe seu dado será penalizado por sua luta anterior")
paladino = int(random.randrange(1,21))
if divindade == '1':
paladino = paladino +3
elif divindade == '2':
paladino = paladino +1
elif divindade == '3':
paladino = paladino -1
else:
print("Escolha inválida")
demonio = int(random.randrange(1,21))
if divindade == '1':
demonio = demonio -2
elif divindade == '2':
demonio = demonio
elif divindade == '3':
demonio = demonio +2
else:
print("Escolha inválida")
print("Dado do Rei Demônio: ", demonio)
print("\nDado do Paladino: ", paladino)
if paladino > demonio:
print("O paladino mata o Rei demônio numa batalha épica e longa de apenas um golpe. Parabéns bravo herói, mesmo ferido você mostrou do que é feito e fez o rei demônio ser chacota pelo resto dos séculos.\n",nome,"se casa com a princesa e após a morte de seu sogro vira Rei do reino humano e será lembrado para sempre")
score = score + 80
elif paladino == demonio:
print("Ocorreu um empate na batalha épica do paladino contra o rei demônio, cada um crava sua espada no coração do oponente, dando um final dramático para nossa história\nRip bravo herói que será lembrado para sempre nos séculos que virão")
score = score + 40
else :
print("No fim da batalha épica o rei demônio prevaleceu, seu nome não será lembrado, a princesa é forçada a casar-se com o rei demônio e os dois reinos travarão uma guerra sangrenta que nunca terá desfexo claro")
score = score + 10
elif dado >=8 and dado <= 13:
print("Subiu com dificuldade e para um pouco no topo muralha para respirar fundo e recuperar o folêgo\n")
print("O Paladino anda em direção ao castelo indo para o Hall de entrada do castelo que dava passagem para a sala do trono e quando abre essa porta lá estava a princesa ao lado do Rei Demônio\n\n")
print("(Rei Demônio) -Olá nobre paladino, o que o traz nessa tarde de Domingo?\n(Paladino) -Me devolva a princesa espero que não tenha derramamento de sangue desnecessário Demônio\n(Rei Demônio) -Muita audácia sua projeto de cavaleiro, me responda uma coisa.\nO Rei Demônio respira fundo e olho nos olhos do paladino com desprezo\n(Rei Demônio) -Depois de todo o esforço que tive para captua-la. Por que a devolveria pra você de mão beijada?")
resposta = input("[1] - Porque você é sábio e gosta de viver\n[2] - Porque isso vai causar uma guerra entre os reinos\nQual a sua resposta: ")
if resposta == '1' or resposta == '3' or resposta == '2':
print("(Rei Demônio) - Então vamos lutar projeto de guerreiro, me cansei de VOCÊ!\n\nO Rei se levanta do seu trono e pega sua espada e caminha lentamente na sua direção")
postura=input("\nRESPOSTA RÁPIDA O QUE VOCÊ FAZ?\n1 - Fica em posição de batalha com a espada em mãos\n2 - Corre em direção ao rei demônio\n3 - Você puxa a garrafa de rum e chama o Rei demônio pro x1 de shots\nQual sua escolha? ")
if postura == '1' or postura == '2':
print("Seus ferimentos te atrapalham nesse momento e a luta será definida em um golpe seu dado será penalizado por sua luta anterior")
paladino = int(random.randrange(1,21))
if divindade == '1':
paladino = paladino +3
elif divindade == '2':
paladino = paladino +1
elif divindade == '3':
paladino = paladino -1
else:
print("Escolha inválida")
demonio = int(random.randrange(1,21))
if divindade == '1':
demonio = demonio -2
elif divindade == '2':
demonio = demonio
elif divindade == '3':
demonio = demonio +2
else:
print("Escolha inválida")
print("Dado do Rei Demônio: ", demonio)
print("\nDado do Paladino: ", paladino)
if paladino > demonio:
print("O paladino mata o Rei demônio numa batalha épica e longa de apenas um golpe. Parabéns bravo herói, mesmo ferido você mostrou do que é feito e fez o rei demônio ser chacota pelo resto dos séculos.\n",nome,"se casa com a princesa e após a morte de seu sogro vira Rei do reino humano e será lembrado para sempre")
score = score + 80
elif paladino == demonio:
print("Ocorreu um empate na batalha épica do paladino contra o rei demônio, cada um crava sua espada no coração do oponente, dando um final dramático para nossa história\nRip bravo herói que será lembrado para sempre nos séculos que virão")
score = score + 40
else :
print("No fim da batalha épica o rei demônio prevaleceu, seu nome não será lembrado, a princesa é forçada a casar-se com o rei demônio e os dois reinos travarão uma guerra sangrenta que nunca terá desfexo claro")
score = score + 10
elif dado >= 5 and dado <=7:
print("Depois de ter subido 2 metros no muro você escorregou e caiu de bunda no chão e depois de passar vergonha o Paladino se levanta e escala o muro nervoso e com êxito dessa vez\n")
print("O Paladino anda com vergonha em direção ao castelo indo para o Hall de entrada do castelo que dava passagem para a sala do trono e quando abre essa porta lá estava a princesa ao lado do Rei Demônio\n\n")
print("(Rei Demônio) -Olá nobre paladino, o que o traz nessa tarde de Domingo?\n(Paladino) -Me devolva a princesa espero que não tenha derramamento de sangue desnecessário Demônio\n(Rei Demônio) -Muita audácia sua projeto de cavaleiro, me responda uma coisa...\n O Rei Demônio Respira fundo e olho nos olhos do paladino com desprezo\n(Rei Demônio) -Depois de todo o esforço que tive para captua-la. Por que a devolveria pra você de mão beijada?")
resposta = input("[1] - Porque você é sábio e gosta de viver\n[2] - Porque isso vai causar uma guerra entre os reinos\n[3] - Porque isso é o certo a se fazer\nQual a sua resposta: ")
if resposta == '1' or resposta == '3' or resposta == '2':
print("(Rei Demônio) -Então vamos lutar projeto de guerreiro, me cansei de VOCÊ!\n\nO Rei se levanta do seu trono e pega sua espada e caminha lentamente na sua direção")
postura=input("\nRESPOSTA RÁPIDA O QUE VOCÊ FAZ?\n[1] - Fica em posição de batalha com a espada em mãos\n[2] - Corre em direção ao rei demônio\nQual sua escolha? ")
if postura == '1' or postura == '2':
print("Seus ferimentos te atrapalham nesse momento e a luta será definida em um golpe seu dado será penalizado por sua luta anterior\n")
paladino = int(random.randrange(1,21))
if divindade == '1':
paladino = paladino +3
elif divindade == '2':
paladino = paladino +1
elif divindade == '3':
paladino = paladino -1
else:
print("Escolha inválida")
demonio = int(random.randrange(1,21))
if divindade == '1':
demonio = demonio -2
elif divindade == '2':
demonio = demonio
elif divindade == '3':
demonio = demonio +2
else:
print("Escolha inválida")
print("Dado do Rei Demônio: ", demonio)
print("\nDado do Paladino: ", paladino)
if paladino > demonio:
print("O paladino mata o Rei demônio numa batalha épica e longa de apenas um golpe. Parabéns bravo herói, mesmo ferido você mostrou do que é feito e fez o rei demônio ser chacota pelo resto dos séculos.\n",nome,"se casa com a princesa e após a morte de seu sogro vira Rei do reino humano e será lembrado para sempre")
score = score + 80
elif paladino == demonio:
print("Ocorreu um empate na batalha épica do paladino contra o rei demônio, cada um crava sua espada no coração do oponente, dando um final dramático para nossa história\nRip bravo herói que será lembrado para sempre nos séculos que virão")
score = score + 40
else :
print("No fim da batalha épica o rei demônio prevaleceu, seu nome não será lembrado, a princesa é forçada a casar-se com o rei demônio e os dois reinos travarão uma guerra sangrenta que nunca terá desfexo claro")
score = score + 10
else:
print("Você começa a escalar e conforme sobe fica mais confiante, e quando estava quase alcançando o topo escorrega no pé de apoio e acaba caindo de cabeça no chão acabando ali a nobre aventura do Paladino \n:( RIP...")
score = score - 100
print("Seu resultado ao final da história foi: ",score)
exit()
else:
print("Escolha inválida, mais atenção na próxima!")
exit()
else:
print("Gênero Inválido")
exit()
print("O resultado final foi: ",score)
#Deusa da Ordem (Facil)
if score <= 0 and divindade == '1':
print("Você fracassou em sua Missão, a Deusa da Ordem esta decepcionada com você, seu fracassado!")
if score > 0 and score < 50 and divindade== '1':
print("Você pelo menos tentou, mas faça melhor na proxima reencarnação, a Deusa da Ordem confia em ti!")
if score >= 50 and score < 100 and divindade== '1':
print("Você lutou bravamente meu grande Paladino, Não desistas na proxima reencarnação, a Deusa da Ordem ficou contente com seus resultados. ")
if score >= 100 and divindade== '1':
print("Oh!, meu grande paladino...Por tamanha coragem, astusia e grandiosidade...\nVocê herdara este reino ao lado da sua princesa resgatada\nSua Deusa da Ordem agradece por tamanha lealdade, que a paz estejas entre vós para sempre! ")
#Deusa da Justiça (Média)
if score <= 0 and divindade== '2':
print("Você fracassou em sua Missão, a Deusa da Justiça esta decepcionada com você, seu fracassado!")
if score > 0 and score < 50 and divindade== '2':
print("Você pelo menos tentou, mas faça melhor na proxima reencarnação, a Deusa da Justiça confia em ti!")
if score >= 50 and score < 100 and divindade== '2':
print("Você lutou bravamente meu grande Paladino, Não desistas na proxima reencarnação, a Deusa da Justiça ficou contente com seus resultados. ")
if score >= 100 and divindade== '2':
print("Oh!, meu grande paladino...Por tamanha coragem, astusia e grandiosidade...\nVocê herdara este reino ao lado da sua princesa resgatada\nSua Deusa da Justiça agradece por tamanha lealdade, que a paz estejas entre vós para sempre! ")
#Deusa do Caos (Dificil)
if score <= 0 and divindade== '3':
print("Você fracassou em sua Missão, a Deusa do Caos esta decepcionada com você, seu fracassado!")
if score > 0 and score < 50 and divindade== '3':
print("Você pelo menos tentou, mas faça melhor na proxima reencarnação, a Deusa do Caos confia em ti!")
if score >= 50 and score < 100 and divindade== '3':
print("Você lutou bravamente meu grande Paladino, Não desistas na proxima reencarnação, a Deusa do Caos ficou contente com seus resultados. ")
if score >= 100 and divindade== '3':
print("Oh!, meu grande paladino...Por tamanha coragem, astusia e grandiosidade...\nVocê herdara este reino ao lado da sua princesa resgatada\nSua Deusa do Caos agradece por tamanha lealdade, que a paz estejas entre vós para sempre! ")
|
9ef756df9f9b18607b42121f9500007f9bcbaf64 | johngarrett/hackCOVID | /src/Grid.py | 3,283 | 4 | 4 | import math
import random
from Desk import Desk
"""
Grids are laid out so that the origin is the top left corner of the office/map/etc.
"""
class Grid:
def __init__(self,
height: int,
length: int,
desk_x: float = 1.0,
desk_y: float = 1.0,
grid: [[int]] = None):
if height < 1 or length < 1:
raise ValueError("height or length cannot be 0")
self.height = height
self.length = length
self.desk_dim = (desk_x, desk_y)
if grid:
self.grid = grid
else:
self.grid = [[None for i in range(length)] for j in range(height)]
def set_desk(self, x: int, y: int, d: Desk) -> Desk:
"""
Put a desk object at position (x,y) in our grid.
"""
ret = self.grid[x][y]
self.grid[x][y] = d
return ret
def get_desk(self, x: int, y: int) -> Desk:
return self.grid[x][y]
def seating(self, social_distance: float) -> [(int, int)]:
"""
DFS algorithm to create a list of desks that are:
1) properly socially distanced and
2) valid places to sit (according to our office layout)
"""
searched_desks = []
good_desks = []
unsearched_desks = [(0,0)]
while len(unsearched_desks) > 0:
(dx, dy) = unsearched_desks.pop()
searched_desks.append((dx, dy))
next_desks = [
(min(dx + i, self.height - 1), min(dy + j, self.length - 1))
for i in range(2) for j in range(2)
]
for d in next_desks:
if d in searched_desks:
continue
else:
unsearched_desks.append(d)
desk_obj = self.grid[d[0]][d[1]]
if not desk_obj or desk_obj.is_obstruction:
continue
if desk_is_properly_spaced(d, good_desks, social_distance, self.desk_dim):
good_desks.append(d)
return good_desks
def __repr__(self) -> str:
s = ""
for row in self.grid:
s += " ".join(["_" if not d
else "|" if d.is_obstruction
else "*" # if d is a desk
for d in row])
s += "\n"
return s
def desk_is_properly_spaced(d: (int,int), others: [(int,int)], social_distance: float, desk_dim: (float, float)) -> bool:
"""
Check that a particular desk is a certain distance from others in a list.
"""
for o in others:
dz = math.sqrt(((d[0]-o[0])/desk_dim[0])**2 + ((d[1]-o[1])/desk_dim[1])**2)
if dz <= social_distance:
return False
return True
if __name__ == "__main__":
g = Grid(10, 10)
for i in range(20):
g.set_desk(random.randint(0,9), random.randint(0,9), Desk(is_obstruction = int(random.randint(0,1))))
print(g)
seats = g.seating(1)
for i in range(10):
for j in range(10):
d = g.get_desk(i,j)
if not d or d.is_obstruction:
continue
if (i,j) not in seats:
g.set_desk(i,j, None)
print()
print(g)
|
670a2f69fb144ba21c9cdb6fd5ac94a93127a1ea | jbial/daily-coding | /dailycoding053.py | 1,431 | 4.125 | 4 | """
This problem was asked by Apple.
Implement a queue using two stacks. Recall that a queue is a FIFO
(first-in, first-out) data structure with the following methods:
enqueue, which inserts an element into the queue, and dequeue, which removes it.
Solution:
Continually push elements to the first stack for the enqueue operation, and for the
dequeue operation, flip all elements in the stack onto the second stack to retrieve
the first in element. This works even when enqueuing new elements onto stack one.
"""
class Queue:
def __init__(self):
self.s1 = list()
self.s2 = list()
def enqueue(self, elem):
self.s1.append(elem)
def dequeue(self):
if len(self.s2) == 0:
while len(self.s1) > 0:
self.s2.append(self.s1.pop())
return self.s2.pop()
def main():
q = Queue()
# add test elements
for i in range(10):
q.enqueue(i)
# dequeue first 5 elements
for i in range(5):
assert q.dequeue() == i, print("Failed")
# add three elements
for i in range(3):
q.enqueue(i + 3)
# check remaining 5 elements are properly dequeued
for i in range(5):
assert q.dequeue() == i + 5, print("Failed")
# check remaining elements dequeued are correct
for i in range(3):
assert q.dequeue() == i + 3, print("Failed")
print("Passed")
if __name__ == '__main__':
main()
|
0751a3a070add3c4cc6b95de450567cfbc4af975 | patcoet/Advent-of-Code | /2017/03/1.py | 1,342 | 3.828125 | 4 | # Given a number, returns the layer it's on (starting at 0)
def layer(x):
for i in range(x):
# Layer i contains numbers ((2*(i-1) + 1)^2 + 1) to ((2*i + 1)^2)
if (i*2 + 1)**2 >= x:
return i
# Given a layer, returns the smallest number in it
def smallest(layer):
if layer == 0:
return 1
else:
return (2*(layer - 1) + 1)**2 + 1
def largest(layer):
return (2*layer + 1)**2
# If we know the input number is on layer k, we know that the distance is
# between k (if it's straight up/down/left/right) and 2*k (if it's in a
# corner), so if we start at smallest(k) and oscillate between those values...
def distance_to_origin(inputt):
input_layer = layer(inputt)
smallest_value_in_layer = smallest(input_layer)
largest_value_in_layer = largest(input_layer)
minimum_possible_steps = input_layer
maximum_possible_steps = input_layer * 2
incrementing_result = False
result = input_layer * 2
for i in range(largest_value_in_layer, smallest_value_in_layer, -1):
if i == inputt:
return result
else:
if result == minimum_possible_steps:
incrementing_result = True
elif result == maximum_possible_steps:
incrementing_result = False
if incrementing_result:
result = result + 1
else:
result = result - 1
print(distance_to_origin(265149)) |
8be6d9e8ecc8f2570e34e638a35e901fdb1fec99 | li-mo-feng/Python | /PythonProjects/面试宝典/字符串操作.py | 302 | 3.984375 | 4 | i='name'
print(i.startswith('m'))
# 判断是否以XX开头并返回结果
print(i.endswith('e'))
# 判断是否以XX结尾并返回结果
print(i.replace('a','f'))
# 字符串内容替换
print(i.split('a'))
# 以a字符进行分割
print(i[2])
# 输出字符串的第三个字符
print(i.index('m'))
|
2bdbdbf76f7b0f99c4cc3dee93958406b168002e | mjjin1214/algorithm | /190218_binary_search.py | 424 | 3.625 | 4 | import sys
sys.stdin = open('input.txt', 'r')
data = list(map(int, input().split()))
def binary(list_x, x):
start, end = 0, len(list_x)-1
while end < start:
mid = (start + end) // 2
if list_x[mid] == x:
return mid
else:
if list_x[mid] > x:
end = mid-1
else:
start = mid+1
return 'not exist'
print(binary(data, 2)) |
62631c6595a2731b08bf5852876d8b0da628bdf2 | AgenttiX/random | /gmail_filter.py | 2,369 | 3.578125 | 4 | """
This is a simple program to create Gmail compatible domain filters (for spam etc.)
Created by Mika "AgenttiX" Mäki, 2016
"""
filename = "domains.txt"
class Spam:
def __init__(self):
self.__domainlist = []
def readfile(self):
""" Reads the domains from a predetermined file """
try:
with open(filename, mode="r") as fileobject:
for line in fileobject:
line = line.rstrip()
self.__domainlist.append(line)
fileobject.close()
except:
print("Error when reading file")
def getlist(self):
""" Returns the domains in a Gmail compatible string """
self.__domainlist.sort()
outstr = "{ "
for index, domain in enumerate(self.__domainlist):
outstr += domain + " "
if (index % 50 == 0) and index > 0:
outstr += "}\n{ "
outstr += "}"
return outstr
def add(self, newaddress):
"""
Adds a new address to the list
:param newaddress: A new address example@example.com as a string
:return: -
"""
list = newaddress.split("@")
newdomain = list[-1]
if not newdomain in self.__domainlist:
self.__domainlist.append(newdomain)
else:
print("Domain is already in the database")
def write(self):
""" Writes the list to a predetermined file"""
self.__domainlist.sort()
try:
fileobject = open(filename, mode="w")
for domain in self.__domainlist:
fileobject.write(domain + "\n")
fileobject.close()
except:
print("Error when writing file")
def main():
# Creates a new instance of the domain handler
spam = Spam()
# UI loop
while True:
print("> ", end="")
inputstr = input()
command = inputstr.split(" ")
if command[0] == "q":
break
elif command[0] == "read":
spam.readfile()
elif command[0] == "print":
print(spam.getlist())
elif command[0] == "add":
try:
spam.add(command[1])
except:
print("Error")
elif command[0] == "write":
spam.write()
if __name__ == "__main__":
main()
|
62de955cf09f62705fa81b2156f9f2c296d52f6d | ReethP/Kattis-Solutions | /heliocentric.py | 370 | 3.5 | 4 | while True:
try:
for i in range(0,10):
earth, mars = input().split()
earth = int(earth)
mars = int(mars)
totaldays = 0
while(earth != mars):
earth = earth+1
mars = mars+1
totaldays = totaldays+1
if(earth == 365):
earth = 0
if(mars == 687):
mars = 0
print("Case",i+1,end="")
print(":", totaldays)
except:
break |
121d2e8a922eb9c5cb66a4bbbd39f835440d7b40 | childe/leetcode | /diagonal-traverse/solution.py | 1,741 | 4.25 | 4 | # -*- coding: utf-8 -*-
'''
https://leetcode-cn.com/problems/diagonal-traverse/
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,000.
'''
class Solution(object):
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0:
return []
i, j, rst = 0, 0, []
d = 1
while True:
# print(i, j, matrix[i][j], rst)
rst.append(matrix[i][j])
if i == len(matrix)-1 and j == len(matrix[-1])-1:
break
if d == 1:
if j == len(matrix[i])-1:
i += 1
d = -d
continue
if i == 0:
j += 1
d = -d
continue
i -= 1
j += 1
else:
if i == len(matrix) - 1:
j += 1
d = -d
continue
if j == 0:
i += 1
d = -d
continue
i += 1
j -= 1
return rst
def main():
s = Solution()
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
output = [1, 2, 4, 7, 5, 3, 6, 8, 9]
a = s.findDiagonalOrder(matrix)
print(a)
assert(a == output)
if __name__ == '__main__':
main()
|
5d315cee74ec974ca84729e60201f206a868a056 | huangyuzhen/let | /94/walk.py | 3,006 | 3.953125 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def walk(self, root, result):
if root:
self.walk(root.left, result)
result.append(root.val)
self.walk(root.right, result)
def inorderTraversal(self, root):
result = []
self.walk(root, result)
return result
def inorderTraversal0(self, root):
f = self.inorderTraversal0
return f(root.left) + [root.val] + f(root.right) if root else []
def inorderTraversal1(self, root):
result = []
stack = []
node = root
while node or stack:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
result.append(node.val)
node = node.right
return result
def inorderTraversal2(self, root):
result = []
stack = [root]
while stack:
node = stack.pop()
if hasattr(node, 'traversalFlag') and node.traversalFlag:
del(node.traversalFlag)
result.append(node.val)
else:
if node.right:
stack.append(node.right)
node.traversalFlag = True
stack.append(node)
if node.left:
stack.append(node.left)
return result
def inorderTraversal22(self, root):
WHITE, GRAY = 0, 1
result = []
stack = [(WHITE, root)]
while stack:
color, node = stack.pop()
if not node: continue
if color == WHITE:
stack.append((WHITE, node.right))
stack.append((GRAY, node))
stack.append((WHITE, node.left))
else:
result.append(node.val)
return result
def inorderTraversal3(self, root):
result = []
node = root
while node:
if not node.left:
result.append(node.val)
node = node.right
else:
newTop = node.left
node.left = None
rightMost = newTop
while rightMost.right:
rightMost = rightMost.right
rightMost.right = node
node = newTop
return result
def initData():
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(6)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right.left = TreeNode(5)
root.right.right = TreeNode(7)
return root
root = initData()
solution = Solution()
print(solution.inorderTraversal0(root))
print(solution.inorderTraversal1(root))
print(solution.inorderTraversal2(root))
print(solution.inorderTraversal22(root))
print(solution.inorderTraversal3(root))
|
b203919789491ec16d9d3030ef29ebab9333dbb5 | RSnoad/Python-Problems | /Problem 15.py | 556 | 4 | 4 | # Find the number of possible routes from top left to bottom right for an n x n grid, only by moving right or down.
from math import factorial
# Use Binomial coefficient formula for n choose r = n! / (r! = (n-r)!)
# Our n = 2 * size of grid as this is the total number of choices we need to make to reach the end.
# Our r = size of grid as this is the total number options to choose when getting all paths, i.e. choosing right
# eliminates a choice to go down.
def routes(n):
print(int((factorial(2 * n)) / (factorial(n) * factorial(n))))
routes(20) |
930a4506ff79a4ffd61cf60de746a85552bd9678 | igorprati/python_modulo | /codelabs02/desafio01.py | 1,158 | 3.828125 | 4 | # Declaração de variável
listaCand = ['José', 'Inácio', 'Tião', 'Severino', 'Branco', 'Nulo'] # lista dos possíveis votos
contador = 0
jose = inacio = tiao = severino = branco = nulo = 0 # contador de votos para cada canditato
continuarVoto = 'S' # laço while
print('Essa é a lista dos candidatos: \n') # mostra a lista dos candidatos
for i in listaCand: # para numerar os candidatos
contador += 1
print(contador, i)
while continuarVoto == "S": # enquanto o usuário escolher continuar votando, while = True
voto = int(input('\nDigite o número de acordo com o candidato a ser votado: '))
if voto == 1:
jose += 1
elif voto == 2:
inacio += 1
elif voto == 3:
tiao += 1
elif voto == 4:
severino += 1
elif voto == 5:
branco += 1
elif voto == 6:
nulo += 1
continuarVoto = input('Continuar votando? [S/N]: ').upper() # pergunta se o usuário quer continuar votando
print(f'\n\nTotal de votos:\n\n ------- \n\n José: {jose}\n Inácio: {inacio}\n Tião: {tiao}\n Severino: {severino}\n\n Total de votos Brancos: {branco}\n Total de votos Nulos: {nulo}\n\n')
|
2d5baf701e4e6d2ee01a8afbc0834312bde25321 | kumarshyam7777/CorePythonPrograms | /dictionary_methods.py | 1,573 | 4.25 | 4 | dict = {
1: 2,
'name': 'shyam',
'profession': 'Python Programmer',
list: [20, 40, 60, 80]
}
print(type(dict))
print(dict.keys()) # Prints the key of the Dictionary
print(type(dict.keys()))
print(list(dict.keys())) # Covertys the dict_keys to list
print(tuple(dict.keys())) # Converts the dict_keys to tuple
print(dict.values())
print(type(dict.values()))
print(list(dict.values())) # Converts the dict_values to list type
print(tuple(dict.values())) # Converts the dict_values to tuple type
print(dict.items()) # Prints the (key,value) for all contents of the dictionary
# this is a way to upadte the methods into another variable and apply update method to the existing dict
updateDict = {
'friends': ['Sugandha', 'Abichal', 'Mudita']
}
dict.update(updateDict)
print(dict) # Update the dictionary by adding key-value pairs from updateDict
updateDict_1 = {
'Electrnics Accessories': ("Motorola Mobile", "HP Laptop", "WD External HDD"),
'Python': 'Dynamically Typed Programming language',
'Java': 'Java is a object Oriented Programming language'
}
dict.update(updateDict_1)
print(dict) # Update the dictionary by adding key-value pairs from updateDict
# .get() method prints the value which are associated with 'Electrnics Accessories'
print(dict.get('Electrnics Accessories'))
print(dict['Electrnics Accessories'])
# Difference between the .get() method and the [] method
print(dict.get('Electronics Accessories'))
# throws an error as Electronis Accessories is not present in dictionary
# print(dict['Electronics Accessories'])
|
6e4ce4f5050d85e7187432c737fe91489f0466d5 | Roshanbagla/Leetcode | /palindrome.py | 249 | 4.3125 | 4 | """An Integer is a palindrome."""
def isPalindrome(number):
"""To check if an integer is a palindrome."""
reverse = number[::-1]
if number == reverse:
return True
return False
number = input()
print(isPalindrome(number))
|
94e333af34ce9e5ee1356b690f4330ae251d4882 | krzaladin/FlappyBirdWorkShop | /FlappyBird4.py | 3,100 | 4 | 4 | #we first import pygame library
import pygame
#to use the random feature
import random
#initialize pygame
pygame.init()
#define colors
black = (0, 0, 0)
white = (255, 255, 255)
blue = (135, 206, 250)
purple = (186, 85, 211)
#define new color 'green'
green = (0, 255, 0)
#define new color 'red'
red = (255, 0, 0)
#define screen size
size = (700, 500)
screen = pygame.display.set_mode(size)
#define screen title
pygame.display.set_caption("Flappy Bird")
#boolean T/F to control game logic
done = False
#clock to control game refresh speed
clock = pygame.time.Clock()
x = 350
y = 250
#define global variables to control speed
x_speed = 0
y_speed = 0
#define global variable positon for the ground
#sinde vertical 'size' equals 500, defined above, and
#ball size is 20 as defined in 'ball' defing function
#and -3 pixel correction
ground = 515
#x-axis location of obstacle
xloc = 700
#y-axis location of obstacle
yloc = 0
#how wide we want obstacle
xsize = 70
#how randomly tall it is
ysize = random.randint(0,350)
#space between two blocks
space = 150
#the speed of the obstacles as they move across the screen
#pixels per frame/flip
obspeed = 2.5
#we proceed to define our obstacles
def obstacles(xloc, yloc, xsize, ysize):
pygame.draw.rect(screen, green, [xloc,yloc,xsize,ysize])
pygame.draw.rect(screen, green, [xloc, int(yloc+ysize+space),xsize,ysize+500])
#define function to draw circle
def ball(x,y):
pygame.draw.circle(screen,purple,(x,y),20)
#define function to handle game over event
def gameover():
font = pygame.font.SysFont(None, 44)
#we update font color
text = font.render("Game Over ", True, red)
screen.blit(text, [150, 250])
#while logic to keep game running
while not done:
#capture input events so we can act upon them
for event in pygame.event.get():
#if user select 'ESC' key or press windows 'X' top right button
if event.type == pygame.QUIT:
done = True
#new if event catch
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_speed = -10
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
y_speed = 5
#fill screen with color defined above
screen.fill(blue)
#time to draw obstacles
obstacles(xloc,yloc,xsize,ysize)
#call function to draw the ball
ball(x,y)
#adjust vertical y position
y += y_speed
#time to redefine per refresh new xlocation
xloc -= obspeed
#once 'y' is change check if ground is touches hence 'game over'
if y > ground:
gameover()
#to stop the ball
y_speed = 0
#if we hit the ground obstacle stops
obspeed = 0
#refresh screen by flipping like a flipbook new animation
pygame.display.flip()
#refresh times per second this will happen via clock defined above
clock.tick(60)
#once logic loop end exit game
pygame.quit() |
181a504290fcc2ea5284c97c4c2f24364c8bb6a1 | andresouzaesilva/Python | /calculadora.py | 1,625 | 3.984375 | 4 | from tkinter import *
from tkinter import ttk
janela=Tk()
# função soma
def soma():
num1=float(num1Entry.get())
num2=float(num2Entry.get())
lb["text"] = num1 + num2
#função subtração
def sub():
num1=float(num1Entry.get())
num2=float(num2Entry.get())
lb["text"] = num1 - num2
#função multiplicação
def multi():
num1 = float(num1Entry.get())
num2 = float(num2Entry.get())
lb["text"] = num1 * num2
#função divisão
def divi():
num1=float(num1Entry.get())
num2=float(num2Entry.get())
lb["text"] = num1 / num2
#Label observação
Label(janela, text="Digite os numeros primeiros e depois a operação!").place(x=10, y=10)
#Label e caixa do número 1
Label(janela, text="Digite o primeiro número").place(x=50, y=40)
num1Entry = Entry(janela)
num1Entry.place(x=50, y=60)
#Label e caixa do número 2
Label(janela, text="Digite o segundo número").place(x=50, y=80)
num2Entry = Entry(janela)
num2Entry.place(x=50, y=100)
#botão soma
b1= Button(janela, width=7, text="+", command=soma)
b1.place(x=180, y=60)
#botão subtração
b2= Button(janela, width=7, text="-", command=sub)
b2.place(x=180, y=100)
#botão multiplicação
b3= Button(janela, width=7, text="*", command=multi)
b3.place(x=180, y=140)
#botão divisão
b4= Button(janela, width=7, text="/", command=divi)
b4.place(x=180, y=180)
#label e caixa resultado
Label(janela, text="Resultado =").place(x=50, y=180)
lb=Label(janela, text="")
lb.place(x=120, y=180)
janela.title("Calculadora")
janela.geometry("280x280")
janela.mainloop() |
dbd17fd9e651995bbd3944b54b5d52e171edf6d3 | nordap/BOJ | /1157_1.py | 573 | 3.5 | 4 | if __name__ == "__main__":
s = input()
s = s.upper()
d = dict()
#for i in upper_s:
# if i in d.keys():
# d[i] += 1
# else:
# d[i] = 1
for i in range(ord('A'),ord('Z')+1):
d[chr(i)] = s.count(chr(i))
chk = 0
max_key = '0'
max_value = -1
for i in d.keys():
if d[i] > max_value:
max_value = d[i]
max_key = i
chk = 0
elif d[i] == max_value:
chk = 1
if chk:
print("?")
else:
print(max_key)
|
2b56fbf7bab995396f0b4a41c46ccdd42b65b436 | chrishuan9/codecademy | /python/16Stats-4.py | 324 | 3.734375 | 4 | def main():
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
print_grades(grades)
print grades_sum(grades)
def print_grades(grades):
for grade in grades:
print grade
def grades_sum(scores):
total = 0
for grade in scores:
total+=grade
return total
if __name__ == "__main__":
main()
|
b051ab283c5361e92127b17d2b691c1b9d97ec57 | mgorgei/codeeval | /Hard/c113 Multiply Lists.py | 892 | 4.1875 | 4 | '''MULTIPLY LISTS
You have 2 lists of positive integers. Write a program which multiplies
corresponding elements in these lists.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Input
example is the following
9 0 6 | 15 14 9
5 | 8
13 4 15 1 15 5 | 1 4 15 14 8 2
The lists are separated with a pipe char, numbers are separated with a space char.
The number of elements in lists are in range [1, 10].
The number of elements is the same in both lists.
Each element is a number in range [0, 99].
OUTPUT SAMPLE:
Print the result in the following way.
135 0 54
40
13 16 225 14 120 10
'''
def f(test):
test = test.split('|')
test[0] = str(test[0]).split()
test[1] = str(test[1]).split()
zipped = zip(test[0], test[1])
result = ""
for x,y in zipped:
result += str(int(x)*int(y)) + ' '
print(result)
#9 0 6 | 15 14 9
|
de06f091462df5462f6ddc73acd3f5bf9ed8e112 | AlexisDongMariano/leetcode | /1021 - Remove Outermost Parenthesis.py | 2,114 | 3.875 | 4 | # ==============================
# Information
# ==============================
# Title: 1021 - Remove Outermost Parenthesis
# Link: https://leetcode.com/problems/remove-outermost-parentheses/
# Difficulty: Easy
# Language: Python
# Problem:
# A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are
# valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()",
# and "(()(()))" are all valid parentheses strings.
# A valid parentheses string S is primitive if it is nonempty, and there does not exist a way
# to split it into S = A+B, with A and B nonempty valid parentheses strings.
# Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k,
# where P_i are primitive valid parentheses strings.
# Return S after removing the outermost parentheses of every primitive string in the primitive
# decomposition of S.
# Example
# Input: "(()())(())"
# Output: "()()()"
# Explanation:
# The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
# After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
# ==============================
# Solution
# ==============================
# 0(n)
def remove_outer_parentheses(S):
p_stack = []
output = []
for i, p in enumerate(S):
if not p_stack:
p_stack.append(p)
elif len(p_stack) == 1 and p == ')':
p_stack.pop()
else:
if p == '(':
p_stack.append(p)
output.append(p)
else:
p_stack.pop()
output.append(p)
return ''.join(output)
def remove_outer_parentheses2(S):
count = 0
p_stack = []
for p in S:
if p == '(' and count > 0:
p_stack.append(p)
if p == ')' and count > 1:
p_stack.append(p)
count += 1 if p == '(' else -1
return ''.join(p_stack)
input = '(()())(())'
print(remove_outer_parentheses(input))
print(remove_outer_parentheses2(input))
|
65f655c56882674f489b3e5259821e287be94725 | AtulSinghBankoti/DataStructure-And-Algorithms | /Problems/src/hackerRank/mars-exploration.py | 492 | 3.5625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the marsExploration function below.
def marsExploration(s):
c = 'SOS'
p = 0
res = 0
for i in s:
if i != c[p]:
print(f'c: {c}')
print(f'i: {i}')
res += 1
if p == len(c)-1:
p = 0
else:
p += 1
return res
if __name__ == '__main__':
s = 'SOSSOSSOS'
result = marsExploration(s)
print(result)
|
bc65632ca68071fa04950834c2fea02ecb287b18 | djmar33/python_work | /ex/ex10/10.1.6.py | 589 | 4 | 4 | #10.1.6包含一百万位大型的文件
#文件赋值给变量filename;
filename = 'pi_million_digits.txt'
#使用open打开文件,并且将内容对象存储到变量file_object中;
with open(filename) as file_object:
#readlines()从文件中读取每一行,并存储在一个列表中;
lines = file_object.readlines()
pi_string = ''
#for循环导出每一行数字;
for line in lines:
pi_string += line.strip()
#使用切片,输出前52位数;
print(pi_string[:52] + "...")
#计算pi_string长度
print(len(pi_string))
|
0786bc92e2e1941132043d73953093e8c4ac486f | xxwqlee/pylearn | /hdd/day2.py | 2,273 | 4.375 | 4 | """
控制结构练习:
1.选择结构:三角形面积周长
2.循环结构:判断素数、最大公约数和最小公倍数
"""
import math
class Triangle:
def __init__(self, a, b, c):
if a + b > c and a + c > b and b + c > a:
self.a = a
self.b = b
self.c = c
else:
print('不能构成三角形')
def perimeter(self):
p = (self.a+self.b+self.c)/2
return p
def area(self):
p = self.perimeter()
# p = (self.a + self.b + self.c) / 2
area = math.sqrt(p * (p - self.a) * (p - self.b) * (p - self.c))
return area
def draw_tri(self):
row = int(self.perimeter())
for i in range(row):
for _ in range(i + 1):
print('*', end='')
print()
for i in range(row):
for j in range(row):
if j < row - i - 1:
print(' ', end='')
else:
print('*', end='')
print()
for i in range(row):
for _ in range(row - i - 1):
print(' ', end='')
for _ in range(2 * i + 1):
print('*', end='')
print()
class IsNum:
def __init__(self):
pass
@staticmethod
def is_prime(a):
end = int(math.sqrt(a))
is_prime = True
for x in range(1, end + 1):
if a % x == 0:
is_prime = False
break
if is_prime and a != 1:
print('{0}是素数'.format(a))
else:
print('{0}不是素数'.format(a))
@staticmethod
def mm_judge(a, b):
x = int(a)
y = int(b)
if x > y:
x, y = y, x
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
print('%d和%d的最大公约数是%d' % (x, y, factor))
print('%d和%d的最小公倍数是%d' % (x, y, x * y // factor))
break
if __name__ == "__main__":
tri1 = Triangle(3, 5, 7)
print(tri1.perimeter(), tri1.area())
tri2 = Triangle(3, 4, 10)
tri1.draw_tri()
IsNum.is_prime(11)
IsNum.is_prime(12)
IsNum.mm_judge(3, 5)
|
3e616cd04c6971dace16788680d08dc03a981674 | felpssc/Python-Desafios | /Lista 4/ex006.py | 222 | 4.03125 | 4 | n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
if n1 == n2:
print('Números iguais!')
elif n1 > n2:
print('Primeiro número é maior!')
else:
print('Segundo número é maior!') |
5e3f39aaa2141faf231879bee37657bdaa3d40bb | alexsomai/tensorflow-getting-started | /basic-classification.py | 2,581 | 3.546875 | 4 | # Fashion MNIST basic classification https://www.tensorflow.org/tutorials/keras/basic_classification
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
# Could use either fashion_mnist or mnist dataset
fashion_mnist = keras.datasets.fashion_mnist
# mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
# (train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# fashion_mnist
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# mnist
# class_names = ['zero', 'one', 'two', 'three', 'four',
# 'five', 'six', 'seven', 'eight', 'nine']
# Plot the data
# plt.figure()
# plt.imshow(train_images[0])
# plt.colorbar()
# plt.gca().grid(False)
# plt.show()
train_images = train_images / 255.0
test_images = test_images / 255.0
# Plot the data
# plt.figure(figsize=(10, 10))
# for i in range(25):
# plt.subplot(5, 5, i + 1)
# plt.xticks([])
# plt.yticks([])
# plt.grid('off')
# plt.imshow(train_images[i], cmap=plt.cm.binary)
# plt.xlabel(class_names[train_labels[i]])
#
# plt.show()
# Setup the layers
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
# Compile the model
model.compile(optimizer=tf.train.AdamOptimizer(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(train_images, train_labels, epochs=5)
# Evaluate accuracy
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
# Make predictions
predictions = model.predict(test_images)
# print(np.argmax(predictions[0]))
# Plot the first 25 test images, their predicted label, and the true label
# Color correct predictions in green, incorrect predictions in red
plt.figure(figsize=(10, 10))
for i in range(25):
plt.subplot(5, 5, i + 1)
plt.xticks([])
plt.yticks([])
plt.grid('off')
plt.imshow(test_images[i], cmap=plt.cm.binary)
predicted_label = np.argmax(predictions[i])
true_label = test_labels[i]
if predicted_label == true_label:
color = 'green'
else:
color = 'red'
plt.xlabel("{} ({})".format(class_names[predicted_label],
class_names[true_label]), color=color)
plt.show()
|
861e7b840110ce7a458eb360b7232f19591a20cc | smwelisson/Exercicio_CeV | /18 - Listas 2 - 84 a 89/86.py | 672 | 3.875 | 4 | matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for l in range(3):
for c in range(3):
matriz[l][c] = int(input(f"Digite um numero para [{l}, {c}]: "))
for l in range(3):
for c in range(3):
print(f"[ {matriz[l][c]:^5} ]", end="")
print()
# n1 = 0
# for x1 in range(3):
# n2 = 0
# for x2 in range(3):
# num = int(input(f"Digite um valor para [{n1}, {n2}]: "))
# n2 += 1
# matriz.append(num)
# n1 += 1
#
# print("-="*30)
#
# matricial = 0
# for n in matriz:
# matricial += 1
# if matricial == 3:
# print(f"[ {n} ] \n")
# matricial = 0
# else:
# print(f"[ {n} ] ", end="")
#
#
|
77e927126fd90e2e8deb4b2d57fc45134562e69b | zachard/python-parent | /hello_python/chapter05/if_condition_test.py | 3,160 | 4.5 | 4 |
# 每条if语句的核心都是一个值为True或False的表达式, 这种表达式被称为条件测试.
# 如果条件测试的值为True, Python就执行紧跟在if语句后面的代码;
# 如果为False, Python就忽略这些代码.
# 条件测试-检查是否相等
car = 'bmw'
print(car == 'bmw')
car = 'audi'
print(car == 'bmw')
# 条件测试-检查是否相等时区分大小写
# 两个大小写不同的值会被视为不相等
print('\n')
car = 'audi'
print('当前车品牌是否为audi: ')
print(car == 'audi')
print('当前车品牌是否为Audi: ')
print(car == 'Audi')
# 可采用lower()函数忽略大小写
car = 'Audi'
print('当前车品牌小写是否为audi: ')
print(car.lower() == 'audi')
# 条件测试-检查是否不相等
# 要判断两个值是否不等, 可结合使用惊叹号和等号(!=)
print('\n')
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print('这不是我想要的!')
# 比较数字
print('\n')
age = 18
print('当前年龄为: ' + str(age))
print('当前年龄是否等于18: ')
print(age == 18)
print('当前年龄是否不为20: ')
print(age != 20)
print('当前年龄是否小于20: ')
print(age < 20)
print('当前年龄是否小于等于18: ')
print(age <= 18)
print('当前年龄是否大于14: ')
print(age > 14)
print('当前年龄是否大于等于16: ')
print(age >= 16)
# 检查多个条件-使用and检查多个条件为True
print('\n')
age_tom = 20
age_bob = 16
print('当前情况下, tom和bob的年龄是否都大于等于18岁: ')
print((age_tom >= 18) and (age_bob >= 18))
age_tom = age_tom + 2
age_bob = age_bob + 2
print('两年后, tom和bob的年龄是否都大于等于18岁: ')
print((age_tom >= 18) and (age_bob >= 18))
# 检查多个条件-使用or检查是否有一个条件为True
print('\n')
age_amy = 14
age_cindy = 16
print('当前情况下, Amy和Cindy中是否有人大于等于18岁: ')
print((age_amy >= 18) or (age_cindy >= 18))
age_amy = age_amy + 2
age_cindy = age_cindy + 2
print('两年后, Amy和Cindy中是否有人大于等于18岁: ')
print((age_amy >= 18) or (age_cindy >= 18))
# 检查特定值是否包含在列表中
# 要判断特定的值是否已包含在列表中, 可使用关键字in.
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('\n')
print('用户点的披萨有: ')
print(requested_toppings)
print('用户是否点了mushrooms披萨: ')
print('mushrooms' in requested_toppings)
print('用户是否点了pepperoni披萨: ')
print('pepperoni' in requested_toppings)
# 检查特定值是否不包含在列表中--可使用关键字not in
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
print('\n')
print('用户' + user + '是否可以发言: ')
print(user not in banned_users)
if user not in banned_users:
print(user + ': 您好, 请发表你的看法!')
# 布尔表达式
# 与条件表达式一样, 布尔表达式的结果要么为True, 要么为False
# 布尔值通常用于记录条件
game_active = True
can_edit = False
print('\n')
if game_active:
print('游戏正在运行!')
if not can_edit: # 布尔值取反, 采用not
print('当前状态下不可编辑') |
72a2ba7e035e1a572e405db9f65f5f0c500f9c4f | maggishaggy/SequenceClusterScripts | /SummarizeOrthoMCLResults.py | 17,681 | 3.765625 | 4 | #!/usr/local/bin/python
#Created on 2/12/13
__author__ = 'Juan Ugalde'
import sys
from collections import defaultdict
#This are functions involved in reading files
def read_genome_list(input_file):
"""
Function used to read the genome list. The output is a dictionary with the genome list (fasta_prefix -> new_prefix)
and the total number of genomes in the list
"""
genome_count = 0
genome_info = {}
genome_name_list = []
genome_prefix_list = []
for line in open(input_file, 'r'):
line = line.rstrip()
element = line.split("\t")
#Check for duplicates
if element[0] in genome_info.keys(): # Duplicate genome ID
print "Duplicate genome id found: " + line
sys.exit("Check for duplicates")
elif element[1] in genome_name_list: # Duplicate genome name
print "Duplicate genome name found: " + line
sys.exit("Check for duplicates")
elif element[2] in genome_prefix_list: # Duplicate prefix name
print "Duplicate prefix found: " + line
sys.exit("Check for duplicates")
else:
genome_info[element[0]] = element[2]
genome_count += 1
genome_name_list.append(element[1])
genome_prefix_list.append(element[2])
return genome_info, genome_count
def get_protein_info(genome_list, fasta_directory):
"""
This function goes into a folder with fasta files (.fasta) of the proteins and get the information for the proteins
in each genome, including the ID and the length of the protein
"""
from Bio import SeqIO
proteins_in_genomes = defaultdict(list)
protein_length = defaultdict(int)
files_read_counter = 0
fasta_files = [fasta_directory + "/" + fasta + ".fasta" for fasta in genome_list]
for fasta in fasta_files:
for record in SeqIO.parse(fasta, "fasta"):
proteins_in_genomes[record.id.split('|')[0]].append(record.id)
protein_length[record.id] = int(len(record.seq))
files_read_counter += 1
return proteins_in_genomes, protein_length, files_read_counter
def get_orthomcl_results(cluster_file, genome_list):
"""
This function reads the results of the OrthoMCL clustering, and returns a dictionary with the information.
The format is:
ClusterID: protein1 protein2 ....
"""
orthomcl_results = open(cluster_file, 'r')
cluster_dictionary = defaultdict(list)
unique_proteins_genome_count = defaultdict(int)
proteins_in_cluster = set()
total_cluster_count = 0
removed_clusters = 0
for line in orthomcl_results:
total_cluster_count += 1
line = line.strip('\n')
ids_proteins = line.split(": ")
proteins = ids_proteins[1].split(" ")
clean_protein_list = [] # This is used to remove proteins from genomes not in the list
for genome in genome_list:
[clean_protein_list.append(protein) for protein in [x for x in proteins if x.startswith(genome)]]
#Now I need to evaluate those clusters that now are unique and zero
if len(clean_protein_list) == 0:
removed_clusters += 1
continue
if len(clean_protein_list) == 1:
unique_proteins_genome_count[clean_protein_list[0].split("|")[0]] += 1
removed_clusters += 1
continue
for protein in clean_protein_list:
cluster_dictionary[ids_proteins[0]].append(protein)
proteins_in_cluster.add(protein)
return cluster_dictionary, proteins_in_cluster, unique_proteins_genome_count, total_cluster_count, removed_clusters
def read_group_files(group_file):
"""
Reads a file with the group list, and returns a dictionary containing
the name of the group and a list with the genomes that are in that group
"""
genome_groups = defaultdict(list)
for line in open(group_file, 'r'):
line = line.rstrip()
element = line.split("\t")
genome_groups[element[0]].append(element[1])
return genome_groups
#Here we go into the main calculations
def get_unique_seqs_genome(sequences_in_genomes, total_set_sequences, sequence_lengths, min_length):
"""
This module takes a dictionary with their genome and proteins, and a set of proteins
and look for proteins that are not in the total set
"""
large_unique_sequences = defaultdict(list)
short_unique_sequences = defaultdict(list)
processed_sequences = 0
for genome in sequences_in_genomes:
for seq_name in sequences_in_genomes[genome]:
processed_sequences += 1
if seq_name in total_set_sequences:
continue
else:
if sequence_lengths[seq_name] > min_length:
large_unique_sequences[genome].append(seq_name)
else:
short_unique_sequences[genome].append(seq_name)
return large_unique_sequences, short_unique_sequences, processed_sequences
def seqs_shared_clusters(cluster_dic, genome_dictionary):
"""
This module takes the cluster dictionary and the genome dictionary and generates outputs which includes:
Clusters that are unique to each genome
Clusters that are shared across all genomes (single and multiple copy)
"""
unique_clusters = defaultdict(list) # Dictionary with the unique clusters
shared_single_clusters = [] # List with clusters that are shared and single copy
shared_multiple_clusters = [] # List with clusters that are shared and in multiple copies
genomes_in_matrix = sorted(genome_dictionary.values())
header = ["Cluster_ID"]
header.extend(sorted(genome_dictionary.values()))
all_clusters_matrix = [header]
for cluster in cluster_dic:
genome_list = [protein.split("|")[0] for protein in cluster_dic[cluster]] # Create a list with the genomes
count = {x: genome_list.count(x) for x in genome_list} # Count the occurences
#Create the matrix
cluster_matrix = [cluster]
for genome in genomes_in_matrix:
if genome in genome_list:
cluster_matrix.append(count[genome])
else:
cluster_matrix.append(0)
#print cluster_matrix
all_clusters_matrix.append(cluster_matrix)
if len(count) == 1:
unique_clusters[genome_list[0]].append(cluster)
elif len(count) == len(genome_dictionary.keys()):
if sum(count.itervalues()) == len(genome_dictionary.keys()):
shared_single_clusters.append(cluster)
else:
shared_multiple_clusters.append(cluster)
return unique_clusters, shared_single_clusters, shared_multiple_clusters, all_clusters_matrix
def clusters_in_groups(clusters, groups):
"""
"""
import itertools
unique_group_clusters = defaultdict(list) # Count the unique clusters in each group
combination_clusters = defaultdict(list)
#Create inverted dictionary
genome_group_info = dict()
for group in groups:
for genome in groups[group]:
genome_group_info[genome] = group
for cluster in clusters:
group_count = defaultdict(lambda: defaultdict(int))
for protein in clusters[cluster]:
genome_id = protein.split("|")[0]
group_for_genome = genome_group_info[genome_id]
group_count[group_for_genome][genome_id] += 1
##Unique clusters for each group
if len(group_count) == 1:
for group in group_count:
if len(group_count[group]) == len(groups[group]):
unique_group_clusters[group].append(cluster)
else: # I could add something here to count the number of proteins not unique
pass
#Shared, all possible combinations
else:
for combination_count in range(2, len(group_count) + 1):
for group_combinations in itertools.combinations(groups.keys(), combination_count):
# Check that all the genomes in the group are represented
group_check = 0
for i in range(0, len(group_combinations)):
if len(group_count[group_combinations[i]]) == len(groups[group_combinations[i]]):
continue
else:
group_check = 1
if group_check == 0:
combination_clusters[group_combinations].append(cluster)
return unique_group_clusters, combination_clusters
if __name__ == '__main__':
import os
import argparse
#Create the options and program description
program_description = "This script summarize the results of orthoMCL, and create several summary files." \
" The inputs are:" \
"-List of clusters, generated by orthoMCL" \
"-A genome list" \
"-A folder with fasta files" \
"- An optional group file, to group genomes. For example, all genomes from the same species "
parser = argparse.ArgumentParser(description=program_description)
parser.add_argument("-l", "--genome_list_index", type=str,
help="File with the genome list. Format GenomeID, FullName, ShortName", required=True)
parser.add_argument("-c", "--cluster_file", type=str, help="Ortholog file, generated by OrthoMCL", required=True)
parser.add_argument("-f", "--fasta_aa_directory", type=str, help="Directory with the fasta files", required=True)
parser.add_argument("-g", "--group_information", type=str, help="Group file")
parser.add_argument("-o", "--output_directory", type=str, help="Output directory", required=True)
args = parser.parse_args()
#Create the output directory
if not os.path.exists(args.output_directory):
os.makedirs(args.output_directory)
#Create a log file
run_summary = open(args.output_directory + "/logfile.txt", 'w')
#####Read the genome list
genome_id_dictionary, genome_count = read_genome_list(args.genome_list_index)
run_summary.write("Genomes in the genome list: %d" % genome_count + "\n")
######Read the cluster information, and check that everything is ok
cluster_information, set_of_proteins_in_clusters, unique_cluster_count, total_clusters, removed_clusters = \
get_orthomcl_results(args.cluster_file, [i for i in genome_id_dictionary.itervalues()])
run_summary.write("Total number of clusters: %d" % len(cluster_information) + "\n")
run_summary.write("Total number of protein in clusters: %d" % len(set_of_proteins_in_clusters) + "\n")
run_summary.write("Total number of removed clusters (not present in the genome file): %d" % removed_clusters + "\n")
#Check the counts, to see if everything is going ok
if total_clusters - removed_clusters != len(cluster_information):
sys.exit("The number of removed clusters clusters plus the retained clusters, "
"doesn't match the total of original clusters in the file")
#####Read the fasta file
dic_protein_in_genomes, dic_protein_length, files_read_counter = \
get_protein_info([i for i in genome_id_dictionary.itervalues()], args.fasta_aa_directory)
run_summary.write("Total fasta files: %d" % files_read_counter + "\n")
run_summary.write("Total number of proteins in the fasta files: %d" % len(dic_protein_length) + "\n")
#####Read the genome groups (if present)
genome_groups = {}
if args.group_information:
genome_groups = read_group_files(args.group_information)
run_summary.write("Total defined groups: %d" % len(genome_groups) + "\n")
#####################################################
#Look for unique protein in each genome
selected_unique_proteins, removed_unique_proteins, total_number_proteins = \
get_unique_seqs_genome(dic_protein_in_genomes, set_of_proteins_in_clusters, dic_protein_length, 50)
#Check that everything looks ok
check_number = 0
for value in selected_unique_proteins.itervalues():
check_number += len(value)
for value in removed_unique_proteins.itervalues():
check_number += len(value)
if total_number_proteins - len(set_of_proteins_in_clusters) - check_number != 0:
sys.exit("Failed checkpoint. The number of unique proteins and proteins in "
"clusters does not match the total number of proteins")
#Print the output files
count_unique_proteins = open(args.output_directory + "/count_unique_sequences.txt", 'w')
list_unique_proteins = open(args.output_directory + "/list_unique_sequences.txt", 'w')
count_unique_proteins.write("Genome\tSelected\tTooShort\n")
for genome in selected_unique_proteins:
count_unique_proteins.write(genome + "\t" + str(len(selected_unique_proteins[genome])) + "\t" +
str(len(removed_unique_proteins[genome])) + "\n")
for protein in selected_unique_proteins[genome]:
list_unique_proteins.write(genome + "\t" + protein.split("|")[1] + "\n")
count_unique_proteins.close()
list_unique_proteins.close()
############################
##Get the clusters shared between genomes and unique clusters to each genome
matrix_output = open(args.output_directory + "/matrix_output.txt", 'w')
list_unique_clusters = open(args.output_directory + "/list_unique_clusters.txt", 'w')
count_unique_clusters = open(args.output_directory + "/count_unique_clusters.txt", 'w')
list_shared_single_copy_clusters = open(args.output_directory + "/list_single_copy_clusters.txt", 'w')
list_shared_multiple_copy_clusters = open(args.output_directory + "/list_shared_multiple_copy.txt", 'w')
unique_clusters, shared_single_clusters, shared_multiple_clusters, all_clusters_matrix = \
seqs_shared_clusters(cluster_information, genome_id_dictionary)
#Print counters
run_summary.write("Number of shared single copy clusters: %d" % len(shared_single_clusters) + "\n")
run_summary.write("Number of shared multiple copy clusters: %d" % len(shared_multiple_clusters) + "\n")
#Print the outputs
matrix_output.write("\n".join(["\t".join(map(str, r)) for r in all_clusters_matrix])) # Matrix output
# Unique clusters per genome (duplicate or paralogs?)
count_unique_clusters.write("Genome\tNumber of Clusters\n")
for genome in unique_clusters:
count_unique_clusters.write(genome + "\t" + str(len(unique_clusters[genome])) + "\n")
for cluster in unique_clusters[genome]:
list_unique_clusters.write(genome + "\t" + cluster + "\t"
+ ",".join(protein for protein in cluster_information[cluster]) + "\n")
# Single copy shared clusters
for cluster in shared_single_clusters:
list_shared_single_copy_clusters.write(cluster + "\t" + ",".join(cluster_information[cluster]) + "\n")
# Multiple copy shared clusters
for cluster in shared_multiple_clusters:
list_shared_multiple_copy_clusters.write(cluster + "\t" + ",".join(cluster_information[cluster]) + "\n")
matrix_output.close()
list_unique_clusters.close()
count_unique_clusters.close()
list_shared_single_copy_clusters.close()
list_shared_multiple_copy_clusters.close()
###Save the cluster information
list_all_clusters = open(args.output_directory + "/list_all_clusters.txt", 'w')
for cluster in cluster_information:
list_all_clusters.write(cluster + "\t" + ",".join(cluster_information[cluster]) + "\n")
list_all_clusters.close()
###############
##Get clusters shared by groups
if args.group_information:
unique_group_clusters, combination_clusters = clusters_in_groups(cluster_information, genome_groups)
list_unique_clusters_group = open(args.output_directory + "/list_unique_clusters_group.txt", 'w')
list_all_group_combinations = open(args.output_directory + "/list_all_group_combinations.txt", 'w')
count_group_results = open(args.output_directory + "/count_groups.txt", 'w')
for group in unique_group_clusters:
protein_count = sum(len(cluster_information[cluster]) for cluster in unique_group_clusters[group])
count_group_results.write(group + "\t" +
str(len(unique_group_clusters[group])) + "\t" + str(protein_count) + "\n")
for cluster in unique_group_clusters[group]:
list_unique_clusters_group.write(group + "\t" + cluster + "\t" + ",".join(cluster_information[cluster]))
count_group_results.write("\n")
for combination in combination_clusters:
combination_name = "-".join(combination)
protein_count = sum(len(cluster_information[cluster]) for cluster in combination_clusters[combination])
count_group_results.write(combination_name + "\t" +
str(len(combination_clusters[combination])) + "\t" + str(protein_count) + "\n")
for cluster in combination_clusters[combination]:
list_all_group_combinations.write(combination_name + "\t"
+ cluster + "\t" + ",".join(cluster_information[cluster]) + "\n")
count_group_results.close()
list_unique_clusters_group.close()
list_all_group_combinations.close()
run_summary.close() |
2f93ad5428bc39fad30c3f2aa451e8096a8bb802 | NikitaInozemtsev/python-practice | /Additional tasks/practice_1/naive_mul/naive_mul.py | 161 | 3.796875 | 4 |
def naive_mul(x, y):
if x == 0 or y == 0:
return 0
r = x
for i in range(0, y - 1):
x = x + r
return x
print(naive_mul(10, 15)) |
49bf980ed31d590ee0c7a9e3fc3c7e6c0b65579d | sincerehwh/Python | /Grammer/3.Container/set.py | 919 | 4.09375 | 4 | '''
- 无序
- 不重复
'''
# 自动去重:C++内是有序的,python中是无序的
new_set = set([1,2,3,4,4,1111,4,4,5,5,6])
new_set2 = set([11,22,33,44,45,1111,45,45,55,56,66])
print(type(new_set))
print(new_set)
print(type(new_set2))
print(new_set2)
# 判断元素是否存在
print(1 in new_set)
print("" in new_set2)
# 并集
print(new_set | new_set2)
print(new_set.union(new_set2))
# 交集
print(new_set & new_set2)
print(new_set.intersection(new_set2))
# 差集 A-B
print(new_set - new_set2)
print(new_set.difference(new_set2))
# 对称差 (A+B)-(A&B) 去除并集内的交集
print(new_set ^ new_set2)
print(new_set.symmetric_difference(new_set2))
# 修改元素
new_set.add("Hello") # 添加单个元素
new_set.update(['a','b','c']) # 添加整个的数组
print(new_set)
# 删除元素 必须知道值
new_set.remove("Hello")
print(new_set)
# 循环
for i in new_set:
print(i)
|
0159ac54bb7e62ac300655de8402ad94320fd302 | Sai-Ram-Adidela/hackerrank | /challenges/itertools/iterables_and_iterators.py | 568 | 3.6875 | 4 | """
Title : Iterables and Iterators
Subdomain : HackerRank/Python/Challenges/itertools
Domain : Python
Author : Sai Ram Adidela
Created : 09 May 2018
"""
from itertools import combinations
if __name__ == '__main__':
N = int(input())
s = input().split()
k = int(input())
count, total = 0, 0
# print('this before for-loop: ', list(combinations(s, k)))
for i in combinations(s, k):
count += 'a' in i
# print('count is: ', count)
total += 1
# print('total is: ', total)
print(count/total)
|
21e2b1ebae411b274be607a5e726ec84198c9303 | brandoni27/PythonClassScripts | /P38_FindTheLongestWord.py | 612 | 4.34375 | 4 | # FindTheLongestWord.py
# Brandon Washington
# 5/22/2019
# Python 3.6
# Description: Finds the longest word in a list and counts the number of characters.
words = ['one','two','three','four','five']
longest = words[0]
for i in range(1,len(words),1):
if len(words[i]) > len(longest):
longest = words[i]
print ('longest word is', longest)
print('has',len(longest),'characters')
'''
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/Brando/Library/Preferences/PyCharmCE2017.2/scratches/P38_FindTheLongestWord.py
longest word is three
has 5 characters
Process finished with exit code 0
''' |
41e246acfc95073ea71c4fcd3cdb71f26a8c85f3 | ody1205/Daily-Coding | /Leetcode/top_100_liked_problems/7.py | 960 | 4.03125 | 4 | '''
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1].
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
'''
def solution(n):
if (-2)**31 < n < (2**31) - 1:
if n < 0:
n = list(str(n))
num = -int(''.join(n[1:len(n)+1][::-1]))
if num >= (-2)**31:
return num
else:
return 0
else:
n = list(str(n))
num = int(''.join(n[::-1]))
if num <= (2**31) - 1:
return num
else:
return 0
else:
return 0
print(solution(1534236469)) |
0d7968c72617cb23a589bf2a16caad4ea9e8fa42 | sharda2001/Function | /STRONG_NO_.py | 306 | 3.953125 | 4 | def Strongnum(n):
a=n
sum=0
while n>0:
i=1
f=1
b=n%10
while i<=b:
f=f*i
i=i+1
sum=sum+f
n=n//10
if a==sum:
print("strong num")
else:
print("not strong num")
n=int(input("enter number"))
Strongnum(n) |
1a059e4f8bfa13728c1889fbbca927b5abd9a9e0 | Ggayane/adventofcode-answers | /python/day-1.py | 353 | 3.546875 | 4 | inputFile = __file__.replace('py', 'txt')
def getInput(fileName):
with open(fileName) as f:
return f.readline()
def captchaCalc():
sum = 0
input = getInput(inputFile)
input += input[0]
for i in range(len(input) - 1):
if input[i] == input[i+1]:
sum += int(input[i])
return sum
print(captchaCalc()) |
d52a63426988b85fb6d01d5a6e4a864f366c23e2 | 77rui77/lianxipython | /多分支结构.py | 230 | 3.671875 | 4 | s=int(input('请输入成绩:'))
if 90<=s<=100:
print('A')
elif 80<=s<90:
print('B')
elif 70<=s<80:
print('C')
elif 60<=s<70:
print('D')
elif 0<=s<60:
print('不及格')
else:
print('请输入有效成绩') |
024c86353f8d912b140be4f070f8450baae98330 | ryansocha03/Pathfinder | /node.py | 3,128 | 3.84375 | 4 | '''Class file for the graph nodes'''
import sys
import pygame
pygame.init()
class node(object):
def __init__(self, row, col):
self.row = row #Contains the row of the node in the grid
self.col = col #Contains the column of the row in the grid
self.isWall = False #True when the node is a wall, false otherwise
self.visited = False #True if the node has been visited in the current iteration of dijkstra
self.distance = sys.maxsize #Distance from the start node
self.isStart = False #True when the node is the start node
self.isEnd = False #True when the node is a pin
self.prev_node = None #Contains this nodes predecessor
#Draw new arrow image and color last node yellow. 0 is left, 1 is up, 2 is right, 3 is down in start_images
def trace_node(self, win, start_images):
pygame.draw.rect(win, (255, 255, 0), (20 * self.prev_node.col + 1, 20 * self.prev_node.row + 101, 18, 18))
#Moved to the left
curr_direction = 0
if self.col < self.prev_node.col:
pygame.draw.rect(win, (255, 255, 255), (20 * self.col + 1, 20 * self.row + 101, 18, 18))
#Moved up
elif self.row < self.prev_node.row:
pygame.draw.rect(win, (255, 255, 255), (20 * self.col + 1, 20 * self.row + 101, 18, 18))
curr_direction = 1
#Moved to the right
elif self.col > self.prev_node.col:
pygame.draw.rect(win, (255, 255, 255), (20 * self.col + 1, 20 * self.row + 101, 18, 18))
curr_direction = 2
#Else moved down
else:
pygame.draw.rect(win, (255, 255, 255), (20 * self.col + 1, 20 * self.row + 101, 18, 18))
curr_direction = 3
win.blit(start_images[curr_direction], (20 * self.col + 1, 20 * self.row + 101))
return curr_direction
#This method performs the necessary updates when the start node is dragged and dropped
@staticmethod
def adjust_start(s_rect, nodes, start, moveStart):
if moveStart:
if s_rect.y < 100:
s_rect.x = nodes[start[0]][start[1]].col * 20
s_rect.y = 100 + (nodes[start[0]][start[1]].row * 20)
else:
offset_x = s_rect.x % 20
offset_y = s_rect.y % 20
prev_start_row = start[0]
prev_start_col = start[1]
nodes[start[0]][start[1]].isStart = False
s_rect.x = s_rect.x - offset_x
start[1] = (s_rect.x - offset_x) // 20 + 1
s_rect.y = s_rect.y - offset_y
start[0] = (s_rect.y - offset_y) // 20 - 4
if nodes[start[0]][start[1]].isWall or nodes[start[0]][start[1]].isEnd:
start[0] = prev_start_row
start[1] = prev_start_col
s_rect.x = nodes[start[0]][start[1]].col * 20
s_rect.y = 100 + (nodes[start[0]][start[1]].row * 20)
nodes[start[0]][start[1]].isStart = True
|
8e66b85de76179e4c3330c8a7cc46d62fe036da4 | da-ferreira/uri-online-judge | /uri/1357.py | 1,336 | 3.578125 | 4 |
number_to_braille = {
1: '*.....',
2: '*.*...',
3: '**....',
4: '**.*..',
5: '*..*..',
6: '***...',
7: '****..',
8: '*.**..',
9: '.**...',
0: '.***..'
}
braille_to_number = {
'*.....': '1',
'*.*...': '2',
'**....': '3',
'**.*..': '4',
'*..*..': '5',
'***...': '6',
'****..': '7',
'*.**..': '8',
'.**...': '9',
'.***..': '0'
}
while True:
d = int(input())
if d == 0:
break
operacao = input()
if operacao == 'S':
digitos = input()
imprimir = []
for i in range(d):
imprimir.append(number_to_braille[int(digitos[i])])
j = 0
for i in range(3):
for k in range(d):
if k != d - 1:
print(imprimir[k][j:j + 2], end=' ')
else:
print(imprimir[k][j:j + 2])
j += 2
else:
numeros = ['' for x in range(d)]
for i in range(3):
entrada = input().split()
for j in range(d):
numeros[j] += entrada[j]
imprimir = ''
for i in range(len(numeros)):
imprimir += braille_to_number[numeros[i]]
print(imprimir)
|
7f07e6cc592a3ddbc4d22fd6decfb8ef32d5b19c | IvayloValkov/Python-the-beginning | /Simple_Solutions/07_house_painting.py | 381 | 3.65625 | 4 | x = float(input())
y = float(input())
h = float(input())
front_back_walls = (x * x) * 2
door = 1.2 * 2
side_walls = (x * y) * 2
windows = (1.5 * 1.5) * 2
roof = ((x * h) / 2) * 2 + side_walls
total_house = (front_back_walls - door) + (side_walls - windows)
green_paint = total_house / 3.4
red_paint = roof / 4.3
print(f'{green_paint:.2f}')
print(f'{red_paint:.2f}') |
0ab1b2fb67f4f2ca98a95fc410ffccd44c513ebc | ngocminhdao88/tdms2uff | /treeitem.py | 5,110 | 4.0625 | 4 | # Ngoc Minh Dao
# minhdao.ngoc@linamar
class TreeItem(object):
def __init__(self, data, parent=None):
"""
Each TreeItem is constructed with a list of data and an optional parent
"""
self._childItems = []
self._itemData = data #list
self._parentItem = parent
if parent is not None:
parent.addChild(self)
def typeInfo(self):
return "Item"
def child(self, number):
"""
Return a specific child from the internal list of children
"""
if (number < 0 or number >= len(self._childItems)):
return None
return self._childItems[number]
def children(self):
"""
Return all the children this item has
"""
return self._childItems
def childCount(self) -> int:
"""
Return a total number of children
"""
return len(self._childItems)
def childNumber(self) -> int:
"""
Get the index of the child in its parent's list of children.
It accesses the parent's _childItems member directly to obtain this information:
"""
if (self._parentItem):
return self._parentItem._childItems.index(self)
#The root item has no parent item. For this we return 0
return 0
def columnCount(self) -> int:
"""
Return the number of elements in the internal _itemData list
"""
return len(self._itemData)
def data(self, column):
"""
Return the data at column in the internal _itemData list
"""
if (column < 0 or column >= len(self._itemData)):
return None
return self._itemData[column]
def setData(self, column, value) -> bool:
"""
Store values in the _itemData list for valid indexes
"""
if (column < 0 or column >= len(self._itemData)):
return False
self._itemData[column] = value
return True
def itemData(self) -> [object]:
"""
Return the _itemData of this node
"""
return self._itemData
def addChild(self, child) -> None:
"""
Add a child into _childItems list
"""
if not child:
return
if child in self._childItems:
return
self._childItems.append(child)
child.setParent(self)
def insertChildren(self, position, count, columns) -> bool:
"""
Add new child into the _childItems list
"""
if (position < 0 or position > len(self._childItems)):
return False
for i in range(count):
data = [None] * columns
item = TreeItem(data, self)
self._childItems.insert(position, item)
return True
def removeChildren(self, position, count) -> bool:
"""
Remove children item from the internal list
"""
if (position < 0 or position + count > len(self._childItems)):
return False
for i in range(count):
child = self._childItems.pop(position)
child.setParent(None)
return True
def parent(self):
"""
Return the parent of this TreeItem
"""
return self._parentItem
def setParent(self, parent=None):
"""
Set the parent to this TreeItem
"""
if parent != self._parentItem:
self._parentItem = parent
def insertColumns(self, position, columns) -> bool:
"""
This function are expected to be called on every item in the tree.
This is done by recursively calling this function on each child of the item
"""
if (position < 0 or position > len(self._itemData)):
return False
for i in range(columns):
self._itemData.insert(position, 0)
for child in self._childItems:
child.insertColumns(position, columns)
return True
def removeColumns(self, position, columns) -> bool:
if (position < 0 or position + columns > len(self._itemData)):
return False
for i in range(columns):
del self._itemData[position]
for child in self._childItems:
child.removeColumns(position, columns)
def _log(self, tabLevel=-1) -> str:
"""
Printout the tree structure
"""
output = ""
tabLevel += 1
for i in range(tabLevel):
output += '\t'
output += "|- " + self._itemData[0] + '\n'
for childItem in self._childItems:
output += childItem._log(tabLevel)
tabLevel -= 1
return output
def __repr__(self):
return self._log()
class DataSetItem(TreeItem):
def __init__(self, data, parent=None):
super(DataSetItem, self).__init__(data, parent)
def typeInfo(self):
return "DataSetItem"
class ChannelItem(TreeItem):
def __init__(self, data, parent=None):
super(ChannelItem, self).__init__(data, parent)
def typeInfo(self):
return "ChannelItem"
|
719688f57a7fe9c0e0b56e0a379d21f44281699a | StHagel/CSE415_Assignments | /Assignment_5/sthagel_VI.py | 4,363 | 3.625 | 4 | """sthagel_VI.py
Value Iteration for Markov Decision Processes.
"""
from math import fabs
# Edit the returned name to ensure you get credit for the assignment.
def student_name():
return "Hagel, Stephan" # For an autograder.
Vkplus1 = {}
Q_Values_Dict = {}
Policy = {}
def one_step_of_VI(S, A, T, R, gamma, Vk):
"""S is list of all the states defined for this MDP.
A is a list of all the possible actions.
T is a function representing the MDP's transition model.
R is a function representing the MDP's reward function.
gamma is the discount factor.
The current value of each state s is accessible as Vk[s].
Your code should fill the dictionaries Vkplus1 and Q_Values_dict
with a new value for each state, and each q-state, and assign them
to the state's and q-state's entries in the dictionaries, as in
Vkplus1[s] = new_value
Q_Values_Dict[(s, a)] = new_q_value
Also determine delta_max, which we define to be the maximum
amount that the absolute value of any state's value is changed
during this iteration.
"""
global Q_Values_Dict, Vkplus1
delta_max = 0.0
for state in S:
# Loop through S to update the value of each individual state
best_value = None
# Will be used to track the maximum
for action in A:
# Calculate sum_Sp (T * (R + gamma * V)) in here
sum_ = 0
for state_prime in S:
sum_ += T(state, action, state_prime) * (R(state, action, state_prime) + gamma * Vk[state_prime])
Q_Values_Dict[(state, action)] = sum_
# Update Q values
if not best_value:
best_value = sum_
# If no action has been checked yet, the first one will be the maximum up to this point
if sum_ > best_value:
best_value = sum_
# Update the maximum
Vkplus1[state] = best_value
# Update state value
delta = fabs(Vk[state] - Vkplus1[state])
if delta > delta_max:
delta_max = delta
# If the current state's value changed by more than any state before that,
# it's change will be kept as delta_max
return Vkplus1, delta_max
# return Vk, 0 # placeholder
def return_Q_values(S, A):
"""Return the dictionary whose keys are (state, action) tuples,
and whose values are floats representing the Q values from the
most recent call to one_step_of_VI. This is the normal case, and
the values of S and A passed in here can be ignored.
However, if no such call has been made yet, use S and A to
create the answer dictionary, and use 0.0 for all the values.
"""
global Q_Values_Dict
if Q_Values_Dict == {}:
for state in S:
for action in A:
Q_Values_Dict[(state, action)] = 0.0
return Q_Values_Dict # placeholder
def extract_policy(S, A):
"""Return a dictionary mapping states to actions. Obtain the policy
using the q-values most recently computed. If none have yet been
computed, call return_Q_values to initialize q-values, and then
extract a policy. Ties between actions having the same (s, a) value
can be broken arbitrarily.
"""
global Policy
Policy = {}
qvals = return_Q_values(S, A)
# A local copy of the q values, that also initializes them, if needed.
for state in S:
best_action = None
best_value = None
# We use the same method for finding the maximum as before, but this time we need to track the action as well.
for action in A:
new_value = qvals[(state, action)]
if not best_value:
best_value = new_value
best_action = action
if new_value > best_value:
best_action = action
best_value = new_value
if best_action:
Policy[state] = best_action
# write the best action into the Policy dictionary
return Policy
def apply_policy(s):
"""Return the action that your current best policy implies for state s."""
global Policy
return Policy[s]
# return None # placeholder
|
d3eb414f1519abc12b857e001bd20c3753971edd | pombredanne/poodle-lex | /Generator/Common.py | 562 | 3.875 | 4 | def lower_nullable(text):
"""
None-safe version of 'str.lower'
@param text: the text to convert to lower-case
"""
if text is None:
return None
return text.lower()
def compare_nullable_icase(lhs, rhs):
"""
None-safe case-insensitive comparison
@param lhs: an item to be compared to rhs
@param rhs: an item to be compared to lhs
"""
if lhs is None and rhs is None:
return True
elif lhs is None or rhs is None:
return False
return lhs.lower() == rhs.lower() |
fea32404df791ba919992ae2d53dca705870dcc5 | phani653/fresh-water | /clg_programs/python/linkedList.py | 1,126 | 3.78125 | 4 | '''
https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/
'''
class Node:
def __init__(self,data):
self.data= data;
self.next= None;
class LinkedList:
def __init__(self):
self.head= None;
def insertAtbegin(self,data):
newnode= Node(data);
if not self.head:
self.head= newnode;
return;
newnode.next= self.head
self.head= newnode;
def insertAtend(self,data):
newnode= Node(data)
if not self.head:
self.head= newnode;
return;
tmp= self.head;
while tmp.next:
tmp= tmp.next;
tmp.next= newnode;
def printList(self):
tmp= self.head;
while tmp:
print (tmp.data),
tmp= tmp.next;
llist= LinkedList();
llist.insertAtbegin(1);
llist.insertAtbegin(11);
llist.insertAtbegin(111);
llist.insertAtend(2);
llist.insertAtend(22);
llist.insertAtend(222);
llist.printList();
|
57d97523f4a9ec1a9ae003ca4703aa038e1044c2 | rianayar/Python-Projects | /Girls Code Inc./Complimenter.py | 320 | 3.890625 | 4 | import random
compliments = ["You're Awesome!", "I think you are great!", "Keep being you!"]
wantsCompliment = input("Would you like to be complimented? Please type 'T' or 'F' \n")
if wantsCompliment == 'T':
print(compliments[random.randint(0,len(compliments)-1)])
else:
print('You chose not to be complimented.') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.