blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
a6af5269d8deb4c6787e69dd854eb1d7f1dea7a8 | zunayedsyed/list-practice | /main.py | 496 | 3.828125 | 4 | # list
# create a function
def list():
x=[5,6,7,8]
y=len(x)
sum=5
sum*=y
print("sum=",sum)
# conditional logic
z=5
if z<sum:
print("weird")
# function call
list()
# list swap
# create a function
def listswap():
x=[1,2,3]
y=5
z=int(input())
if z in x:
print("swapmode")
temp=y
y=z
z=temp
print("y=",y,"z=",z)
# function call
listswap()
# list sum
# create a function
def listsum():
x=[5,6,7,8]
y=x[2:4]
z=len(y)
sum=9
sum*=z
print("sum=",sum)
# function call
listsum()
|
520a7ca114440422421018cf9f285cf2930af7ce | vSzemkel/PythonScripts | /cp-tasks/binary_operator.py | 930 | 3.515625 | 4 | #!/usr/bin/python3
#
# Binary operator
# https://codingcompetitions.withgoogle.com/kickstart/round/0000000000435c44/00000000007ec290
from random import randint
fn_cache = {}
def fn(a, b):
if (a,b) in fn_cache:
return fn_cache[(a,b)]
ret = randint(0, 10**18)
fn_cache[(a,b)] = ret
return ret
class Op:
def __init__(self, state=None):
self.state = state
def __radd__(self, other):
return Op(other) # state==None
def __add__(self, other):
return fn(self.state, other)
def solve(tc):
n = int(input())
A = Op()
out = []
seen = {}
for i in range(n):
s = input().replace("#", "+A+")
r = eval(s)
if r not in seen:
seen[r] = len(seen) + 1
out.append(seen[r])
print(f"Case #{tc}:", *out)
t = int(input())
for _ in range(1, t + 1):
solve(_)
"""
Run:
py.exe binary_operator.py < binary_operator.in
""" |
90de23275cbf5d05b7adef62dff2b25d0624caf9 | liuchao111/Test1.1 | /newstudentssystem.py | 6,345 | 3.65625 | 4 | # 这是一个简单的学生信息管理系统,主要功能是对学生信息进行
# 1,增删改查 2,保存到文件 3,从文件中读取信息
# 制作人刘超
def gongneng():
print("---------------学生信息管理系统---------------\n"
"1,添加学生信息\n"
"2,删除学生信息\n"
"3,修改学生信息\n"
"4,显示所有学生信息\n"
"5,将学生信息保存到文件(xueshengxinxi.txt)\n"
"6,读取文档学生信息(xueshengxinxi.txt)\n"
"7,退出\n"
"---------------------------------------------\n")
def add_stu_info():
mm = []
while True:
name = input("请输入学生姓名: ")
try:
age = int(input("请输入年龄: "))
yu = int(input("请输入语文成绩: "))
shu = int(input("请输入数学成绩: "))
ying = int(input("请输入英语成绩: "))
except Exception as e:
print(e+"是非数字,请重新输入")
continue
info = {"name": name, "age": age, "yu_wen": yu, "shu_xue": shu, "yin_yu": ying}
mm.append(info)
print("该学生信息已成功录入")
try:
nn = int(input("按1继续录入,按非1的数字返回主页面: "))
if nn == 1:
True
else:
break
except Exception as e:
print(e+"不是非数字,请重新输入: ")
return mm
def del_stu_info(stu_info, name11=''):
if not name11:
name11 = input("请输入要删除学生的名字:")
for information in stu_info:
if name11 == information.get("name"):
print("该学生已被成功删除!")
return information
raise IndexError("该学生不在列表里" % name11)
def mod_stu_info(stu_info):
modname = input("请输入要修改的学生名字:")
for imitation in stu_info:
if modname == imitation.get("name"):
age = int(input("输入年龄:"))
yu = int(input("输入语文成绩: "))
shu = int(input("输入数学成绩: "))
yang = int(input("输入英语成绩: "))
imitation = {"name": modname, "age": age, "yu_wen": yu, "shu_xue": shu, "yin_yu": yang}
return imitation
raise IndexError("该学生信息未被找到!!!!!")
def show_all_stu(stu_info):
print("---------------所有学生信息如下---------------")
if not stu_info:
print("没有学生信息,请先录入!")
return
print("姓名".center(6), "年龄".center(6), "语文".center(6), "数学".center(6), "英语".center(6))
for inform in stu_info:
print(inform.get("name").center(7), str(inform.get("age")).center(8), str(inform.get("yu_wen")).center(8),
str(inform.get("shu_xue")).center(8), str(inform.get("yin_yu")).center(8))
print("---------------------------------------------")
def save_stu_info(stu_info):
try:
students_txt = open(r"C:\Users\我\PycharmProjects\python产生txt存放地\xueshengxinxi.txt", 'w')
except Exception as e:
students_txt = open(r"C:\Users\我\PycharmProjects\python产生txt存放地xueshengxinxi.txt", "x")
for information in stu_info:
students_txt.write(str(information) + "\n")
students_txt.close()
print("学生信息已经成功保存到xueshengxinxi.txt文档中!")
def read_stu_info():
old_infor = []
try:
students_txt = open(r'C:\Users\我\PycharmProjects\python产生txt存放地\xueshengxinxi.txt')
except FileNotFoundError:
print("文件打开失败,文件不存在")
return
while True:
xii = students_txt.readline()
if not xii:
break
xii = xii.rstrip()
xii = xii[1:-1]
student_dict = {}
for mom in xii.split(","):
key_value = []
for k in mom.split(":"):
k = k.strip()
if k[0] == k[-1] and len(k) > 2:
key_value.append(k[1:-1])
else:
key_value.append(int(k))
student_dict[key_value[0]] = key_value[1]
old_infor.append(student_dict)
students_txt.close()
return old_infor
def get_name(*l):
for x in l:
return x.get("name")
def get_age(*l):
for x in l:
return x.get("age")
def get_yu(*l):
for x in l:
return x.get("yu_wen")
def get_shu(*l):
for x in l:
return x.get("shu_xue")
def get_yin(*l):
for x in l:
return x.get("yin_yu")
def main():
stu_info = []
while True:
gongneng()
try:
mn = int(input('请输入功能选项(1-7): '))
except Exception as e:
print(e+"非全数字,系统识别出错")
if mn == 1:
stu_info = add_stu_info()
elif mn == 2:
while True:
try:
stu_info.remove(del_stu_info(stu_info))
except Exception as e:
print(e)
try:
mun = int(input("按1继续删除,按非1的数字返回主页面: "))
if mun == 1:
True
else:
break
except Exception as e:
print(e+"是非数字")
elif mn == 3:
while True:
try:
student = mod_stu_info(stu_info)
except Exception as e:
print(e)
else:
stu_info.remove(del_stu_info(stu_info, name11=student.get("name")))
print("该学生信息已被成功修改")
stu_info.append(student)
qwq = input("按任意数继续修改,回车键返回主页面: ")
if not qwq:
break
elif mn == 4:
show_all_stu(stu_info)
elif mn == 5:
save_stu_info(stu_info)
elif mn == 6:
stu_info = read_stu_info()
elif mn == 7:
break
else:
print("输入数字不在1-7之间,请重新输入")
continue
main()
|
3c7ccaca5bf7bcf5c68c14517bb56cceeeec996b | pfdamasceno/data-structures-algorithms | /chapter-01/P1.36.py | 1,008 | 4.25 | 4 | '''
P-1.36 Write a Python program that inputs a list of words, separated by whitespace,
and outputs how many times each word appears in the list. You
need not worry about efficiency at this point, however, as this topic is
something that will be addressed later in this book.
'''
def count_words(text):
'''
input: str(text) = text in the form of a string
output: dict(word_count) = dictionary of words as well as the number of occurences in the text
'''
words = [i.lower() for i in text.split()]
word_set = set(words)
count_dic = {}
for w in word_set:
count_dic[w] = 0
for w in words:
count_dic[w] += 1
return(count_dic)
if __name__ == "__main__":
print(count_words("Write a Python program that inputs a list of words, separated by whitespace, and outputs how many times each word appears in the list. You need not worry about efficiency at this point, however, as this topic is something that will be addressed later in this book."))
#
|
8988148eda0c24c5c29bf3201bed1bab74d1b678 | GeoGamez/Python | /PythonPrograms/triangle.py | 400 | 4.1875 | 4 | #input for both programs
integer= int(input("Please enter a number 1 or greater: "))
#triangle
if integer == 1:
print("*")
else:
print('*') #the starting triangle always only has 1 *
for x in range(0,integer-2): # this for loop prints all the hollow chucks and to ensure inputting 1 and 2 don't make *'s I subtract 2
print('*' + " " * x + '*')
print('*'*integer) # closing the triangle
|
c4bedcb4f9462b2dec19aa823eddd438526e793f | prhod/mailsender | /src/mysmtp.py | 2,001 | 3.5625 | 4 | from smtplib import SMTP, SMTPAuthenticationError
from email.base64mime import body_encode as encode_base64
import base64
class mySMTP(SMTP):
def auth(self, mechanism, authobject, *, initial_response_ok=True):
"""Authentication command - requires response processing.
'mechanism' specifies which authentication mechanism is to
be used - the valid values are those listed in the 'auth'
element of 'esmtp_features'.
'authobject' must be a callable object taking a single argument:
data = authobject(challenge)
It will be called to process the server's challenge response; the
challenge argument it is passed will be a bytes. It should return
bytes data that will be base64 encoded and sent to the server.
Keyword arguments:
- initial_response_ok: Allow sending the RFC 4954 initial-response
to the AUTH command, if the authentication methods supports it.
"""
# RFC 4954 allows auth methods to provide an initial response. Not all
# methods support it. By definition, if they return something other
# than None when challenge is None, then they do. See issue #15014.
mechanism = mechanism.upper()
initial_response = (authobject() if initial_response_ok else None)
if initial_response is not None:
response = encode_base64(initial_response.encode('utf-8'), eol='')
(code, resp) = self.docmd("AUTH", mechanism + " " + response)
else:
(code, resp) = self.docmd("AUTH", mechanism)
# If server responds with a challenge, send the response.
if code == 334:
challenge = base64.decodebytes(resp)
response = encode_base64(
authobject(challenge).encode('utf-8'), eol='')
(code, resp) = self.docmd(response)
if code in (235, 503):
return (code, resp)
raise SMTPAuthenticationError(code, resp) |
9f46d296bf6148a94c08b0c3fc98e4412306601b | Dadajon/100-days-of-code | /competitive-programming/hackerrank/algorithms/implementation/043-library-fine/lib_fine.gyp | 978 | 3.5625 | 4 | def library_fine(return_day, return_month, return_year,
expect_day, expect_month, expect_year):
if return_year > expect_year:
return 10000
if return_year < expect_year:
return 0
if return_month > expect_month:
return 500 * (return_month - expect_month)
if return_month < expect_month:
return 0
if return_day > expect_day:
return 15 * (return_day - expect_day)
return 0
if __name__ == '__main__':
returned_date = input().split()
returned_day = int(returned_date[0])
returned_month = int(returned_date[1])
returned_year = int(returned_date[2])
expected_date = input().split()
expected_day = int(expected_date[0])
expected_month = int(expected_date[1])
expected_year = int(expected_date[2])
result = library_fine(returned_day, returned_month, returned_year,
expected_day, expected_month, expected_year)
print(str(result) + '\n')
|
fe8aa084942310901710d3174bafd51e2ced96ee | OCoderO/Elements-of-Software-Design---UT-Austin | /Expression Tree - A17/ExpressionTree.py | 5,808 | 3.65625 | 4 | # File: ExpressionTree.py
# Description:
# Student Name: Rosemary Cramblitt
# Student UT EID: rkc753
# Partner Name: Wendy Zhang
# Partner UT EID: wz4393
# Course Name: CS 313E
# Unique Number: 52240
# Date Created: 4/17/21
# Date Last Modified: 4/19/21
import sys
operators = ['+', '-', '*', '/', '//', '%', '**']
class Stack (object):
def __init__(self):
self.stack = []
def push(self, data):
self.stack.append (data)
def pop(self):
if(not self.is_empty()):
return self.stack.pop()
else:
return None
def is_empty(self):
return len(self.stack) == 0
class Node (object):
def __init__ (self, data = None, lChild = None, rChild = None):
self.data = data
self.lChild = lChild
self.rChild = rChild
class Tree (object):
def __init__ (self):
self.root = Node(None)
# this function takes in the input string expr and
# creates the expression tree
def create_tree (self, expr):
# Assume that the expression string is valid and there are spaces between the operators, operands, and the parentheses.
#Take the expression string and break it into tokens, split where there is empty space
expression = expr.split()
new_stack = Stack()
#Start with an empty node, that is the root node, call it the current node
current_node = self.root
#4 types of tokens - left parenthesis, right parenthesis, operator, and operand
for token in expression:
#If the current token is a left parenthesis add a new node as the left child of the current node. Push current node on the stack and make current node equal to the left child.
if token == '(':
new_stack.push(current_node)
current_node.lChild = Node(None)
current_node = current_node.lChild
#If the current token is an operator set the current node's data value to the operator. Push current node on the stack. Add a new node as the right child of the current node and make the current node equal to the right child.
elif token in operators:
current_node.data = token
new_stack.push(current_node)
current_node.rChild = Node(None)
current_node = current_node.rChild
#If the current token is an operand, set the current node's data value to the operand and make the current node equal to the parent by popping the stack.
elif token.isdigit() or '.' in token:
current_node.data = token
current_node = new_stack.pop()
#If the current token is a right parenthesis make the current node equal to the parent node by popping the stack if it is not empty.
elif token == ')':
if not new_stack.is_empty():
current_node = new_stack.pop()
else:
break
# this function should evaluate the tree's expression
# returns the value of the expression after being calculated
def evaluate (self, aNode):
#operators = ['+', '-', '*', '/', '//', '%', '**']
if aNode.data == '+':
return float(self.evaluate(aNode.lChild) + self.evaluate(aNode.rChild))
elif aNode.data == '-':
return float(self.evaluate(aNode.lChild) - self.evaluate(aNode.rChild))
elif aNode.data == '*':
return float(self.evaluate(aNode.lChild) * self.evaluate(aNode.rChild))
elif aNode.data == '/':
return float(self.evaluate(aNode.lChild) / self.evaluate(aNode.rChild))
elif aNode.data == '//':
return float(self.evaluate(aNode.lChild) // self.evaluate(aNode.rChild))
elif aNode.data == '%':
return float(self.evaluate(aNode.lChild) % self.evaluate(aNode.rChild))
elif aNode.data == '**':
return float(self.evaluate(aNode.lChild) ** self.evaluate(aNode.rChild))
elif aNode.data.isdigit() or '.' in aNode.data:
return eval(aNode.data)
# this function should generate the preorder notation of
# the tree's expression
# returns a string of the expression written in preorder notation
def pre_order (self, aNode):
#make sure the list is not empty
if (aNode.lChild == None) and (aNode.rChild == None):
return aNode.data
#for preorder, check and add to str firsrt: center, left, right
else:
return aNode.data + " "+ self.pre_order(aNode.lChild) + " " + self.pre_order(aNode.rChild)
# this function should generate the postorder notation of
# the tree's expression
# returns a string of the expression written in postorder notation
def post_order (self, aNode):
#make sure list is not empty
if (aNode != None):
#create nodelist
node = ""
node+=str(self.post_order(aNode.lChild))
node+=str(self.post_order(aNode.rChild))
storeddata=aNode.data
#for preorder, add first then check and add to str: left, right, center
if storeddata!=None:
node+=str(aNode.data)+ " "
return node
return ""
# you should NOT need to touch main, everything should be handled for you
def main():
# read infix expression
line = sys.stdin.readline()
expr = line.strip()
tree = Tree()
tree.create_tree(expr)
# evaluate the expression and print the result
print(expr, "=", str(tree.evaluate(tree.root)))
# get the prefix version of the expression and print
print("Prefix Expression:", tree.pre_order(tree.root).strip())
# get the postfix version of the expression and print
print("Postfix Expression:", tree.post_order(tree.root).strip())
if __name__ == "__main__":
main()
# Prefix Expression: * + 8 3 - 7 2
# Postfix Expression: 8 3 + 7 2 - *
|
2f8d3c620fc13ba966c2fc16421040467575cdd2 | erneslobo/Python_Basico_2_2019 | /Tarea4/Tarea4.py | 2,028 | 3.953125 | 4 | #Suponga que se tiene una lista de listas que se tiene diversas cantidades por persona.
# La primera columna con números representa la cantidad en miles de colones que tienen en la cuenta del banco,
# la segunda columna la cantidad en crédito en miles de colones y
# la tercer columna en miles de colones en deuda.
hoja_calculo = [
['carlos', 54.54,6.57,3.64],
['juan', 5.54,9.57,4.64],
['luis', 9.54,7.57,1.64] ,
]
def transpuesta(hoja_calculo):
return [list(i) for i in zip(*hoja_calculo)]
b = transpuesta(hoja_calculo)
print(b) #sea b la tabla resultante luego de aplicar transpuesta
#Por otro lado, se puede aplicar matemática o cualquier otra operación a alguna fila en específico.
# Por ejemplo: dividir todos los números entre 10. Obteniendo:
#b[1] = list(map(lambda x: x/10, b[1]))
#print(b)
#print(b[1::])
#Contruya un diccionario de funciones matematicas (utilizando funciones lambda) entre todos los números de la lista tales como:
#Promedio
#La suma
#La multiplicación
import functools
promedio = lambda x,y : x / y
suma = lambda x,y : x + y
multiplicacion = lambda x,y : x * y
intereses = lambda x: x*1.20
fm = {
'promedio' : promedio,
'suma' : suma,
'multiplicacion' : multiplicacion,
'intereses' : intereses
}
#Obtenga utilizando el diccionario de funciones:
#1. El promedio de la cantidad miles de colones en débito: cuánto tienen en promedio todas las personas.
print('El promedio de la cantidad miles de colones en débito:', (fm['promedio'])(sum(b[1]),len(b[1])))
#2. La suma de todas las deudas
print('La suma de todas las deudas:',functools.reduce(fm['suma'],b[3]))
#3. la multiplicación de todos los crédito entre si
print('La suma de todas las deudas:',functools.reduce(fm['multiplicacion'],b[2]))
#Actualice (en la tabla general)los valores de los créditos aplicando un impuesto del 20% (esto es multiplicar por 1.2) a toda la fila de créditos usando el diccionario de funciones.
b[2] = list(map(fm['intereses'], b[2]))
print(b)
pass
|
a21cb56d6d59115421d6531bbf648ad60156d75e | gregariouspanda/Julia-learns-python | /generate_story.py | 745 | 3.875 | 4 | import sys
import create_dictionary
import random
def main():
num_words = sys.argv[2]
word_dict = create_dictionary.create_dictionary(sys.argv[1])
print(generate_story(word_dict, int(num_words)))
def generate_story(word_dict, num_words):
story = ''
words = 0
last_word_added = word_dict['$'][random.randint(0, len(word_dict['$'])-1)]
story += last_word_added
words += 1
while words < num_words:
last_word_added = word_dict[last_word_added][random.randint(0, len(word_dict[last_word_added])-1)]
if last_word_added == '$':
story += ". "
else:
story += ' ' + last_word_added
words += 1
return story
if __name__ == '__main__':
main()
|
3ad7122c083bcf7ed8d8a5a4937ef9400bc9030b | freebz/Foundations-for-Analytics-with-Python | /ch01/ex1-6.py | 1,150 | 4.1875 | 4 | print("Output #14: {0:s}".format('I\'m enjoying learning Python.'))
print("Output #15: {0:s}".format("This is a long string. Without the backslash\
it would run off of the page on the right in the text editor and be very\
difficult to read and edit. By using the backslash you can split the long\
string into smaller strings on separate lines so that the whole string is easy\
to view in the text editor."))
print("Output #16: {0:s}".format('''You can use triple single quotes
for multi-line comment strings.'''))
print("Output #17: {0:s}".format("""You can also use triple double quotes
for multi-line comment strings."""))
# Output #14: I'm enjoying learning Python.
# Output #15: This is a long string. Without the backslashit would run off of the page on the right in the text editor and be verydifficult to read and edit. By using the backslash you can split the longstring into smaller strings on separate lines so that the whole string is easyto view in the text editor.
# Output #16: You can use triple single quotes
# for multi-line comment strings.
# Output #17: You can also use triple double quotes
# for multi-line comment strings.
|
1b1bf66df81fdb3960523c915521fdcb6f46d2d2 | jimas95/Intro_to_AI | /lab4/student_code.py | 3,436 | 3.53125 | 4 | import common
# return true if game is over (Tie)
# check if the board if tie (full)
def is_tie(board):
res = True
for item in board:
if(item==0):
res = False
return res
# max value of minimax
def max_value(state):
v = - 1000000
# check state
result = common.game_status(state)
# if someone won or its a tie return
if(result == common.constants.X):
return 10
if(result == common.constants.O):
return -10
if(is_tie(state)):
return 0
for y in range(3): # open all possible moves
for x in range(3):
# play new move
cell_num = common.get_cell(state,y,x)
if(cell_num==0):
new_state = state.copy()
common.set_cell(new_state,y,x,common.constants.X)
v = max(v,min_value(new_state)) # estimate
return v
# min value of minimax
def min_value(state):
v = 1000000
# check state
result = common.game_status(state)
# if someone won or its a tie return
if(result == common.constants.X):
return 10
if(result == common.constants.O):
return -10
if(is_tie(state)):
return 0
for y in range(3): # open all possible moves
for x in range(3):
# play new move
cell_num = common.get_cell(state,y,x)
if(cell_num==0):
new_state = state.copy()
common.set_cell(new_state,y,x,common.constants.O)
v = min(v,max_value(new_state)) # estimate
return v
def minmax_tictactoe(board, turn):
result = common.constants.NONE
if(turn==common.constants.X):
result = max_value(board)
if(turn==common.constants.O):
result = min_value(board)
if(result==10):
return common.constants.X
elif(result==-10):
return common.constants.O
return common.constants.NONE
def max_valueAB(state,alpha,beta):
v = - 1000000
# check state
result = common.game_status(state)
# if someone won or its a tie return
if(result == common.constants.X):
return 10
if(result == common.constants.O):
return -10
if(is_tie(state)):
return 0
for y in range(3): # open all possible moves
for x in range(3):
# play new move
cell_num = common.get_cell(state,y,x)
if(cell_num==0):
new_state = state.copy()
common.set_cell(new_state,y,x,common.constants.X)
v = max(v,min_valueAB(new_state,alpha,beta)) # estimate
if(v>=beta):
return v
alpha = max(alpha,v)
return v
def min_valueAB(state,alpha,beta):
v = 1000000
# check state
result = common.game_status(state)
# if someone won or its a tie return
if(result == common.constants.X):
return 10
if(result == common.constants.O):
return -10
if(is_tie(state)):
return 0
for y in range(3): # open all possible moves
for x in range(3):
# play new move
cell_num = common.get_cell(state,y,x)
if(cell_num==0):
new_state = state.copy()
common.set_cell(new_state,y,x,common.constants.O)
v = min(v,max_valueAB(new_state,alpha,beta)) # estimate
if v<=alpha :
return v
beta = min(beta,v)
return v
def abprun_tictactoe(board, turn):
# init variables
result = common.constants.NONE
alpha = -100000
beta = 100000
if(turn==common.constants.X):
result = max_valueAB(board,alpha,beta)
if(turn==common.constants.O):
result = min_valueAB(board,alpha,beta)
if(result==10):
return common.constants.X
elif(result==-10):
return common.constants.O
return common.constants.NONE
|
78ff3b3df166ced7acecf3d475e1c731887cf903 | rupesh1219/python | /games/guess_the_number.py | 1,220 | 4.3125 | 4 | ########################################################################
# generate a random number
# user has to guess the random number generated and will input via console
# then compare the output and input - indicate whether the guess is too
# high or low , if correct give a positive indication
# lets say we give him 3 chances and break the function
########################################################################
import random
def generate_random(min, max):
generated = random.sample(range(min, max), 1)
for i in generated:
return i
def user_guess():
guess = int(input('enter guess:'))
return guess
def main(min, max):
generated = generate_random(min, max)
count = 0
while(count < 3):
guess = user_guess()
if abs(generated - guess) > generated:
print('the number is high')
count += 1
elif abs(generated - guess) < generated:
print('the number is low')
count += 1
else:
print('hurray you have guessed the right number')
break
else:
print('you have reached maximum attempts')
print('correct answer is %d', generated)
main(1, 6)
|
27cd9964735e227d870f0b56988319245a7e4fca | ddeneau/Simulations | /OrbitSim.py | 6,700 | 3.546875 | 4 | # Simulation of two dimensional orbital mechanics.
# All numerical values are scaled down for no real noticeable performance improvements.
# This is simply done to improve code readability and does simplify some calculations (for me).
import numpy
import scipy.constants
import pygame
import random
WIDTH = 1400
HEIGHT = 800
MINIMUM_ECCENTRICITY, MAXIMUM_ECCENTRICITY = 1, 10
MINIMUM_MASS, MAXIMUM_MASS = 5, 20
MINIMUM_BODIES, MAXIMUM_BODIES = 1, 6
LOWER_X_BOUNDARY, UPPER_X_BOUNDARY = 150, 450
LOWER_Y_BOUNDARY, UPPER_Y_BOUNDARY = 50, 250
# Simulation state changes. Keeps objects within bounds.
def adjust_coordinates(body):
if body.x < 0:
body.x += 500
else:
body.x += 500
if body.y < 0:
body.y += 500
else:
body.y += 500
body.x = (int(body.x))
body.y = (int(body.y))
# Stores general information that applies to all objects in the simulation, as well
# as the graphical features.
class Mechanics:
def __init__(self, semi_major, semi_minor, focus):
self.semi_major = semi_major # The semi-major axis (Of the one star)
self.semi_minor = semi_minor # The semi-minor axis (Of the one star)
self.focus = focus # Focus of ellipse (Of the one star)
self.star = Body(50, 25, int(WIDTH / 2), int(HEIGHT / 2), 0, 0, 0) # main star (mass, radius)
self.screen = pygame.display.set_mode((WIDTH, HEIGHT)) # Making of the screen
self.bodies = list() # List of the stuff to be simulated.
self.generate_bodies() # Start creating stuff to orbit.
# Generates anywhere from one to the default number of bodies for the simulation. (Can be any number really).
def generate_bodies(self):
for i in range(random.randint(MINIMUM_BODIES, MAXIMUM_BODIES)):
mass = random.randint(MINIMUM_MASS, MAXIMUM_MASS)
x = random.randint(LOWER_X_BOUNDARY, UPPER_X_BOUNDARY)
y = random.randint(LOWER_Y_BOUNDARY, UPPER_Y_BOUNDARY)
radius = mass
e = random.randrange(MINIMUM_ECCENTRICITY, MAXIMUM_ECCENTRICITY) / 1000
theta = random.randrange(1, 5)
offset = i / 100
self.bodies.append(Body(mass, radius, x, y, e, theta, e + offset))
# Updates alpha with new angular acceleration.
def compute_force(self, body):
mass = self.star.mass
r_squared = body.distance**2
body.alpha = scipy.constants.gravitational_constant * mass / r_squared
# Calculates new angular velocity
def compute_angular_velocity(self, body):
body.omega = numpy.sqrt(body.alpha / (body.mass * numpy.power(self.semi_major, 3)))
# Update x and y values of planet based off of Kepler's Law's
def compute_radial_vector(self, body):
# semi_major/distance
x = (body.distance * numpy.cos(body.theta)) - body.eccentricity
y = (body.distance * numpy.sin(body.theta) * (1 - numpy.power(body.eccentricity, 2)))
body.update_state(x, y, body.theta, body.omega)
# Computations of one tick of the simulation.
def run_simulation_frame(self):
for body in self.bodies:
self.screen.fill((100, 100, 100)) # Reset the screen to black so object renders do not compound per frame.
self.compute_force(body) # Force and angular acceleration equation.
self.compute_angular_velocity(body) # Angular velocity equation.
self.compute_radial_vector(body) # Updates x and y positions.
body.update_angle() # Increments angle to move time forward.
body.check_angle() # Make sure no angle exceeds 2pi rads.
# Coordinate adjustment to fit with pygame coordinate scheme.
# Initializes simulation as well as pygame window.
def init_graphics(self):
clock = pygame.time.Clock() # Use PyGames build in clock feature for timekeeping.
pygame.display.set_caption('Orbit Simulation') # Name for the window.
self.screen.fill((100, 100, 100)) # This syntax fills the background colour
pygame.display.flip() # Activates the display.
planet_radii = list()
star_radius = self.star.radius
r = [0] * len(self.bodies)
g = [0] * len(self.bodies)
b = [0] * len(self.bodies)
for i in range(len(self.bodies)):
r[i] = random.randrange(0, 120)
g[i] = random.randrange(0, 150)
b[i] = random.randrange(0, 170)
for body in self.bodies:
planet_radii.append(body.radius)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
self.run_simulation_frame()
for body in self.bodies:
adjust_coordinates(body)
pygame.draw.circle(self.screen, (200, 0, 0), (self.star.x, self.star.y), star_radius, star_radius)
i = 0
for body in self.bodies:
pygame.draw.circle(self.screen, (r[i], g[i], b[i]), (body.x, body.y), body.radius, body.radius)
i += 1
pygame.display.update()
clock.tick(100)
pygame.quit()
# A object that experience state changes in relation to physical forces.
class Body:
def __init__(self, mass, radius, x, y, eccentricity, theta, phi):
self.mass = mass # Mass of body.
self.radius = radius # Radius of body
self.x = x # x coordinate
self.y = y # y coordinate
self.omega = 0 # Angular velocity
self.alpha = 0 # Angular acceleration
self.theta = theta # Angle between distance from star and x-axis
self.phi = phi # Angle between radius, from focus, and x-axis
self.eccentricity = eccentricity # Deviation from circular orbit.
self.distance = int(numpy.sqrt(x ** 2 + y ** 2)) # Radial distance from star.
# Change state of body based on parameters.
def update_state(self, x, y, alpha, omega):
self.x = x
self.y = y
self.alpha = alpha
self.omega = omega
print({"x": x}, {"y": y}, self.eccentricity)
# Keeps us between 0 and 2Pi
def check_angle(self):
if self.phi > 2 * numpy.pi:
self.phi = 0
if self.theta > 2 * numpy.pi:
self.theta = 0
# Updates value of angle between semi-major axis and the vector from the star to the planet.
def update_angle(self):
self.theta += numpy.arctan(numpy.tan(self.phi / 2) /
numpy.sqrt((1 + self.eccentricity) / (1 - self.eccentricity)))
# Runs program.
m = Mechanics(200, 150, 100)
m.init_graphics()
|
1056f7199d51ed5c70721450513df7bba1c47b89 | leilei92/Coding-Algorithm | /DFS/valid_parentheses.py | 711 | 3.6875 | 4 | # given n pairs of parenthese, write a function to generate
# all combinations of well-formed parentheses
# for example: n = 3
class Solution(object):
def validParentheses(self, n):
answers, sequence = [], []
self.bt(answers, sequence, n, 0, 0)
return answers
def bt(self, answers, sequence, n, l, r):
if l == r == n: # len(sequence) == 2*n
answers.append(''.join(sequence))
return
if l < n:
sequence.append('(')
self.bt(answers, sequence, n, l + 1, r)
sequence.pop()
if l > r:
sequence.append(')')
self.bt(answers, sequence, n, 1, r + 1)
sequence.pop()
|
a370294aeaa1aeeb3a146c2d8c6e9e2a86d923ec | EHwooKim/Algorithms | /프로그래머스/level2/42585.py | 460 | 3.578125 | 4 | def solution(arrangement):
answer = 0
count = 0
pre_open = False
for bracket in arrangement:
if bracket == '(':
count += 1
pre_open = True
else:
if pre_open == True:
count -= 1
answer += count
else:
count -= 1
answer += 1
pre_open = False
return answer
print(solution('()(((()())(())()))(())')) |
4db51652518fef57ac9790e7fe0a8088c1d15c12 | woodyhoko/CSES.fi | /Introductory Problems/Permutations.py | 172 | 3.625 | 4 | s = int(input())
if s==1:
print(1)
elif s<4:
print("NO SOLUTION")
else:
print(' '.join(str(x) for x in range(2,s+1,2)),' '.join(str(x) for x in range(1,s+1,2))) |
ca9ae852accb440c6114a6c9ba568109f48d5c87 | sanyatishenko/PythonEDU | /if.py | 437 | 4.28125 | 4 | ###################################
# Условный оператор if-elif-else
###################################
a = int(input('Введите число: '))
if a < 0 :
print("Число", a,"отрицательное.")
elif a == 0 :
print("Ноль.")
else :
print("Число", a,"положительное.")
# Короткая запись if
print(a,"не равно нулю") if a else print("Ноль") |
3775ec7628085b56b4ee20a556459ac940d38e76 | rtsaunders19/_python_ | /mod.py | 141 | 3.5 | 4 |
try:
a = 20
b = 0
print(a/b)
except ZeroDivisionError:
print('hey this is an error')
finally:
print('this always shows') |
14cce1981162db3593f8e542342d1ff87f0d5e12 | fifa007/Leetcode | /src/house_robber.py | 973 | 3.828125 | 4 | #!/usr/bin/env python2.7
'''
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed,
the only constraint stopping you from robbing each of them is that
adjacent houses have security system connected and it will automatically contact
the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house,
determine the maximum amount of money you can rob tonight without alerting the police.
'''
import math
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums is None or len(nums) == 0:
return 0
a_0 = 0
a_1 = nums[0]
ret = nums[0]
i = 1
while i < len(nums):
ret = max(a_0 + nums[i], a_1)
a_0 = a_1
a_1 = ret
i += 1
return ret |
f623caaaf1541fef2af5b0d74574d2e66993b16d | jorgesanme/Python | /Ejercicios/Pildoras/nota_if_.py | 469 | 3.953125 | 4 | def evalua(nota):
valoracion="aprobado"
if nota<0:
print("nota no validad")
elif 0<nota<5:
return "suspenso"
elif 0<nota>=5 and nota<6:
return "aprobado"
elif 0<nota>=6 and nota<8:
return "bien"
elif nota>=8 and nota<9:
return "notable"
else:
return "sobresaliente"
nota= int (input("introduzca nota: "))
print(evalua(nota))
if nota in range(0, 5):
print(" hay que estudiar más")
|
77d66875a60529bbb4fb634cd51d12abb165c3a4 | 0xJinbe/Exercicios-py | /Ex 045.py | 599 | 4.25 | 4 | """Faça um programa que peça dois números, base e expoente, calcule e mostre o primeiro número elevado ao segundo número. Não utilize a função de potência da linguagem."""
print("base ^ expoente:")
base=int(input("Base: "))
expoente=int(input("Expoente: "))
potencia=1
count=1
while count <= expoente:
potencia *= base
count +=1
print(base,"^",expoente,"=",potencia)
#for
print("base ^ expoente:")
base=int(input("Base: "))
expoente=int(input("Expoente: "))
potencia=1
for count in range(expoente):
potencia *= base
count += 1
print(base,"^",expoente,"=",potencia)
|
95bc7e2ca5482232a1225a7c77d5f3bfc449593d | sungis/test-code | /service_examples/radix_tree.py | 11,633 | 3.875 | 4 | from collections import deque
class RadixTree:
def __init__(self):
"""
Create a Radix Tree with only the default node root.
"""
self.root = RadixTreeNode()
self.root.key = ""
self.size = 0
def insert(self, key, value, node=None):
"""
Recursively insert the key in the radix tree
"""
if not node:
node = self.root
self.size += 1
number_of_matching_chars = node.get_number_of_matching_characters(key)
# we are either at the root node
# or we need to go down the tree
if node.key == "" or number_of_matching_chars == 0 or (
number_of_matching_chars < len(key) and number_of_matching_chars >= len(node.key)):
flag = False
new_text = key[number_of_matching_chars:]
for child in node.children:
if child.key.startswith(new_text[0]):
flag = True
self.insert(new_text, value, child)
break
# just add the node as the child of the current node
if not flag:
n = RadixTreeNode()
n.key = new_text
n.real = True
n.value = value
node.children.append(n)
# there is an exact match, just make the current node a data node
elif number_of_matching_chars == len(key) and number_of_matching_chars == len(node.key):
if node.real:
raise DuplicateKeyError("Duplicate Key: '%s' for value: '%s' " % (key, node.value))
node.real = True
node.value = value
# this node needs to be split as the key to be inserted
# is a prefix of the current node key
elif number_of_matching_chars > 0 and number_of_matching_chars < len(node.key):
n1 = RadixTreeNode()
n1.key = node.key[number_of_matching_chars:]
n1.real = node.real
n1.value = node.value
n1.children = node.children
node.key = key[0:number_of_matching_chars]
node.real = False
node.children = [n1]
if number_of_matching_chars < len(key):
n2 = RadixTreeNode()
n2.key = key[number_of_matching_chars:]
n2.real = True
n2.value = value
node.children.append(n2)
else:
node.value = value
node.real = True
# this key needs to be added as the child of the current node
else:
n = RadixTreeNode()
n.key = node.key[number_of_matching_chars:]
n.children = node.children
n.real = node.real
n.value = node.value
node.key = key
node.real = True
node.value = value
node.children.append(n)
def delete(self, key):
"""
Deletes the key from the trie
"""
visitor = VisitorDelete()
self.visit(key, visitor)
if (visitor.result):
self.size -= 1
return visitor.result
def find(self, key):
"""
Returns the value for the given key
"""
visitor = VisitorFind()
self.visit(key, visitor)
return visitor.result
def complete(self, key, node=None, base=""):
"""
Complete the a prefix to the point where ambiguity starts.
Example:
If a tree contain "blah1", "blah2"
complete("b") -> return "blah"
Returns the unambiguous completion of the string
"""
if not node:
node = self.root
i = 0
key_len = len(key)
node_len = len(node.key)
while i < key_len and i < node_len:
if key[i] != node.key[i]:
break
i += 1
if i == key_len and i <= node_len:
return base + node.key
elif node_len == 0 or (i < key_len and i >= node_len):
beginning = key[0:i]
ending = key[i:key_len]
for child in node.children:
if child.key.startswith(ending[0]):
return self.complete(ending, child, base + beginning)
return ""
def search_prefix(self, key, record_limit):
"""
Returns all keys for the given prefix
"""
keys = []
node = self._search_prefix(key, self.root)
if node:
if node.real:
keys.append(node.value)
self.get_nodes(node, keys, record_limit)
return keys
def high_light(self,content):
buff = ''
index = 0
c_len=len(content)
while (index < c_len):
key = content[index]
matches = self.search_prefix(key,100)
flag = False
for m in matches:
if (index + len(m) > c_len):
continue
matchsource=content[index:index+len(m)]
if(matchsource.lower() == m):
buff += '<b>' + matchsource + '<b>'
index +=len(m)
flag = True
break
if flag :
continue
buff += key
index +=1
return buff
def _search_prefix(self, key, node):
"""
Util for the search_prefix function
"""
result = None
number_of_matching_chars = node.get_number_of_matching_characters(key)
if number_of_matching_chars == len(key) and number_of_matching_chars <= len(node.key):
result = node
elif node.key == "" or (number_of_matching_chars < len(key) and number_of_matching_chars >= len(node.key)):
new_text = key[number_of_matching_chars:]
for child in node.children:
if child.key.startswith(new_text[0]):
result = self._search_prefix(new_text, child)
break
return result
def get_nodes(self, parent, keys, limit):
"""
Updates keys... (not really sure)
"""
queue = deque(parent.children)
while len(queue) != 0:
node = queue.popleft()
if node.real:
keys.append(node.value)
if len(keys) == limit:
break
queue.extend(node.children)
def visit(self, prefix, visitor, parent=None, node=None):
"""
Recursively visit the tree based on the supplied "key". Calls the Visitor
for the node those key matches the given prefix
"""
if not node:
node = self.root
number_of_matching_chars = node.get_number_of_matching_characters(prefix)
# if the node key and prefix match, we found a match!
if number_of_matching_chars == len(prefix) and number_of_matching_chars == len(node.key):
visitor.visit(prefix, parent, node)
# we are either at the root OR we need to traverse the children
elif node.key == "" or (number_of_matching_chars < len(prefix) and number_of_matching_chars >= len(node.key)):
new_text = prefix[number_of_matching_chars:]
for child in node.children:
# recursively search the child nodes
if child.key.startswith(new_text[0]):
self.visit(new_text, visitor, node, child)
break
def contains(self, key):
"""
Returns True if the key is valid. False, otherwise.
"""
visitor = VisitorContains()
self.visit(key, visitor)
return visitor.result
def debug(self):
"""
Returns a string representation of the radix tree.
WARNING: Do not use on large trees!
"""
lst = []
self._debug_node(lst, 0, self.root)
return "\r".join(lst)
def _debug_node(self, lst, level, node):
"""
Recursive utility method to generate visual tree
WARNING: Do not use on large trees!
"""
temp = " " * level
temp += "|"
temp += "-" * level
if node.real:
temp += "%s[%s]" % (node.key, node.value)
else:
temp += "%s" % (node.key)
lst.append(temp)
for child in node.children:
self._debug_node(lst, level + 1, child)
class RadixTreeNode(object):
def __init__(self):
self.key = ""
self.children = []
self.real = False
self.value = None
def get_number_of_matching_characters(self, key):
number_of_matching_chars = 0
while number_of_matching_chars < len(key) and number_of_matching_chars < len(self.key):
if key[number_of_matching_chars] != self.key[number_of_matching_chars]:
break
number_of_matching_chars += 1
return number_of_matching_chars
class Visitor(object):
def __init__(self, initial_value=None):
self.result = initial_value
def visit(self, key, parent, node):
pass
class VisitorFind(Visitor):
def visit(self, key, parent, node):
if node.real:
self.result = node.value
class VisitorContains(Visitor):
def visit(self, key, parent, node):
self.result = node.real
class VisitorDelete(Visitor):
def visit(self, key, parent, node):
self.result = node.real
# if it is a real node
if self.result:
# If there are no node children we need to
# delete it from its parent's children list
if len(node.children) == 0:
for child in parent.children:
if child.key == node.key:
parent.children.remove(child)
break
# if the parent is not a real node and there
# is only one child then they need to be merged
if len(parent.children) == 1 and not parent.real:
self.merge_nodes(parent, parent.children[0])
# we need to merge the only child of this node with itself
elif len(node.children) == 1:
self.merge_nodes(node, node.children[0])
# we just need to mark the node as non-real
else:
node.real = False
def merge_nodes(self, parent, child):
"""
Merge a child into its parent node. The operation is only valid if it is
the only child of the parent node and parent node is not a real node.
"""
parent.key += child.key
parent.real = child.real
parent.value = child.value
parent.children = child.children
class DuplicateKeyError(Exception):
pass
if __name__ == "__main__":
rt = RadixTree()
rt.insert("apple", "apple")
rt.insert("appleshack", "appleshack")
rt.insert("appleshackcream", "appleshackcream")
rt.insert("applepie", "applepie")
rt.insert("ape", "ape")
content = "apple ape applepie hhj"
rt.high_light(content)
buff = ''
index = 0
c_len=len(content)
while (index < c_len):
key = content[index]
matches = rt.search_prefix(key,100)
flag = False
for m in matches:
if (index + len(m) > c_len):
continue
matchsource=content[index:index+len(m)]
if(matchsource.lower() == m):
buff += '<b>' + matchsource + '<b>'
index +=len(m)
flag = True
break
if flag :
continue
buff += key
index +=1
print buff
print(rt.debug())
|
d9e7519d897251a3a79f9278ad7ee99272415a91 | Python87-com/PythonExercise | /day09_20191111/w.py | 343 | 3.75 | 4 | count = 1
# 纸张厚度
thickness = 0.01
# while 循环里需要计算单位的一致性,如果改成米的话,则前面输出的厚度会出现科学计数法
while thickness < 8848430:
thickness = thickness * 2 # 这里也可以写成 thickness *= 2 效果是一样的
count += 1
print(thickness)
print(count - 1)
|
7f7593d3b04e41fe5445d67367150ccc60e23d83 | FatemehRezapoor/LearnPythonTheHardWay | /LearnPythonTheHardWay/E11_12AskQuestion.py | 516 | 4.1875 | 4 | # May 31, 2018
# Exercise 11-13
# ** ASK FOR INPUT FROM USER **
print('How old are you?')
age = input()
print('How tall are you?')
height = input()
print('I am %s years old and I am %r tall' % (age, height)) # The user input is string
# Another Method to combine print with input command
age = input('How old are you:')
print('I am %s years old' % age)
# My Tiny project: Ask for numbers from user and add them up
print('Please enter two numbers')
a = int(input())
b = int(input())
print(a + b)
|
e76f993f41ffeb13abdc6977b41ae139713df80e | RubennCastilloo/master-python | /09-listas/predefenidas.py | 707 | 4.28125 | 4 | cantantes = ['Megan Nicole', 'Dua Lipa', 'Bebe Rexha']
numeros = [1, 2, 5, 8, 3, 4]
# Ordenar una lista
print(numeros)
numeros.sort()
print(numeros)
# Añadir elementos
cantantes.append("Bruno Mars")
print(cantantes)
cantantes.insert(1,"David Bisbal")
print(cantantes)
# Eliminar elementos
cantantes.pop(1)
cantantes.remove("Bebe Rexha")
print(cantantes)
# Dar la vuelta
print(numeros)
numeros.reverse()
print(numeros)
# Buscar dentro de una lista
print("Bruno Mars" in cantantes)
# Contar elementos
print(len(cantantes))
# Cuantas veces aparece un elemento
numeros.append(8)
print(numeros.count(8))
# Conseguir un indice
print(cantantes)
print(cantantes.index("Megan Nicole"))
# Unir listas
cantantes.extend(numeros)
print(cantantes) |
3b3648d8a9018ddaa341def031213dd0036c21f9 | rafal-mizera/UDEMY | /kurs_dla_poczatkujacych/for.py | 1,444 | 3.546875 | 4 | data = ['Error:File cannot be open',
'Error:No free space on disk',
'Error:File missing',
'Warning:Internet connection lost',
'Error:Access denied']
elements = []
for el in data:
elements = list(el.split(":"))
if elements[0] == "Error":
print(elements[0].upper(),elements[1].upper())
else:
print(elements[0].upper(), elements[1])
string_A = '+---+---+---+---+'
string_B = '| | | | |'
for num in range(1,10):
if num % 2 != 0:
print(string_A)
else:
print(string_B)
for num in range(1,10):
if num % 2 == 0:
print(num * "x")
else:
print(num * "o")
#####################################################
"""W tym zadaniu obliczysz silnię. Silnia to działanie matematyczne,
które dla liczby n wyznacza wartość mnożąc przez siebie wszystkie liczby naturalne mniejsze
lub równe n. Symbol oznaczający silnię to wykrzyknik, np.:"""
i = 10
for x in range(1,i+1):
result = 1
for j in range(1,x+1):
result *= j
print(x,result)
def silnia(x):
if x == 0:
return 1
elif x < 0:
return "Nie można wyświetlić silni"
else:
return x * silnia(x-1)
list_noun = ['dog', 'potato', 'meal', 'icecream', 'car']
list_adj = ['dirty', 'big', 'hot', 'colorful', 'fast']
for noun in list_noun:
for adj in list_adj:
print(adj + " " + noun)
print(4,silnia(4))
|
6373856fc1455785061a30e6aae8cf425b410bea | Lithika-Ramesh/Amaatra-Grade-12-Lab-Programs | /Lab programs/lab prog 14.py | 207 | 3.65625 | 4 | #WAP to count the number of words present in text files
#july 22
f=open("Lithika/story.txt","r")
str=f.read()
l=str.split()
c=0
for i in l:
c=c+1
f.close()
print("total number of words =",c) |
0be8d3e48914bc166644992fc683e0ebbbde4609 | sunilkumarvalmiki/data-visualization-web-app-using-streamlit | /app.py | 6,508 | 3.75 | 4 | # importing the packages
import streamlit as st
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use("Agg")
import seaborn as sns
import pandas as pd
import numpy as np
DATA_URL = ("movies_data.csv")
st.markdown("# Self Exploratory Visualization on movies data")
st.markdown("Explore the dataset to know more about movies")
img=Image.open('images/movie_camera.jpg')
st.image(img,width=100)
st.markdown(" **MOVIE** is also called a film, motion picture or moving picture, is a work of visual art used to simulate experiences that communicate ideas, stories, perceptions, feelings, beauty, or atmosphere through the use of moving images. These images are generally accompanied by sound, and more rarely, other sensory stimulations. The word **cinema**, short for cinematography, is often used to refer to filmmaking and the film industry, and to the art form that is the result of it.")
st.markdown("The data presented here are of 3 different genres of movie - **SC-FI, Action, Thriller**")
if st.button("see the Movie genre's"):
# Movie # 1
img=Image.open('images/sc-fi.jpg')
st.image(img,width=700, caption="SC-FI")
# Movie # 2
img=Image.open('images/action.jpg')
st.image(img,width=700, caption="Action")
# Movie # 3
img=Image.open('images/thriller.png')
st.image(img,width=700, caption="Thriller")
# info
img=Image.open('images/all_movies.png')
st.image(img,width=700, caption="info")
# Ballons
st.balloons()
st.info("The dataset contains different aspects like Genre, Rank, Votes, Budget, Profit, IMDB-Rating etc.")
img=Image.open('images/all_movies_2.png')
st.image(img,width=700)
st.sidebar.markdown("## Side Panel")
st.sidebar.markdown("Use this panel to explore the dataset")
@st.cache(persist=True, show_spinner=True)
# Load the Data
def load_data(nrows):
# Parse date and Time
df = pd.read_csv(DATA_URL, nrows = nrows)
lowercase = lambda x:str(x).lower()
df.rename(lowercase, axis='columns',inplace=True)
return df
st.markdown("### Click the button below to explore the dataset through my visualization")
if st.button("Visualization created by Author"):
img=Image.open('images/visualization.png')
st.image(img,width=700, caption="Viz. created by sunil kumar valmiki")
st.markdown("### **Takeaway:** SCI-FI is the most voted & highest rated genre of all 3")
st.markdown("-----")
# Loading data
# df = load_data(100000)
# original_data = df
st.header("Now, Explore Yourself the Movies")
# Create a text element and let the reader know the data is loading.
data_load_state = st.text('Loading the Movie dataset....')
# Load 10,000 rows of data into the dataframe.
df = load_data(100)
# Notify the reader that the data was successfully loaded.
data_load_state.text('Loading Movie dataset....Completed!')
images=Image.open('images/all_movies.png')
st.image(images,width=600)
# Showing the original raw data
if st.checkbox("Show Raw Data", False):
st.subheader('Raw data')
st.write(df)
st.title('Quick Explore')
st.sidebar.subheader(' Quick Explore')
st.markdown("Tick the box on the side panel to explore the dataset.")
if st.sidebar.checkbox('Basic info'):
if st.sidebar.checkbox('Dataset Quick Look'):
st.subheader('Dataset Quick Look:')
st.write(df.head())
if st.sidebar.checkbox("Show Columns"):
st.subheader('Show Columns List')
all_columns = df.columns.to_list()
st.write(all_columns)
# if st.sidebar.checkbox('Column Names'):
# st.subheader('Column Names')
# st.write(df.columns())
if st.sidebar.checkbox('Statistical Description'):
st.subheader('Statistical Data Descripition')
st.write(df.describe())
if st.sidebar.checkbox('Missing Values?'):
st.subheader('Missing values')
st.write(df.isnull().sum())
st.title('Create Own Visualization')
st.markdown("Tick the box on the side panel to create your own Visualization.")
st.sidebar.subheader('Create Own Visualization')
if st.sidebar.checkbox('Graphics'):
if st.sidebar.checkbox('Count Plot'):
st.subheader('Count Plot')
st.set_option('deprecation.showPyplotGlobalUse', False)
st.info("If error, please adjust column name on side panel.")
column_count_plot = st.sidebar.selectbox("Choose a column to plot count. Try Selecting attributes ",df.columns)
hue_opt = st.sidebar.selectbox("Optional categorical variables. Try Selecting attributes ",df.columns.insert(0,None))
# if st.checkbox('Plot Countplot'):
fig = sns.countplot(x=column_count_plot,data=df,hue=hue_opt)
st.pyplot()
# if st.sidebar.checkbox('Heatmap'):
# st.subheader('HeatMap')
# fig = sns.heatmap(df.corr(),annot=True, annot_kws={"size": 9}, linewidths=1.5)
# st.pyplot()
if st.sidebar.checkbox('Boxplot'):
st.subheader('Boxplot')
st.set_option('deprecation.showPyplotGlobalUse', False)
st.info("If error, please adjust column name on side panel.")
column_box_plot_X = st.sidebar.selectbox("X (Choose a column). Try Selecting island:",df.columns.insert(0,None))
column_box_plot_Y = st.sidebar.selectbox("Y (Choose a column - only numerical). Try Selecting Body Mass",df.columns)
hue_box_opt = st.sidebar.selectbox("Optional categorical variables (boxplot hue)",df.columns.insert(0,None))
# if st.checkbox('Plot Boxplot'):
fig = sns.boxplot(x=column_box_plot_X, y=column_box_plot_Y,data=df,palette="Set3")
st.pyplot(fig)
# if st.sidebar.checkbox('Pairplot'):
# st.subheader('Pairplot')
# hue_pp_opt = st.sidebar.selectbox("Optional categorical variables (pairplot hue)",df.columns.insert(0,None))
# st.info("This action may take a while.")
# fig = sns.pairplot(df,palette="coolwarm")
# st.pyplot()
st.markdown(" > Thank you for exploring Movie datasets. This is my first Streamlit work. Feedbacks are highly welcomed.")
st.sidebar.info(" [Source Article](https://github.com/sunilkumarvalmiki/data-visualization-web-app-using-streamlit) | [Twitter Tags](https://twitter.com/SunilkumarValm1/status/1405965400211296257)")
st.sidebar.info("Project is done by [sunil kumar](https://twitter.com/SunilkumarValm1)")
st.sidebar.info("Self Exploratory Visualization on Movies - Brought To you By [Sunil Kumar](https://github.com/sunilkumarvalmiki)")
st.sidebar.text("Built with ❤️ Streamlit") |
a3b2989e85d1c2caf759db21119aa1d4fb89d8b2 | j0hnk1m/leetcode | /easy/70.py | 557 | 3.71875 | 4 | n = 3
# recursive - o(2^n) runtime, o(n) space
def climbStairs(n):
if n == 0 or n == 1:
return 1
return climbStairs(n-1) + climbStairs(n-2)
# recursive w/ memoization - o(n) runtime, o(n) space
def climbStairs(n):
memo = {0: 1, 1: 1}
res = helper(n, memo)
return res
def helper(n, memo):
if n not in memo:
memo[n] = helper(n-1, memo) + helper(n-2, memo)
return memo[n]
# dp - o(n) runtime, o(n) space
dp = {0: 1, 1: 1}
if n >= 2:
for i in range(2, n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
|
49c80bb1c05c364f878748966c48455acda86282 | huang199408/pycharm_test | /test1.py | 400 | 3.71875 | 4 | # coding=utf-8
# 有三个办公室,还有8个老师等待随机分配
import random
# 先创建3个办公室
offices = [[], [], []]
# 假设8个老师是ABCDEFGH
teachers = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
b = 0
while b < len(teachers):
a = random.randint(0, 2)
if len(offices[a]) < 3:
offices[a].append(teachers[b])
b += 1
for temp in offices:
print (temp)
|
895c365884bfd0bca8dc19a484e9a3b1415bc925 | BWatson019/AboutMe | /Test2Pt2.py | 1,707 | 4.125 | 4 | """
Author: <Brittney Watson>
Description: <Create a program that uses concepts from this class (be creative!)>
"""
import random
import Test2Pt2b #importng prime numbers program from another file
WORD = ('cyber', 'security', 'rocks')
word = random.choice(WORD)
correct = word
hint = word[0] + word[(len(word)-1):(len(word))]
letter_guess = ''
word_guess = ''
store_letter = ''
count = 0
limit = 3
print('Welcome to the guess the word game!"')
print('You have 3 attempts at guessing the letters in a word')
print('Start!')
while count < limit:
letter_guess = input('Guess the letter: ')
if letter_guess in word:
print('yes!')
store_letter += letter_guess
count += 1
if letter_guess not in word:
print('Sorry try again!')
count += 1
if count == 2:
print('\n')
hintRequest = input('Would you like a hint? ')
if hintRequest == 'y':
print('\n')
print('HINT: The first and last letter of the word is: ', hint)
if hintRequest == 'n':
print('You are brave!')
print('\n')
print('So far you have guessed ',len(store_letter),'letters correctly.')
print('These letters are: ', store_letter)
word_guess = input('Guess the word: ')
while word_guess:
if word_guess.lower() == correct:
print('Awesome!')
break
elif word_guess.lower() != correct:
print('Sorry! The answer was,', word)
break
print('\n')
#Round two
print('Wait! One more guess before you go :) ')
G1 = input ('Is 7 a prime number?: ')
if G1 == 'yes':
answer = Test2Pt2b.checkIfPrime(13)
print (answer)
else:
print ('False')
print('Thanks for playing the guessing game!')
|
5a216f3631f5906a9db7d37f39957443bead0575 | RhythmShift/Python3-Parsing | /Python3_Project.py | 617 | 3.6875 | 4 | #This is the Python3 project to parse a log file
import urllib.request
import re
import os
from datetime import time
from datetime import date
from datetime import datetime
urllib.request.urlretrieve("https://s3.amazonaws.com/tcmg476/http_access_log", "Amazon_Logfile.txt")
#Opens and reads the text file. Closes afterwards
log = "Amazon_Logfile.txt"
file = open ("Amazon_Logfile.txt", 'r')
lines = file.readlines()
file.close()
#Look for the patterns
countline = 0
for line in lines:
if line != -1:
countline = countline + 1
print("There are " + str(countline) + " lines in this document")
|
344baf58de047ec1e819a9fb18f6725f8430113d | tuhiniris/Advanced-JavaScript-Codes | /Faster Algorithms/_/uniquesort.py | 327 | 3.890625 | 4 | from collections import defaultdict
def def_value():
return False
def uniqSort(arr):
memo = defaultdict(def_value)
result = []
for i in range(len(arr)):
if memo[arr[i]]==False:
result.append(arr[i])
memo[arr[i]]=True
#print(memo)
result.sort()
return(result)
ans = uniqSort([4,2,2,3,2,2,2])
print(ans)
|
746d336c638406229fb5c1ebca48db92d14b1c7b | kazuma-shinomiya/leetcode | /234.palindrome-linked-list.py | 711 | 3.734375 | 4 | #
# @lc app=leetcode id=234 lang=python3
#
# [234] Palindrome Linked List
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
reverse = None
fast = slow = head
while fast and fast.next:
fast = fast.next.next
reverse, reverse.next, slow = slow, reverse, slow.next
if fast: slow = slow.next
while reverse and reverse.val == slow.val:
slow = slow.next
reverse = reverse.next
return not reverse
# @lc code=end
|
7c2788a91794b3aa87fa3f3539742702f04c973f | PolozSabina/Homework | /Homework_16.py | 367 | 3.5 | 4 | v1 = 13
v2 = 18
def have_trains_crashed(v1, v2):
distance_train__a = 4
distance_train__b = 6
time_train__a = distance_train__a / v1
time_train__b = distance_train__b / v2
return time_train__b <= time_train__a
if have_trains_crashed(v1, v2):
print('Поезда столкнутся')
else:
print('Поезда нестолкнутся')
|
f091e5d5251a33333b2d3d490f7705ee08417f89 | JamesDevaney1150/Python-Essentials | /tictactoe.py | 3,752 | 4.46875 | 4 | #TIC TAC TOE
#LAST UPDATED 26/09/2021
##1-Define the board
tttboard=[]
for i in range(3): #a for loop that creates 3 new lists inside the ttboardlist
row = ["-" for i in range(3)] #the print statement then creates a new line after every list
tttboard.append(row) #giving the user a look of a board, the elements in the lists
print("Tic,Tac,Toe:",*tttboard,sep='\n') #can then be used to update the game.
print("Player x goes first.")
#2-Define the Turn
player="x"
for turn in range(10):
r= int(input("Enter row: ")) #User input selecting the row and column from the lists , these integers will be used to select the element in the list
c= int(input("Enter column: "))
if tttboard[r][c] == "-": #comparing the element selected
tttboard[r][c]= player #if element selected is - then change to value of player (either x or o depending on turn)
else:
print("You can't go there")
continue
if turn % 2 == 0: #changes the players turns to either x or o
player="o"
print("\n It is", player, "'s turn")
else:
player="x"
print("\n It is", player, "'s turn")
print(*tttboard,sep='\n')
#3-Define Win
#ACROSS TOP
if tttboard[0][0] == "x" and tttboard[0][1] == "x" and tttboard[0][2] == "x": #Win statements, compares each "row" to see if values
print(*tttboard,"YOU WIN",sep='\n') # all equal x or o. If they are then print win statement.
elif tttboard[0][0] == "o" and tttboard[0][1] == "o" and tttboard[0][2] == "o":
print(*tttboard,"YOU WIN",sep='\n')
#ACROSS MIDDLE
elif tttboard[1][0] == "x" and tttboard[1][1] == "x" and tttboard[1][2] == "x":
print(*tttboard,"YOU WIN",sep='\n')
elif tttboard[1][0] == "o" and tttboard[1][1] == "o" and tttboard[1][2] == "o":
print(*tttboard,"YOU WIN",sep='\n')
#ACROSS BOTTOM
elif tttboard[2][0] == "x" and tttboard[2][1] == "x" and tttboard[2][2] == "x":
print(*tttboard,"YOU WIN",sep='\n')
elif tttboard[2][0] == "o" and tttboard[2][1] == "o" and tttboard[2][2] == "o":
print(*tttboard,"YOU WIN",sep='\n')
#DOWN LEFT SIDE
elif tttboard[0][0] == "x" and tttboard[1][0] == "x" and tttboard[2][0] == "x":
print(*tttboard,"YOU WIN",sep='\n')
elif tttboard[0][0] == "o" and tttboard[1][0] == "o" and tttboard[2][0] == "o":
print(*tttboard,"YOU WIN",sep='\n')
#DOWN MIDDLE SIDE
elif tttboard[0][1] == "x" and tttboard[1][1] == "x" and tttboard[2][1] == "x":
print(*tttboard,"YOU WIN",sep='\n')
elif tttboard[0][1] == "o" and tttboard[1][1] == "o" and tttboard[2][1] == "o":
print(*tttboard,"YOU WIN",sep='\n')
#DOWN RIGHT SIDE
elif tttboard[0][2] == "x" and tttboard[1][2] == "x" and tttboard[2][2] == "x":
print(*tttboard,"YOU WIN",sep='\n')
elif tttboard[0][2] == "o" and tttboard[1][2] == "o" and tttboard[2][2] == "o":
print(*tttboard,"YOU WIN",sep='\n')
#DIAGONAL R2L
elif tttboard[2][0] == "x" and tttboard[1][1] == "x" and tttboard[0][2] == "x":
print(*tttboard,"YOU WIN",sep='\n')
elif tttboard[2][0] == "o" and tttboard[1][1] == "o" and tttboard[0][2] == "o":
print(*tttboard,"YOU WIN",sep='\n')
#DIAGONAL L2R
elif tttboard[2][2] == "x" and tttboard[1][1] == "x" and tttboard[0][0] == "x":
print(*tttboard,"YOU WIN",sep='\n')
elif tttboard[2][2] == "o" and tttboard[1][1] == "o" and tttboard[0][0] == "o":
print(*tttboard,"YOU WIN",sep='\n')
#4-Define TIE
if turn == 9:
print(*tttboard,"ITS A TIE, GAME OVER",sep='\n') #if turn counter gets to 9 print IT'S A TIE, GAME OVER
|
fbdc865b350c314c00504ce735f615267be10db3 | anatulea/codesignal_challenges | /Python/09_Drilling the Lists/62_checkParticipants.py | 1,535 | 3.78125 | 4 | '''
You're organizing murder mystery games for your coworkers, and came up with a lot of ideas for various groups of participants. The ith 0-based game can be played only if there are at least i people registered for it. Game number 0 is a beta that you will try out with your friends, so there's no need for participants.
You're expecting a full house, since a lot of participants signed up already. Not too many, unfortunately: looks like some games can't be played, because too few people registered for them. Given the list of participants, your task is to return the list of games for which too few people signed up.
Example
For participants = [0, 1, 1, 5, 4, 8], the output should be
checkParticipants(participants) = [2].
For the game number 2 (0-based) 2 people are required, but only one person has registered.
'''
def checkParticipants(participants):
return [idx for idx, num in enumerate(participants) if num < idx]
# return filter (lambda i:i>participants[i],range(len(participants)))
participants = [0, 1, 1, 5, 4, 8]
def checkParticipants2(participants):
result = [] # will store the game index of the games that too few people sighnd for
for idx, num in enumerate(participants):
if idx > num: #if the index is grater than the value means not enough people signed
result.append(idx) # add the index to the result array
return result
print(checkParticipants2(participants)) # [2]
participants2 = [3, 3, 3, 3, 3, 3, 3, 3]
print(checkParticipants2(participants2)) # [4, 5, 6, 7]
|
fdc0c83b8447ebec3dca5d601509ed8b8dc11a52 | kimgeonsu/python_19s | /!.py | 107 | 3.75 | 4 | n=int(input("숫자를 입력하세요:"))
for i in range (1, n) :
n= n*i
print(n)
|
782c83abf018cbdef660a0b652c19e847d286a55 | filipnovotny/algos | /dynamic_programming/fib.py | 331 | 3.53125 | 4 | def memoize(f):
mem = dict()
def helper(n):
if n in mem:
return mem[n]
else:
mem[n] = f(n)
return mem[n]
return helper
@memoize
def fib(n):
if n==0:
return 0;
elif n==1:
return 1;
else:
return fib(n-2)+fib(n-1);
print(fib(100)); |
e0d949c721a707691e2425f26bab64fedf69aea5 | YaChenW/Data-Structure | /Graph/PrimMST.py | 8,692 | 3.78125 | 4 | #索引最小堆
class indexMinHeap:
def __init__(self,data=list()):
self.data = data #最小堆
if len(data)>0:
self.index = list(range(len(data)))
self.reIndex = list(range(len(data)))
else:
self.index = list() #保存原index下的元素在最小堆中的位置
self.reIndex = list() #反向索引
self.heapify() #堆初始化
#获得父节点索引
def parent(self,index):
return (index-1)//2
#获得左孩子索引
def leftChilder(self,index):
return index*2+1
#获得右孩子索引
def rightChilder(self,index):
return index*2+2
#index1,index2在堆,索引堆,反向索引堆中位置交换
def swop(self,index1,index2):
self.data[index1],self.data[index2] = self.data[index2],self.data[index1]
self.index[self.reIndex[index1]],self.index[self.reIndex[index2]] = self.index[self.reIndex[index2]],self.index[self.reIndex[index1]]
self.reIndex[index1],self.reIndex[index2] = self.reIndex[index2],self.reIndex[index1]
#比较
def compare(self,a,b):
if a == None:return False
if b == None:return True
return a<b
#上浮
def shiftUp(self,index):
if 0<index<len(self.data):
parentIndex = self.parent(index)
if self.compare(self.data[index],self.data[parentIndex]):
self.swop(index,parentIndex)
self.shiftUp(parentIndex)
#下沉
def shiftDown(self,index):
if 0<=index<len(self.data):
leftChilderIndex = self.leftChilder(index)
rightChilderIndex = self.rightChilder(index)
if rightChilderIndex<len(self.data) and self.compare(self.data[rightChilderIndex], self.data[leftChilderIndex]):
if self.compare(self.data[rightChilderIndex] , self.data[index]):
self.swop(index,rightChilderIndex)
self.shiftDown(rightChilderIndex)
elif leftChilderIndex<len(self.data):
if self.compare(self.data[leftChilderIndex] , self.data[index]):
self.swop(index,leftChilderIndex)
self.shiftDown(leftChilderIndex)
#获得堆中元素的个数
def getSize(self):
return len(self.data)
#堆是否为空
def isEmpty(self):
return len(self.data) == 0
#初始化data为堆
def heapify(self):
if len(self.data)>0:
index = len(self.data)
while index>=0:
self.shiftDown(index)
index-=1
#查看最小的元素
def finMin(self):
return None if self.isEmpty else self.data[0]
#查看最小元素的索引
def findMinIndex(self):
return None if self.isEmpty() else self.reIndex[0]
#取出最小元素索引
def extractMinIndex(self):
ret = self.findMinIndex()
self.extractMin()
return ret
#取出最小的元素
def extractMin(self):
if self.isEmpty():return
ret = self.data[0]
self.data[0] = None
self.swop(0,len(self.data)-1)
self.shiftDown(0)
return ret
#入堆
def add(self,e):
index = len(self.data)
self.index.append(index)
self.reIndex.append(index)
self.data.append(e)
self.shiftUp(index)
#获得索引为 index 的元素
def get(self,index):
return None if self.isEmpty() else self.data[self.index[index]]
#改变 索引为 index 的元素的值
def set(self,index,v):
oIndex = self.index[index]
self.data[oIndex] = v
self.shiftUp(oIndex)
self.shiftDown(oIndex)
#带权稀疏图
#Lazy Prim
class SparseWeightedGraph:
#边
class edge:
def __init__(self,a,b,w):
if a==b:
raise Exception('a==b')
self.a,self.b = a,b
self.weight = w
#返回a节点
def A(self):
return self.a
#返回b节点
def B(self):
return self.b
#返回权值
def W(self):
return self.weight
#给定一个节点返回另一个节点
def other(self,x):
return self.a if x==self.b else self.b
#重写比较
def __lt__(self,other):
if other in (None,-1):return True
return self.weight<other if type(other) in (int,float) else self.weight<other.weight
def __gt__(self,other):
if other in (None,-1):return False
return self.weight>other if type(other) in (int,float) else self.weight>other.weight
def __le__(self,other):
if other in (None,-1):return True
return self.weight<=other if type(other) in (int,float) else self.weight<=other.weight
def __ge__(self,other):
if other in (None,-1):return False
return self.weight>=other if type(other) in (int,float) else self.weight>=other.weight
def __eq__(self,other):
if other in (None,-1):return False
return self.a==other or self.b==other if type(other) is int else self.weight==other.weight
def __ne__(self,other):
if other in (None,-1):return True
return self.a!=other and self.b!=other if type(other) is int else self.weight!=other.weight
#带权稀疏图的构造函数
def __init__(self,p):
if p < 0 :raise Exception('error p<0')
self.p = p #点
self.e = 0 #边
self.g = [ list() for i in range(p) ] #保存图的邻接表
#获得点的个数
def P(self):
return self.P
#获得边的条数
def E(self):
return self.e
#根据 p 获得边
def getEdge(self,p):
return self.g[p] if 0<= p < self.p else None
#添加边
def addEdge(self,s,e,w):
if 0<=s<self.p and 0<=e<self.p:
if e not in self.g[s]:
edge = self.edge(s,e,w)
self.g[s].append(edge)
self.g[e].append(edge)
self.e+=1
def show(self):
for i in range(len(self.g)):
print(i,end=" = ")
for j in self.g[i]:
print('{a:%r,b:%r,w:%r}'%(j.A(),j.B(),j.W()),end = ', ')
print()
#最小生成树 LazyPrim
class LazyPrimMST:
def __init__(self,groph):
self.groph = groph #获取图
self.pq = indexMinHeap()#最小索引堆辅助取出最小边
self.visited = set() #记录访问过的节点
self.mst = list() #保存最小边
self.creatMST()
def creatMST(self):
print('MST')
p=0 #起始点为 p
for i in self.groph[p]: #访问起始点, 遍历所有边
self.pq.add(i)
self.visited.add(p) #起始点已经访问过
while len(self.mst) < len(self.groph)-1:
edge = self.pq.extractMin() #获取最小的横切边
if edge.A() in self.visited and edge.B() in self.visited:continue
self.mst.append(edge) #保存横切边
np = edge.other(p) #边的另一个节点 保存到np
for i in self.groph[np]: #访问np点, 遍历所有边
if i.other(np) != p:
self.pq.add(i)
self.visited.add(np) #np已经被访问过了
p = np
#最小生成树 Prim
class PrimMST:
def __init__(self,groph): #获取图
self.groph = groph
self.mst = list() #保存所有横切边
self.imh = indexMinHeap([ -1 if i!=0 else None for i in range(len(groph)) ]) #辅助用最小索引堆
p = 0 #初始点为p
for i in self.groph[p]:
self.imh.set(i.other(p),i)
while len(self.mst)+1<len(self.groph): #当所有点都被访问过则退出循环
edge = self.imh.extractMin() #取出最小边
self.mst.append(edge)
p = edge.other(p) #将要访问的点 p
for i in self.groph[p]: #访问p中所有点
otherP = i.other(p) #边的另一个点
edge = self.imh.data[self.imh.index[otherP]] #访问的边
if edge == -1 or i<edge and edge != None: #如果当前点没有访问过, 或者当前边的权值大于访问边的权值
self.imh.set(otherP,i) #将访问边放进 imh
def show(self):
for i in self.mst:
print('{a:%r,b:%r,w:%r}'%(i.A(),i.B(),i.W()),end = ', ')
|
25018d2b46770d64947c8aa5979b0d61eba40db4 | anurag1212/code-catalog | /code/ds-algo-python/chapter6/R-6.6.py | 405 | 3.65625 | 4 | def bracketmatch(s,i=0,opens="[({",closes="])}"):
if i>=len(s):
return True
if s[i] in closes:
return i
if s[i] in opens:
next = bracketmatch(s,i+1)
if type(next) is bool:
return False
if opens.find(s[i]) == closes.find(s[next]):
return bracketmatch(s,next+1)
else:
return False
print(bracketmatch("(()))"))
|
01c027153bca83297a74f0bf56f512dd3c679de5 | varshajoshi36/practice | /leetcode/python/easy/ExcelSheetNumber.py | 570 | 3.78125 | 4 | '''
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
'''
import string
def titleToNumber(s):
"""
:type s: str
:rtype: int
"""
alphabets = list(string.ascii_uppercase)
multiplier = 1
number = 0
for i in range(len(s) - 1, -1, -1):
number += multiplier * (alphabets.index(s[i]) + 1)
multiplier *= 26
return number
s = 'Z'
print titleToNumber(s)
|
0d9749f2ecc9c5e22e3069ac1e7b82e33218a431 | irvanardynsyh/Lab_1-2 | /Lab 1.py | 1,152 | 3.90625 | 4 | # Penggunaan End
print("PENGGUNAAN END")
print('A', end='')
print('B', end='')
print('C', end='')
print()
print('X')
print('y')
print('Z')
print("\n")
# Penggunaan Separator
print("PENGGUNAAN SEPARATOR")
w, x, y, z = 10, 15, 20, 25
print(w, x, y, z)
print(w, x, y, z, sep=',')
print(w, x, y, z, sep='')
print(w, x, y, z, sep=':')
print(w, x, y, z, sep='-----')
print("\n")
# String Format
print("STRING SEBELUM DI FORMAT")
print(0,10**0)
print(1,10**1)
print(2,10**2)
print(3,10**3)
print(4,10**4)
print(5,10**5)
print(6,10**6)
print(7,10**7)
print(8,10**8)
print(9,10**9)
print(10,10**10)
print("\n")
# String Format
print("STRING SETELAH DI FORMAT")
print('{0:>3} {1:>16}'.format(0,10**0))
print('{0:>3} {1:>16}'.format(1,10**1))
print('{0:>3} {1:>16}'.format(2,10**2))
print('{0:>3} {1:>16}'.format(3,10**3))
print('{0:>3} {1:>16}'.format(4,10**4))
print('{0:>3} {1:>16}'.format(5,10**5))
print('{0:>3} {1:>16}'.format(6,10**6))
print('{0:>3} {1:>16}'.format(7,10**7))
print('{0:>3} {1:>16}'.format(8,10**8))
print('{0:>3} {1:>16}'.format(9,10**9))
print('{0:>3} {1:>16}'.format(10,10**10))
|
85c560ccf2850185742b5a602632268fa6bc07f7 | tillyoswellwheeler/python-learning | /hackerrank_challenges/division.py | 686 | 4.125 | 4 | #----------------------------------------------
# HackerRank Challenges -- Division
#----------------------------------------------
# ------------------------------------
# Task
# Read two integers and print two lines. The first line should contain integer division, a//b .
# The second line should contain float division, a/b .
#
# You don't need to perform any rounding or formatting operations.
# INPUT TYPE
#--- The first line contains the first integer, a . The second line contains the second integer, b .
def calc_division(a, b):
integer_div = a // b
float_div = a / b
print(integer_div)
print(float_div)
return integer_div, float_div
calc_division(a,b) |
d68fe861a80437aa7df982272ee1d513723f0492 | yurimalheiros/IP-2019-2 | /lista1/roberta/questao4.py | 499 | 3.921875 | 4 | # Função Definir alarme
# Autor Roberta de Lima
from datetime import datetime, timedelta
# Função Estática
print("ALARME")
dt = datetime(2019,11,3, 14)
hrAlarme = dt + timedelta(hours=51)
print("Sendo 14hrs, daqui a 51hrs o alarme tocará às ",hrAlarme.strftime("%H:%M "))
# Função dinâmica
#tempo = int(input("Digite o tempo para alarme(horas): "))
#hj = datetime.now()
#hrAlarme = hj + timedelta(hours=tempo)
#print("Hora do alarme: ", hrAlarme.strftime("%H:%M %d/%m/%Y"))
|
e4b2ac61ad90e2442bf978b9cb88e25ed60107df | davidalejandrolazopampa/Mundial | /10.py | 163 | 3.9375 | 4 | f=int(input("ingrese F°: "))
c=((f-32)*5)/9
if 46>f and 29<f:
print(c)
elseif f==46:
print("Limite Inferior")
else :
print("Limite Superior")
|
8b98a523b681beca19d2dc28977bece86a23ab93 | carterjin/digit-challenge | /PNG_digit_question.py | 2,767 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 11:34:04 2020
@author: Kami
"""
import itertools
testdigits = range(1,10)
# Shunting-yard_algorithm
##https://en.wikipedia.org/wiki/Shunting-yard_algorithm
def op_prec(char):
if char == '*' or char == '/':
return 3
else:
return 2
def str_to_stack(exp):
output = ''
oper_stack = ''
q_num = 0
for char in exp:
if char.isdigit() or char == '?':
output += char
if char == '?': q_num += 1
elif char in ['+','-','*','/']:
while(oper_stack and oper_stack[0] != '(' and
op_prec(oper_stack[0]) >= op_prec(char)):
output += oper_stack[0]
oper_stack = oper_stack[1:]
oper_stack = char + oper_stack
elif char == '(':
oper_stack = char + oper_stack
elif char == ')':
while(oper_stack[0] != '('):
output += oper_stack[0]
oper_stack = oper_stack[1:]
if oper_stack and oper_stack[0] == '(':
oper_stack = oper_stack[1:]
return (output + oper_stack, q_num)
def eval(stack, test):
nums = test.copy()
ans = []
for char in stack:
if char.isdigit():
ans.append(int(char))
elif char == '?':
ans.append(nums.pop(0))
elif char in ['+','-','*','/']:
b = ans.pop()
a = ans.pop()
if char == '+': c = a + b
elif char == '-': c = a - b
elif char == '*': c = a * b
elif char == '/': c = a / b
ans.append(c)
return ans[0]
def print_ans(exp, nums):
temp_exp = exp
while nums:
temp_exp = temp_exp.replace('?',str(nums.pop(0)), 1)
print(temp_exp)
print('PNG digit question solver\n ------Designed by Haoming Jin------')
print('All unknown numbers are 1-9 and don\'t repeat, allowed operators are +-*/()')
print('Acceptable formats examples: ?+?=9\t? + 1 = 9\t(1+?)/4 = 1.5\t 2+?*4 = 14\t?*?*?+?=295')
while (True):
exp = input('Enter the equation, type unknown number as "?", type "exit" to quit:\n')
if exp == 'exit': break
exp = exp.replace(' ','')
try:
(ques,ans) = exp.split('=')
ans = float(ans)
(stack,q_num) = str_to_stack(ques)
is_found = False
print('Answer:')
for test in itertools.permutations(testdigits, r = q_num):
test = list(test)
if eval(stack, test) == ans:
is_found = True
print_ans(exp, test)
if not is_found:
print('Not Found')
except:
print('Input Error') |
8f17255ddd95781518148019efc8d0ba4bb9a6c3 | ebrisum/Basictrack_2021_1a | /Week 3/excercise_3_4_4_6.py | 467 | 3.984375 | 4 | numbers = [83, 75, 74.9, 70, 69.9, 65, 60, 59.9, 55, 50,
49.9, 45, 44.9, 40, 39.9, 2, 0]
for grade in numbers:
if grade>=75:
print(grade,":First")
if 70<=grade<75:
print(grade,":Upper second")
if 60<=grade<70:
print(grade,":Second")
if 50<=grade<60:
print(grade,":Third")
if 45<=grade<50:
print(grade,":F1 Supp")
if 40<=grade<45:
print(grade,":F2")
if grade<40:
print(grade,":F3")
|
a7890ad585b4345e0741613923f9d9761b2c6dc6 | zyga/arrowhead | /xkcd518.py | 3,193 | 3.890625 | 4 | #!/usr/bin/env python3
from arrowhead import Flow, step, arrow, main
def ask(prompt):
answer = None
while answer not in ('yes', 'no'):
answer = input(prompt + ' ')
return answer
class XKCD518(Flow):
"""
https://xkcd.com/518/
"""
@step(initial=True, level=1)
@arrow('do_you_understand_flowcharts')
def start(step):
"""
START
"""
print(step.Meta.label)
# ---------------
@step(level=2)
@arrow(to='good', value='yes')
@arrow(to='okay_you_see_the_line_labeled_yes', value='no')
def do_you_understand_flowcharts(step):
"""
Do you understand flowcharts?
"""
return ask(step.Meta.label)
@step(level=2)
@arrow(to='lets_go_drink')
def good(step):
print(step.Meta.label)
# ---------------
@step(level=3)
@arrow(to='hey_I_should_try_installing_freebsd')
def lets_go_drink(step):
"""
Let's go drink.
"""
print(step.Meta.label)
@step(accepting=True, level=3)
def hey_I_should_try_installing_freebsd(step):
"""
Hey, I should try installing freeBSD!
"""
print(step.Meta.label)
# ---------------
@step(level=4)
@arrow(to='and_you_can_see_ones_labeled_no', value='yes')
@arrow(to='but_you_see_the_ones_labeled_no', value='no')
def okay_you_see_the_line_labeled_yes(step):
"""
Okay. You see the line labeled 'yes'?
"""
return ask(step.Meta.label)
@step(level=4)
@arrow(to='good', value='yes')
@arrow(to='but_you_just_followed_them_twice', value='no')
def and_you_can_see_ones_labeled_no(step):
"""
...and you can see the ones labeled 'no'?
"""
return ask(step.Meta.label)
# ---------------
@step(level=5)
@arrow(to='wait_what', value='yes')
@arrow(to='listen', value='no')
def but_you_see_the_ones_labeled_no(step):
"""
But you see the ones labeled "no"?
"""
return ask(step.Meta.label)
# ---------------
@step(accepting=True, level=5)
def wait_what(step):
"""
Wait, what!
"""
print(step.Meta.label)
# ---------------
@step(level=6)
@arrow(to='I_hate_you')
def listen(step):
"""
Listen
"""
print(step.Meta.label)
@step(accepting=True, level=6)
def I_hate_you(step):
"""
I hate you
"""
print(step.Meta.label)
# ---------------
@step(level=5)
@arrow(to='that_wasnt_a_question', value='yes')
@arrow(to='that_wasnt_a_question', value='no')
def but_you_just_followed_them_twice(step):
"""
But you just followed them twice!
"""
return ask(step.Meta.label)
@step(level=5)
@arrow(to='screw_it')
def that_wasnt_a_question(step):
"""
(That wasn't a question)
"""
print(step.Meta.label)
@step(level=4)
@arrow(to='lets_go_drink')
def screw_it(step):
"""
Screw it.
"""
print(step.Meta.label)
if __name__ == '__main__':
main(XKCD518)
|
a99032c42eec0b666fa080cf77d9941763b974c4 | nektarios94/Palindrome-exercise-written-in-Python | /Python_code/main.py | 441 | 4.03125 | 4 | from palindrome import palindrome
list = []
while (True):
string = input("Please type a string of characters (press 'e' to exit): ")
if string != 'e' and string != 'E':
list.append(string)
if palindrome(string) and (len(string) > 1): # excluding single characters
print ('\'%s\' is a palindrome' %(string))
else:
print('\'%s\' is not a palindrome' %(string))
else:
break
|
efd7e7dac25515a879b03a2ccb10e43cc18b2136 | aschiedermeier/Programming-Essentials-in-Python | /Module_6/6.1.3.6.existingVariables.py | 2,313 | 4.375 | 4 | # 6.1.3.6 OOP: Properties
# Checking an attribute's existence
# in Python you may not expect that all objects of the same class have the same sets of properties.
class ExampleClass:
def __init__(self, val):
if val % 2 != 0:
self.a = 1
else:
self.b = 1
exampleObject = ExampleClass(1) # this object only has one attribute: a
print(exampleObject.a)
# print(exampleObject.b) #AttributeError: 'ExampleClass' object has no attribute 'b'
# 6.1.3.7 OOP: Properties
# Checking an attribute's existence: continued
# The try-except instruction gives you the chance to avoid issues with non-existent properties.
class ExampleClass:
def __init__(self, val):
if val % 2 != 0:
self.a = 1
else:
self.b = 1
exampleObject = ExampleClass(1)
print(exampleObject.a)
try:
print(exampleObject.b)
except AttributeError:
pass
# hasattr function
# Python provides a function which is able to safely check if any object/class contains a specified property.
# The function is named hasattr, and expects two arguments to be passed to it:
# the class or the object being checked;
# the name of the property whose existence has to be reported (note: it has to be a string containing the attribute name, not the name alone)
class ExampleClass:
def __init__(self, val):
if val % 2 != 0:
self.a = 1
else:
self.b = 1
exampleObject = ExampleClass(1)
print(exampleObject.a)
if hasattr(exampleObject, 'b'):
print(exampleObject.b)
# 6.1.3.8 OOP: Properties
# hasattr() function can operate on classes, too.
class ExampleClass:
attr = 1
print(hasattr(ExampleClass, 'attr'))
print(hasattr(ExampleClass, 'prop'))
# hasattr() function can operate on classes, too.
class ExampleClass:
a = 1
def __init__(self):
self.b = 2
exampleObject = ExampleClass()
print(hasattr(exampleObject, 'b')) #True: b is in object as variable
print(hasattr(exampleObject, 'a')) #True: a is in object in dictionary
print(exampleObject.a) # 1
print(exampleObject.b) # 2
print(exampleObject.a, exampleObject.__dict__) # a is herited class variable, in dictionary only b
print(hasattr(ExampleClass, 'b')) #False
print(hasattr(ExampleClass, 'a')) #True
print(ExampleClass.__dict__) # has only a
|
a19aaf4285dcc0804b2066d9dd86a6e2db02cdb1 | CosmoAndrade/PythonExercicios2020 | /65.py | 3,885 | 3.828125 | 4 | '''
Crie uma Fazenda de Bichinhos instanciando vários objetos bichinho e mantendo o controle deles através de uma lista. Imite o funcionamento do programa básico, mas ao invés de exigir que o usuário tome conta de um único bichinho, exija que ele tome conta da fazenda inteira. Cada opção do menu deveria permitir que o usuário executasse uma ação para todos os bichinhos (alimentar todos os bichinhos, brincar com todos os bichinhos, ou ouvir a todos os bichinhos). Para tornar o programa mais interessante, dê para cada bichinho um nivel inicial aleatório de fome e tédio.
'''
import random
class Tamagushi():
def __init__(self, nome, fome = 0, saude = 0, idade = 0):
self.__nome = nome
self.__fome = fome
self.__saude = saude
self.__idade = idade
@property
def nome(self):
return self.__nome
@property
def fome(self):
return self.__fome
@property
def saude(self):
return self.__saude
@property
def idade(self):
return self.__idade
@nome.setter
def nome(self, novoNome):
if type(novoNome) == str:
self.__nome = novoNome
@fome.setter
def fome(self, novaFome):
if type(novaFome) == int:
self.__fome = novaFome
@saude.setter
def saude(self, novaSaude):
if type(novaSaude) == int:
self.__saude = novaSaude
@idade.setter
def idade(self, novaIdade):
if type(novaIdade) == int:
self.__idade = novaIdade
@property
def alimentar(self):
return ''
@alimentar.setter
def alimentar(self, alimento):
if type(alimento) == str:
alimento.lower()
if alimento == 'banana':
self.__fome -= 10
elif alimento == 'castanha':
self.__fome -= 5
elif alimento == 'rosquinha':
self.__fome -= 15
else:
self.__fome -= 3
if self.__fome < 0:
self.__fome = 0
@property
def brincar(self):
return ''
@brincar.setter
def brincar(self, tempo):
if type(tempo) == int:
self.__saude += tempo
if self.__saude > 100:
self.__saude = 100
@property
def humor(self):
return (100 - self.__fome + self.__saude)/2
def __str__(self):
return f'\nnome : {self.nome}\nfome : {self.fome}\nsaude : {self.saude}\nidade : {self.idade}\nhumor : {self.humor}'
fazenda = []
qtBichinhos = int(input('Digite quantos bichinhos você quer na fazenda: '))
for i in range(0, qtBichinhos):
fazenda.insert(i,Tamagushi(input(f'Digite o nome do {i+1}º bichinho: ')))
fazenda[i].fome = random.randint(0,100)
fazenda[i].saude = random.randint(0,100)
fazenda[i].idade = random.randint(0,100)
def exibirBichos():
for bicho in fazenda:
print(bicho)
def alimentarBichos():
alimento = input('Digite o alimento a ser dado aos bichos: ').lower()
for bicho in fazenda:
bicho.alimentar = alimento
def brincarComBichos():
tempo = int(input('Digite por quanto tempo vai brincar com os bichos: '))
for bicho in fazenda:
bicho.brincar = tempo
def menu():
escolha = ''
while escolha != 's':
print('\nDigite:')
print('A para alimentar os bichos.')
print('B para brincar com os bichos.')
print('E para exibir os dados dos bichos.')
print('S para sair.')
escolha = input('Sua escolha é: ').lower()
if escolha == 'a':
alimentarBichos()
elif escolha == 'b':
brincarComBichos()
elif escolha == 'e':
exibirBichos()
elif escolha == 's':
pass
else:
print('\nEscolha inválida!\n')
menu() |
1f7ba5b1b98bc5778ef3063d7b64d212420f2f0b | kinetickansra/algorithms-in-C-Cplusplus-Java-Python-JavaScript | /Algorithms/Recursion/Python/GenerateParenthesis.py | 304 | 3.59375 | 4 | def bracket(n, asf, open, close):
if n == 0:
if open == close:
print(asf)
return
if open > close:
bracket(n - 1, asf + ")", open, close + 1)
# if close
bracket(n - 1, asf + "(", open + 1, close)
n = int(input())
bracket(2 * n, "", 0, 0)
|
390fa0ed3d42e6ccc00c10ee0077e45e71a3561c | nishathapa/Inception-Machine | /Handling.py | 416 | 3.5 | 4 | try:
# p=5/0
p = 78
j= 98
r=p/0
f = open("ac.txt")
for line in f:
print(line)
except FileNotFoundError as e:
print(e.filename)
except Exception as e:
print(e)
except ZeroDivisionError as e:
print(e)
# except FileNotFoundError:
# print("printed error")
# except ZeroDivisionError:
# print("Divided by zero")
#
# # i = 0/0
# we added here just for fun
|
2f2a50f5ac17e986eb8878d6e7d6ad8184b9b8d6 | vicky-xiaoli/html | /python1/py0911.py | 508 | 3.859375 | 4 |
# 11有一个列表['a','b','c','a','e','a'], 使用for循环统计a出现的次数,并删除其中的所有a元素
# lis = ['a','b','c','a','e','a',"a","a"]
# count = 0
# for i in lis: #循环列表
# if i == 'a':
# count = count + 1 #当i是a的时候,每循环一次加一次
# print(count) #循环结束后,打印最后次数
# for j in range(count): #按计数引循环a
# lis.remove("a") #每次循环都删除a,直到循环结束
# print(lis)
#
|
faf19d0133e060b5ee5a5ec77abed36c9d117505 | shonshch/compilationHw3 | /CompilationTests/hw3/make_submission.py | 813 | 3.671875 | 4 | #!/usr/bin/python3
import os
from zipfile import ZipFile
import glob
import sys
if len(sys.argv) == 3:
tz1 = sys.argv[1]
tz2 = sys.argv[2]
else:
tz1 = input("Enter the first Teudat Zehut: ")
tz2 = input("Enter the second Teudat Zehut: ")
code_files = glob.glob('*.c') + glob.glob('*.cpp') + glob.glob('*.hpp') + ['parser.ypp', 'scanner.lex']
removes = glob.glob('parser.tab.*pp') + glob.glob('lex.yy.c')
for remove in removes:
code_files.remove(remove)
zipname = f'{tz1}-{tz2}.zip'
if os.path.exists(zipname):
os.remove(zipname)
print('Cleaned up old submission zip')
zf = ZipFile(zipname, mode='w')
print('Filename is:', zipname)
print('Including:')
for fn in code_files:
print(f'- {fn}')
zf.write(fn)
print('Prepared submission file')
|
bc2fa3a03d6a42b43501c4cd440dfec17c746ec8 | smrsassa/Studying-python | /curso/PY2/while_true/ex4.py | 652 | 3.75 | 4 | #exercicio 69
homems = mulheresvinte = dezoito = 0
while True:
print ('-'*60)
print ('Cadastre uma pessoa')
print ('-'*60)
idade = int(input('Qual sua idade: '))
sexo = str(input('Qual seu sexo: [M/F] '))
print ('-'*60)
if sexo in 'Mm':
homems += 1
elif sexo in 'Ff' and idade < 20:
mulheresvinte += 1
if idade > 18:
dezoito += 1
cont = str(input('Quer continuar? [S/N]'))
if cont in 'Nn':
break
print (f'Tem {homems} homems cadastrados')
print (f'Tem {mulheresvinte} mulheres com menos de 20 anos cadastradas')
print (f'Tem {dezoito} pessoas com mais de 18 anos cadastrados') |
296851fe24b6c08ff92ad0c61ae8321e2edb0a5f | jrcamelo/IF968-Projetos-e-Listas | /Atividades/Lista8/PythonDB.py | 6,099 | 3.6875 | 4 | # João Rafael
def menu():
dados = []
while not dados:
limparTela()
print("MENU PRINCIPAL DO BANCO DE DADOS",
"\nEscolha a operação que deseja realizar:",
"\n1. Registrar Pessoa",
"\n2. Procurar Pessoa",
"\n3. Alterar Registro",
"\n4. Deletar Registro",
"\n5. Finalizar")
switch = {1: "create",
2: "read",
3: "update",
4: "delete",
5: "sair"}
opcao = ""
while not opcao:
opcaoinput = input("\nOperação: ")
if opcaoinput.isdigit():
if int(opcaoinput) <= len(switch) and int(opcaoinput) > 0:
opcao = switch[int(opcaoinput)]
if opcao == "sair":
return ""
limparTela()
dados = formatoEntrada(opcao)
resultado = (crud(opcao, dados))
if resultado:
input("\n" + resultado)
return opcao
def criarArquivo(caminho):
f = open(caminho, "a+")
f.seek(0)
if not f.readlines():
f.write("Nome Sobrenome Idade Sexo\n")
f.close()
def lerArquivo(f):
lista = []
linhas = f.readlines()
for i in range(1, len(linhas)):
linha = limparTexto(linhas[i])
if linha:
lista.append(linha.split(" "))
return lista
def escreverArquivo(linhas, caminho, operacao):
criarArquivo(caminho)
f = open(caminho, operacao)
for i in range(len(linhas)):
f.write("\n")
for j in range(len(linhas[i])):
f.write(linhas[i][j] + " ")
f.write("\n")
f.close
def alterarArquivo(linhas, caminho):
criarArquivo(caminho + "temp")
escreverArquivo(linhas, caminho + "temp", "a+")
from os import rename, remove
remove(caminho)
rename(caminho + "temp", caminho)
def formatoEntrada(operacao):
textoOperacao = "registrar uma pessoa"
if operacao == "delete":
textoOperacao = "deletar um registro"
textoPrint = "Para " + textoOperacao + ", insira os dados da forma abaixo:"
textoInput = "NOME SOBRENOME IDADE (M ou F)\n"
updateInput = ""
if operacao == "sair":
return "sair"
elif operacao == "read":
readInput = input("Para buscar um registro, digite o Nome e/ou Sobrenome da pessoa\n")
return limparTexto(readInput)
elif operacao == "update":
print("Para editar um registro, digite os dados que deseja editar da forma abaixo:")
updateInput = tratarDados(receberInput(textoInput))
if updateInput:
textoPrint = "\nAgora digite os dados novos no mesmo formato"
else:
textoPrint = ""
dados = ""
if textoPrint:
print(textoPrint)
dados = tratarDados(receberInput(textoInput))
if updateInput and dados:
return [updateInput, dados]
else:
return dados
def tratarDados(lista):
lista = capitalizarLista(lista)
if len(lista) == 4 and lista[2].isdigit() and len(lista[3]) == 1:
return lista
else:
input("\nFORMATO INVÁLIDO!")
def receberInput(inputTexto):
texto = input(inputTexto)
texto = texto.split(" ")
for i in range(len(texto)):
texto[i] = limparTexto(texto[i])
return texto
def crud(operacao, dados):
switch = {"create": create,
"read": read,
"update": update,
"delete": delete}
resultado = switch[operacao](dados)
return resultado
def create(dados):
linha = ""
for i in range(len(dados)):
linha += dados[i] + " "
linha = linha[0:-1]
escreverArquivo([[linha]], caminho, "a+")
input("\n" + dados[0] + " " + dados[1] + " adicionado ao banco de dados!")
def read(dados):
banco = lerArquivo(open(caminho, "r"))
pessoa = ""
if banco:
for i in range(len(banco)):
for j in range(2):
if dados.upper() == banco[i][j].upper():
for k in range(len(banco[i])):
pessoa += limparTexto(banco[i][k]) + " "
pessoa = pessoa[0:-1] + "\n"
if pessoa:
return pessoa
else:
input("\n" + dados + " não foi encontrado!")
def update(dados):
banco = lerArquivo(open(caminho, "r"))
dadosAntes = dados[0]
dadosDepois = dados[1]
alterado = ""
if banco:
i = 0
while i < len(banco):
if banco[i] == dados[0]:
alterado = banco[i] = dados[1]
i += 1
if alterado:
alterarArquivo(banco, caminho)
input("\n" + dados[0][0] + " " + dados[0][1] +
" alterado para " + dados[1][0] + " " + dados[1][1])
else:
input("\n" + dados[0][0] + " " + dados[0][1] + " não encontrado!")
def delete(dados):
banco = lerArquivo(open(caminho, "r"))
deletado = ""
if banco:
i = 0
while i < len(banco):
if banco[i] == dados:
deletado = banco.pop(i)
i += 1
if deletado:
alterarArquivo(banco, caminho)
input("\n" + dados[0] + " " + dados[1] + " deletado do banco de dados!")
def limparTela():
print("\n"*50)
def limparTexto(texto):
texto = texto.replace("\n", "")
texto = texto.strip()
return texto
def capitalizarLista(lista):
for i in range(len(lista)):
if len(lista[i]) > 1:
lista[i] = lista[i][0].upper() + lista[i][1:].lower()
else:
lista[i] = lista[i].upper()
return lista
def simNao():
Sims = ["S", "SI", "SIM", "Y", "YE", "YES", "1"]
Naos = ["N", "NA", "NAO", "NÃ", "NÃO", "NO", "0"]
while True:
escolha = input(" (S)im ou (N)ão: ").upper()
if escolha in Sims:
return True
elif escolha in Naos:
return False
caminho = "data.txt"
criarArquivo(caminho)
while menu():
pass
|
6a6263a9f7079fd401cf0fa6862e1dceaff79d74 | amullenger/PyBank_Exercise | /main3.py | 3,025 | 3.875 | 4 | import os
import csv
my_file = os.path.join('', 'budget_data.csv')
"""Create lists for seperately storing all months, profit/loss figures, calculated differences in P/L,
and a master list of lists to store all data with P/L converted to float type"""
month_list = []
P_L_List = []
P_L_Difference = []
master_list = []
"""Open csv file and create reader object so we can pull data into lists. Iterate through reader to append month data, P/L data,
and a master set of data into respective lists. Convert P/L data to float type where necessary."""
with open (my_file, "r", newline="") as CsvFile:
csv_reader = csv.reader(CsvFile)
next(csv_reader)
for row in csv_reader:
month_list.append(row[0])
P_L_List.append(float(row[1]))
master_list.append([row[0], float(row[1])])
#Calculate toal months by finding size of the months list we created
month_count = len(month_list)
#Calculate total P/L by adding up all elements of P/L list.
P_L_Sum = sum(P_L_List)
"""Iterate through P/L list using indexes. The differences are calculated by subtracting the
current list element from the next list element. Append these values to our list for storing differences.
Find avg difference by adding all elements of differences list and dividing by the size of the list."""
for i in range(len(P_L_List) -1):
P_L_Difference.append(P_L_List[i+1] - P_L_List[i])
P_L_Avg_Diff = sum(P_L_Difference)/len(P_L_Difference)
"""Create tracker variables for greatest increase and month of greatest increase.
Iterate through master list and take difference between next P/L figure and current P/L figure.
If this value is greater than the value currently stored in our greatest increase tracker,
set current P/L value to greatest and pull the month of the next element, since P/L changes will be measured in the second month."""
greatest_increase = 0
greatest_inc_month = ""
for i in range(len(master_list)-1):
if ( master_list[i+1][1] - master_list[i][1] ) > greatest_increase:
greatest_increase = master_list[i+1][1] - master_list[i][1]
greatest_inc_month = master_list[i+1][0]
"""Follow process similar to above calculation of greatest increase to get greatest decrease.
Instead of checking if P/L difference is greater than the current value of our gratest decrease tracker,
we want to check if it is less than this value"""
greatest_decrease = 0
greatest_dec_month = ""
for i in range(len(master_list)-1):
if ( master_list[i+1][1] - master_list[i][1] ) < greatest_decrease:
greatest_decrease = master_list[i+1][1] - master_list[i][1]
greatest_dec_month = master_list[i+1][0]
#Print formatted text showing desired output figures
print(f"""\
Financial Analysis
-------------------------
Total Months: {month_count}
Total: {P_L_Sum}
Average Change: {P_L_Avg_Diff}
Greatest Increase in Profits: {greatest_inc_month} ({greatest_increase})
Greatest Decrease in Profits: {greatest_dec_month} ({greatest_decrease})
""")
|
ebd80b7a1750ed164559c89537b5ac64fbf01bd5 | Lianyihwei/RobbiLian | /Lcc/pythonrace/PYA710.py | 249 | 3.609375 | 4 | #TODO
from tabnanny import check
dict = {}
while True:
key = input("Key: ")
if key == "end":
break
value = input("Value: ")
dict[key] = value
search_key = input("Search key: ")
print(search_key in dict.keys()) |
5c121c3cb65d337966e5a5bb07d28b3fe8d636cf | lucky-star-king/javaInternet | /作业6/test.py | 372 | 3.640625 | 4 | # def printname(name="mmi"):
# print(name)
# # printname()
# def rever(a,b):
# a,b=b,a
# a,b=1,2
# rever(1,2)
# print(a,b)
# def summ(*args):
# m=0
# for x in args:
# m+=x
# print(m)
# li=[1,2,4,5,6,23,4]
# summ(*li)
def fi(n):
if n==1:
return 0
return 1 if (n==2 or n==3) else fi(n-1)+fi(n-2)
print(fi(6))
|
d5d3f724b78cdc2c98630bcf7ab271f8487099ad | juandsuarezz/holbertonschool-higher_level_programming | /0x0B-python-input_output/8-load_from_json_file.py | 381 | 4.03125 | 4 | #!/usr/bin/python3
"""Documentation of a load from json file function"""
import json
def load_from_json_file(filename):
"""creates an object from a json file
Arguments:
filename (str): file to load the string
Returns:
JSON object represented by the string
"""
with open(filename) as f:
json_obj = json.load(f)
return json_obj
|
70f828c5a4f4617979fe6125c854d7b180e9c8a8 | harishtm/learningpython | /quick_sort.py | 658 | 4.28125 | 4 | import sys
def quick_sort(array):
array_length = len(array)
if array_length <= 1:
return array
else:
pivot = array[0]
greater = [element for element in array[1:] if element > pivot]
lesser = [element for element in array[1:] if element <= pivot]
return quick_sort(lesser) + [pivot] + quick_sort(greater)
if __name__ == "__main__":
if sys.version_info.major < 3:
input_function = raw_input
else:
input_function = input
user_input = input_function("Enter number seperated by comma : ")
unsorted = [int(item) for item in user_input.split(',')]
print quick_sort(unsorted)
|
c400e001b057ad2daca11d8eb29e2326d624d44c | jasonluocesc/LeetCode | /Solution/14_LongestCommonPrefix.py | 845 | 3.65625 | 4 | class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
strs.sort(key=len)
if len(strs[0]) == 0:
return ""
if len(strs) == 1:
return strs[0]
first = strs[0]
last = strs[-1]
length = len(first)
i=0
while i<length:
if first[i]==last[i]:
for str in strs:
if str[i] == first[i]:
pass
else:
return first[0:i]
i+=1
else:
return first[0:i]
return first[0:i]
strs_1 = ["abab","aba","abc"]
#strs_1.sort(key=len)
#print(strs_1)
print(Solution().longestCommonPrefix(strs_1))
|
7741b75d914b23e80bfe789b667e1a44ff578a7a | christophgockel/tictactoe | /test_player.py | 1,148 | 3.53125 | 4 | from unittest import TestCase
from mock import Mock
from player import Player, PlayerO, PlayerX
from board import make_board
class TestPlayer(TestCase):
def test_player_has_symbol(self):
o = Player(Player.O)
x = Player(Player.X)
self.assertEqual(Player.O, o.symbol)
self.assertEqual(Player.X, x.symbol)
def test_has_convenience_factory_functions(self):
self.assertEqual(Player.O, PlayerO().symbol)
self.assertEqual(Player.X, PlayerX().symbol)
def test_can_provide_next_move_with_input_object(self):
player_input = Mock()
player_input.next_move = Mock(return_value=2)
player = PlayerX(player_input)
self.assertEqual(2, player.next_move())
player_input.next_move.assert_called()
def test_player_inputs_next_move_is_called_with_players_symbol_and_current_board(self):
board = Mock()
player_input = Mock()
player_input.next_move = Mock(return_value=2)
player = PlayerX(player_input)
self.assertEqual(2, player.next_move(board))
player_input.next_move.assert_called_with(player.symbol, board)
|
cf0c72d92d72bbdefc08b922a1b5c4893932cfe8 | Shalom5693/Data_Structures | /Recursion/ProductSUM.py | 192 | 3.765625 | 4 | def productSum(array,m=1):
# Write your code here.
sum = 0
for element in array:
if type(element) is list:
sum += productSum(element,m+1)
else :
sum += element
return sum * m
|
69e9c2b46842145279e4f3b4c82be222f522d632 | arotanskiy/Homeworks | /P110_exam.py | 2,702 | 3.6875 | 4 | """
This module generates an address for delivery service with random street, build and flat numbers
"""
import random
import json
import re
streets_file = 'py110_exam_base.json' # source file with country, city and streets
def test_mode(*args):
"""
This function to use test mode
:param args:
:return:
"""
def verify_street_format(generate_address):
"""
This is a wrapper for a function
:param generate_address:
:return: result of wrapper
"""
def wrapper():
"""
This function check a validity of street spelling
:return: generated address or an assert if street spelling is wrong
"""
if len(args) == 0:
pattern1 = '.+\n' # check "enter" at the end of line
pattern2 = '.+,.+' # check there is no "," symbol
result = generate_address().send(None)
if re.fullmatch(pattern1 and pattern2, result[2]) and type(result[2]) is str:
print('Street format is not valid!')
raise AssertionError('"{}" street format is not valid!'.format(result[2]))
else:
return result
else:
result = generate_address().send(None)
param = str(args[0])
if re.findall(param, result[0]) or re.findall(param, result[1]) or re.findall(param, result[2]):
result = 'Generated address "{}" matches a template "{}"'.format(result, param)
return result
else:
return result
return wrapper
return verify_street_format
def get_random_address():
"""
This function read a json file and extract country, city, and street
:return: country, city, and street
"""
with open(streets_file, 'r', encoding='utf-8') as f:
file = json.load(f)
country = random.choice(file.get("country"))
city = random.choice(file.get("city"))
street = random.choice(file.get("street"))
return country, city, street
@test_mode("переулок") # This is a test mode
# @test_mode() # This is a default mode to generate address
def generate_address():
"""
This function generates a random house and flat and get country, city, street
:return: country, city, street, house, flat
"""
while True:
house = random.randint(1, 50)
flat = random.randint(1, 230)
country, city, street = get_random_address()
yield country, city, street, house, flat
if __name__ == "__main__":
for i in range(4):
print(generate_address())
|
44b99118b4faca2060bbd5c5a07833d89a2c5663 | mohanad1996/GraduationProject | /length_review.py | 407 | 3.625 | 4 | import csv
def get_avg_len():
length=0
count=0
with open('C:/Users/admin/PycharmProjects/Graduation-Project/Output.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
length+=len(row[2])
#print(len(row[2]))
#print(row[2])
count+=1
result=length/count
print(length/count)
return result
|
6d17efae48c109b50faae5158dfb8fe51586deeb | mayflower6157/Leetcode | /1089.Duplicate zeros/solution.py | 674 | 3.6875 | 4 | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
n = len(arr)
raw_arr = arr.copy() # Assignment don't create a new list
duplicated_arr = []
for i in range(n):
if (len(duplicated_arr) >= n):
for j in range(i, n):
arr[j] = duplicated_arr[j]
return
if (raw_arr[i] != 0):
duplicated_arr.append(raw_arr[i])
else:
duplicated_arr.append(0)
duplicated_arr.append(0)
arr[i] = duplicated_arr[i]
|
4f854135a950b1cc355926629972f5c038aa39f4 | shanminlin/Cracking_the_Coding_Interview | /chapter-10/11_peaks_and_valleys.py | 436 | 4.0625 | 4 | """
Chapter 10 - Problem 10.11 - Peaks and Valleys
Problem:
In an array of integers, a "peak" is an element which is greater than or equal to the adjacent integers and
a "valley" is an element which is less than or equal to the adjacent integers. For example, in the array
{5, 8, 6, 2, 3, 4, 6}, {8, 6} are peaks and {5, 2} are valleys. Given an array of integers, sort the array
into an alternating sequence of peaks and valleys.
"""
|
9b061c9fe9c44c2916fafa917b4b949d11acd3c5 | torothin/Bookstore_python | /BradsBookStore.py | 6,912 | 4.28125 | 4 | #Brad Duvall
#Book Store App V1 (Attempt to complete prior to performing exercise)
#1/25/17 to 2/6/17 (Estimated 30-40 hours to complete)
#Uses SQLite3 and Tkinter to create an executable bookstore app
#
from tkinter import *
import sqlite3
window=Tk()
window.resizable(0,0)
#Creates the initial database and database table
def create_table():
conn=sqlite3.connect("Bradsbookstore.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (position INTEGER, title TEXT, author TEXT, year INTEGER, isbn INTEGER)")
conn.commit()
conn.close()
#Adds and entry into the bookstore database
def insert():
conn=sqlite3.connect("Bradsbookstore.db")
cur=conn.cursor()
position=max_position()+1
title=e1_value.get()
author=e2_value.get()
year=int(e3_value.get())
isbn=int(e4_value.get())
cur.execute("INSERT INTO store VALUES(?,?,?,?,?)",(position,title,author,year,isbn))
conn.commit()
conn.close()
view()
#Finds the largest value for position. Called by insert()
def max_position():
conn=sqlite3.connect("Bradsbookstore.db")
cur=conn.cursor()
cur.execute("SELECT MAX(position) FROM store")
max_position_value=cur.fetchone()[0]
conn.close()
return max_position_value
#used only for initial library building
def insert2(position,title,author,year,isbn):
conn=sqlite3.connect("Bradsbookstore.db")
cur=conn.cursor()
cur.execute("INSERT INTO store VALUES(?,?,?,?,?)",(position,title,author,year,isbn))
conn.commit()
conn.close()
view()
#Grabs and inserts all the books stored in the database.
#Also updates position (book number) to ensure continuity for the position values
def view():
conn=sqlite3.connect("Bradsbookstore.db")
cur=conn.cursor()
cur.execute("SELECT * FROM store")
i=1
for rows in cur.fetchall():
cur.execute("UPDATE store SET position=? WHERE isbn=?",(i,rows[4]))
i+=1
cur.execute("SELECT * FROM store")
text_window.delete(0,END)
for item in cur.fetchall():
text_window.insert(END,item)
conn.commit()
conn.close()
#deletes a book entry based on Listbox selection
def delete():
conn=sqlite3.connect("Bradsbookstore.db")
cur=conn.cursor()
cur.execute("DELETE FROM store WHERE position=?",(text_window.get(ACTIVE)[0],))
conn.commit()
conn.close()
view()
#Function to update information for a book stored in the database based on Listbox selection
def update():
conn=sqlite3.connect("Bradsbookstore.db")
cur=conn.cursor()
if e1_value.get()=="":
update_title=cur.execute("SELECT title FROM store WHERE position=?",(text_window.get(ACTIVE)[0],)).fetchone()[0]
else:
update_title=e1_value.get()
if e2_value.get()=="":
update_author=cur.execute("SELECT author FROM store WHERE position=?",(text_window.get(ACTIVE)[0],)).fetchone()[0]
else:
update_author=e2_value.get()
if e3_value.get()=="":
update_year=cur.execute("SELECT year FROM store WHERE position=?",(text_window.get(ACTIVE)[0],)).fetchone()[0]
else:
update_year=e3_value.get()
if e4_value.get()=="":
update_isbn=cur.execute("SELECT isbn FROM store WHERE position=?",(text_window.get(ACTIVE)[0],)).fetchone()[0]
else:
update_isbn=e4_value.get()
cur.execute("UPDATE store SET title=?, author=?, year=?, isbn=? WHERE position=?", (update_title,update_author,update_year,update_isbn,text_window.get(ACTIVE)[0]))
conn.commit()
conn.close()
view()
#performs a search on one entry only, multiple entries will be prioritized by entry position (Title, Author,Year, or ISBN)
def search():
conn=sqlite3.connect("Bradsbookstore.db")
cur=conn.cursor()
cur.execute("SELECT * FROM store")
text_window.delete(0,END)
if e1_value.get()!="":
for rows in cur.fetchall():
if e1_value.get()==rows[1]:
text_window.insert(END,rows)
elif e2_value.get()!="":
for rows in cur.fetchall():
if e2_value.get()==rows[2]:
text_window.insert(END,rows)
elif e3_value.get()!="":
for rows in cur.fetchall():
if int(e3_value.get())==rows[3]:
text_window.insert(END,rows)
elif e4_value.get()!="":
for rows in cur.fetchall():
if int(e4_value.get())==rows[4]:
text_window.insert(END,rows)
conn.close()
create_table()
#inputs
l1=Label(window, text="Title")
l1.grid(row=0, column=0)
e1_value=StringVar()
e1=Entry(window, textvariable=e1_value)
e1.grid(row=0, column=1)
l2=Label(window, justify="right", text="Author")
l2.grid(row=0, column=2)
e2_value=StringVar()
e2=Entry(window, textvariable=e2_value)
e2.grid(row=0, column=3)
l3=Label(window,text="Year")
l3.grid(row=1, column=0)
e3_value=StringVar()
e3=Entry(window, textvariable=e3_value)
e3.grid(row=1, column=1)
l4=Label(window,text="ISBN")
l4.grid(row=1, column=2)
e4_value=StringVar()
e4=Entry(window, textvariable=e4_value)
e4.grid(row=1, column=3)
#command buttons
b1=Button(window, text="View All", command=view, width=15)
b1.grid(row=2, column=5)
b2=Button(window, text="Search Entry", command=search, width=15)
b2.grid(row=3, column=5)
b3=Button(window, text="Add Entry", command=insert, width=15)
b3.grid(row=4, column=5)
b4=Button(window, text="Update Selected", command=update, width=15)
b4.grid(row=5, column=5)
b5=Button(window, text="Delete Selected", command=delete, width=15)
b5.grid(row=6, column=5)
b6=Button(window, text="Close", command=quit, width=15)
b6.grid(row=7, column=5)
#Text Box
scroll_bar=Scrollbar(window, orient="vertical")
text_window=Listbox(window, yscrollcommand=scroll_bar.set,height=10, width=60)
text_window.grid(row=2,column=0, rowspan=6, columnspan=4)
scroll_bar.config(command=text_window.yview)
scroll_bar.grid(row=2,column=4,rowspan=6,sticky="NS")
# #Initial database build
# insert2(1,"The Stand","Steven King","2012","0307947300")
# insert2(2,"IT","Steven King","2016","1501142976")
# insert2(3,"Dark Tower","Steven King","2016","1501143514")
# insert2(4,"Heart of Atlantas","Steven King","2000","0671024248")
# insert2(5,"What You Break","Reed Farrel Coleman","2017","0399173048")
# insert2(6,"A Separation: A Novel","Katie Kitamura","2017","0399576101")
# insert2(7,"A Piece of the World: A Novel","Christina Baker Kline","2017","0062356267")
# insert2(8,"1984","George Orwell","1950","0451524934")
# insert2(9,"Fahrenheit 451","Ray Bradbury","2012","1451673310")
# insert2(10,"Catch-22: 50th Anniversary Edition","Joseph Heller","2011","1451626657")
# insert2(11,"The Catcher in the Rye","J.D. Salinger","1991","0316769487")
# insert2(12,"Of Mice and Men","John Steinbeck","1991","0140177396")
view()
window.mainloop()
|
87dcd996c0fdf037719fbff5a9f82d5598ca6b13 | dishamisal/LeetCode | /Shuffle-the-Array.py | 658 | 3.609375 | 4 | # Problem:
# Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
# Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Solution:
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
final = []
parts = len(nums) / n
import numpy as np
split_list = np.array_split(nums, parts)
# print(split_list[0])
# print(split_list[1])
# print(split_list[0][0])
for one, two in zip(split_list[0], split_list[1]):
# print(one, two)
final.append(one)
final.append(two)
print(final)
return(final)
|
ed751fd6a5664c1a954ad4b54b1a681fe5b1285d | rafaelperazzo/programacao-web | /moodledata/vpl_data/107/usersdata/260/52354/submittedfiles/questao3.py | 265 | 3.578125 | 4 | # -*- coding: utf-8 -*-
p=int(input("digite o valor de p: "))
q=int(input("digite o valor de q: "))
dp=0
dq=0
for i in range(1,q*p,1):
if q%i==0:
dq=dq+1
if p%i==0:
dp=dp+1
if dp==2 and dq==2 and q==p+2 :
print("S")
else:
print("N")
|
25009cc18729f29b77d0a5f91b9a2ee9623a6404 | Tiago1704/VariosPython | /QS con Pila.py | 1,004 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 22 02:05:17 2018
@author: Tiago Ibacache
"""
import P
def quicksortConLista (pila, izq, der):
pila = P.Pila()
P.crearpila(pila)
i = izq
d = der
med = pila[(izq + der)/2]
while (i <= d):
while pila[i] < med and d <= der:
i = i + 1
while med < pila[i] and d >= izq:
d = d - 1
if i<=d:
aux = pila[i]; pila[i] = pila[d]; pila[d] = aux;
i = i + 1; d = d - 1;
if izq < d:
quicksort(pila, izq, d)
if i < der:
quicksort(pila, i, der)
def imprimirQS (P, tam):
P.mostrar_pila(pila)
def leePila():
pila = []
cantN = int (raw_input("Cantidad de numeros a ingresar: "))
for i in range (0, cantN):
pila.append(int(raw_input("Ingrese el numero %d: ") % i))
return pila
A = leepila()
quicksort(A, 0, len(A)-1)
imprimeQS(A, len(A)) |
70713f4fecb95092cf6bdc8bb6dc1a0502554e63 | ramkishorem/pythonic | /session3_list_loop/19.py | 404 | 3.671875 | 4 | """
Drill 5: MyVengers
> Create myvengers = ['Thor','Iron Man','Black widow','Hawkeye']
> create a copy called yourvengers
> replace yourvengers elements with your favourites, you may
add more too
> Compare elements of myvengers and yourvengers and
make sure they are different.
> Print lasted 2 Avengers on my list and then yours
> List your Avengers one by one with a serial number using loop
""" |
52d6aaf1b6f38bf00968ce27cdbdd24fb75fe87f | rohitdanda/MachineLearning | /DataProcessing.py | 1,403 | 3.5 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plot
from sklearn.preprocessing import Imputer
from sklearn.preprocessing import LabelEncoder,OneHotEncoder,StandardScaler
from sklearn.model_selection import train_test_split
#importing the data from CSV file
datasets = pd.read_csv('Data.csv')
#Setting the pre required Data as x and result from them is y
X = datasets.iloc[:, :-1].values
Y = datasets.iloc[:, 3].values
# Here we preprocess the data finding the NAN vlaue and using mean
imputerData = Imputer(missing_values="NaN",strategy="mean",axis=0)
imputerData = imputerData.fit(X[:,1:3])
X[:,1:3] = imputerData.transform(X[:,1:3])
#Encoding the value to binary data
labelEncoder_X = LabelEncoder()
X[:,0]=labelEncoder_X.fit_transform(X[:,0])
labelEncoder_Y = LabelEncoder()
Y = labelEncoder_Y.fit_transform(Y);
# After Label Encoder we have to make Dummy Encoder we use OneHOtEncoder
oneHotEncoder_X = OneHotEncoder(categorical_features = [0])
X = oneHotEncoder_X.fit_transform(X).toarray()
# SPlitting the Data Sets in to Training Sets and Test sets
X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.25,random_state=5)
# feature Scaling the data so that values between them wont differ long
X_sandardScaler = StandardScaler()
X_train = X_sandardScaler.fit_transform(X_train)
X_test = X_sandardScaler.transform(X_test) |
bf08bde0df8f7e9f417f71246ffca5263ee119c5 | rafz10/scripts20181 | /Lista 10 - Funções/Teste Numero Primo.py | 223 | 3.734375 | 4 | def primo(n):
'''
Metodo para checar se é primo
'''
for i in range(2,n):
if n % i == 0 :
print ('Não é primo')
break
else:
print('È primo')
primo(8)
|
1093ec614de401ce2dc148f8964c63b6e77bf5f2 | saurabhwasule/python-practice | /Nice_training_material/core_python_hands-final/mytest.py | 430 | 3.546875 | 4 | from pkg.MyInt import MyInt
import unittest
class MyTest(unittest.TestCase):
def test_add(self):
"""Testing addition functionality"""
a = MyInt(2)
b = MyInt(3)
c = a + b
self.assertEqual(c, MyInt(5))
def test_less(self):
"""Testing less functionality"""
a = MyInt(2)
b = MyInt(3)
#self.assertLess(a,b)
self.assertEqual(a<b, False) |
9a9b87db301eb76a2614f69ee019517858e626c5 | davidm3591/Code-Cheats-Settings | /python/code_hints_tips/python_str_vs_repr.py | 810 | 3.953125 | 4 | # ######################################################################
#
# Python str() vs repr()
#
# ######################################################################
def brk_ln():
print("")
# ### str() vs repr() ### #
# Example 1 of str()
str_intro = "Example 1 of str()"
print(str_intro)
s = "Hello, Geeks."
print(str(s))
print(str(2.0 / 11.0))
brk_ln()
# Example 1 of repr()
repr_intro = "Example 1 of repr()"
print(repr_intro)
s = "Hello, Geeks."
print(str(s))
print(str(2.0 / 11.0))
# -----------------------------------
brk_ln()
# Example 2 of str()
import datetime
today = datetime.datetime.now()
str_intro = "Example 2 of str()"
print(str_intro)
print(str(today))
brk_ln()
# Example 2 of repr()
repr_intro = "Example 2 of repr()"
print(repr_intro)
print(repr(today))
|
4e16314b882b6417273982a89b874561fbd4a351 | Aleksey-Bykov1/Python_algorithms | /lesson_3_home_work.py | 7,640 | 4.125 | 4 | # -------------------------------------------- 1 ----------------------------------------------------
''' 1. В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне
от 2 до 9.'''
# Без использования словаря
n = list(range(2, 100))
multiples_2 = 0
multiples_3 = 0
multiples_4 = 0
multiples_5 = 0
multiples_6 = 0
multiples_7 = 0
multiples_8 = 0
multiples_9 = 0
for i in n:
if i % 2 == 0:
multiples_2 += 1
if i % 3 == 0:
multiples_3 += 1
if i % 4 == 0:
multiples_4 += 1
if i % 5 == 0:
multiples_5 += 1
if i % 6 == 0:
multiples_6 += 1
if i % 7 == 0:
multiples_7 += 1
if i % 8 == 0:
multiples_8 += 1
if i % 9 == 0:
multiples_9 += 1
print(f'{multiples_2 = }')
print(f'{multiples_3 = }')
print(f'{multiples_4 = }')
print(f'{multiples_5 = }')
print(f'{multiples_6 = }')
print(f'{multiples_7 = }')
print(f'{multiples_8 = }')
print(f'{multiples_9 = }')
# С использованием словаря
multiples = dict.fromkeys(range(2, 10), 0)
for i in range(2, 100):
for j in range(2, 10):
if i % j == 0:
multiples[j] += 1
for key in multiples:
print(f'{key} кратны {multiples[key]} чисел')
# -------------------------------------------- 2 ----------------------------------------------------
''' 2. Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан массив
со значениями 8, 3, 15, 6, 4, 2, то во второй массив надо заполнить значениями 1, 4, 5, 6
(или 0, 3, 4, 5 - если индексация начинается с нуля), т.к. именно в этих позициях первого массива стоят
четные числа.'''
n = [int(i) for i in input("Введите несколько чисел через пробел: ").split()]
index_n = []
for i in range(len(n)):
if n[i] % 2 == 0:
index_n.append(i)
print(f'Номера четных индексов в списке "n" - {index_n}')
# -------------------------------------------- 3 ----------------------------------------------------
''' 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.'''
from random import randint as rnd
n = [rnd(1, 100) for i in range(rnd(17, 29))]
print(n)
max_ind, max_val = 0, 0
min_ind, min_val = 0, 99999999999
for ind, val in enumerate(n):
if val > max_val:
max_ind, max_val = ind, val
elif val < min_val:
min_ind, min_val = ind, val
print(f'{min_ind = }, {min_val = }, {max_ind = }, {max_val = }')
n[min_ind] = max_val
n[max_ind] = min_val
print(n)
# -------------------------------------------- 4 ----------------------------------------------------
''' 4. Определить, какое число в массиве встречается чаще всего.'''
from random import randint as rnd
n = [rnd(1, 100) for i in range(rnd(42, 58))]
print(n)
count_n = 0
num = 0
for i in n:
if n.count(i) > count_n:
count_n = n.count(i)
num = i
print(f'Наибольшее число повторений - {count_n}, у числа - {num}')
# -------------------------------------------- 5 ----------------------------------------------------
''' 5. В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и позицию (индекс)
в массиве.'''
from random import randint as rnd
n = [rnd(-100, 100) for i in range(rnd(27, 42))]
print(n)
max_neg_n = -float('inf')
for ind, val in enumerate(n):
if val < 0 and val > max_neg_n:
max_neg_n = val
ind_n = ind
print(f'Максимальное минимальное число в списке: {max_neg_n}, значение индекса {ind_n}')
# -------------------------------------------- 6 ----------------------------------------------------
''' 6. В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами.
Сами минимальный и максимальный элементы в сумму не включать.'''
from random import randint as rnd
n = [rnd(1, 100) for i in range(rnd(24, 38))]
print(n)
max_ind, max_val = 0, 0
min_ind, min_val = 0, 99999999999
for ind, val in enumerate(n):
if val > max_val:
max_ind, max_val = ind, val
elif val < min_val:
min_ind, min_val = ind, val
print(f'{min_ind = }, {min_val = }, {max_ind = }, {max_val = }')
if min_ind < max_ind:
print('Сумма элементов между максимальным и минимальным = ', sum(n[min_ind + 1 : max_ind]))
else:
print('Сумма элементов между максимальным и минимальным = ', sum(n[max_ind + 1: min_ind]))
# -------------------------------------------- 7 ----------------------------------------------------
''' 7. В одномерном массиве целых чисел определить два наименьших элемента. Они могут быть как равны между
собой (оба являться минимальными), так и различаться. '''
from random import randint as rnd
n = [rnd(1, 100) for i in range(rnd(23, 44))]
print(n)
min_num = n[0]
min_num_2 = n[1]
for i in n:
if i < min_num:
min_num_2 = min_num
min_num = i
elif i < min_num_2:
min_num_2 = i
print(f'Минимальное число {min_num}, второе минимальное число {min_num_2}')
# -------------------------------------------- 8 ----------------------------------------------------
''' 8. Матрица 5x4 заполняется вводом с клавиатуры кроме последних элементов строк. Программа должна вычислять
сумму введенных элементов каждой строки и записывать ее в последнюю ячейку строки. В конце следует вывести
полученную матрицу.'''
str_n = 4
col_n = 4
a = [[int(input('Введите числа для списка: ')) for i in range(col_n)] for j in range(str_n)]
for i in range(len(a)):
a[i].append(sum(a[i]))
print('Итоговая матрица')
for i in a:
for j in i:
print(f'{j:>8}', end='')
print()
# -------------------------------------------- 9 ----------------------------------------------------
''' 9. Найти максимальный элемент среди минимальных элементов столбцов матрицы.'''
from random import randint as rnd
S = 8
C = 6
a = [[int(rnd(1, 100)) for _ in range(C)] for _ in range(S)]
min_col = float('inf')
max_min = -float('inf')
for i in a:
for j in i:
print(f'{j:>4}', end='')
print()
for j in range(C):
for i in range(S):
if a[i][j] < min_col:
min_col = a[i][j]
if min_col > max_min:
max_min = min_col
print("Максимальный среди минимальных: ", max_min)
|
e70e63a99989cd4a11b56fa5ace40fa9027387d4 | jphafner/project-euler | /euler_004.py | 727 | 4.3125 | 4 | #!/usr/bin/env python
"""
A palindromic number reads the same both ways. The largest palildrome made
from the product of two 2-digit numbers is 9009 = 91 x 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
import sys
from numpy import sqrt
def orig():
"""
My original solution to this problem.
"""
p = 0
n = str(p)
for i in range(100,1000):
for j in range(i,1000):
n = str(i*j)
if n==n[::-1]:
p = max(p,int(n))
return p
def main():
"""
Print the largest palidrome made from the product of two 3-digit numbers.
"""
print "largest palidrome is ",orig()
if __name__ == "__main__":
sys.exit(main())
|
1ebfe11587081abb883c0d02ff651dbaa9e218c8 | bes-1/lessons_python | /dz_4_4_berezin.py | 145 | 3.65625 | 4 | begin_list = [1, 5, 5, 6, 15, 4, 4, 4, 23, 12, 12, 3, 4]
answer_list = [el for el in begin_list if begin_list.count(el) < 2]
print(answer_list)
|
53ad2d65583f075e8d4b1e825c079d75bf4c0abd | roctbb/GoTo-Start-2017 | /Lesson 1/bw_dog.py | 617 | 3.5 | 4 | from PIL import Image
file = input("введите имя картинки:")
im = Image.open(file)
pixels = im.load()
for i in range(im.width//2):
for j in range(im.height):
r, g, b = pixels[i, j]
S = (r+g+b)//3
if S < 100:
pixels[i, j] = (255,255,255)
else:
pixels[i, j] = (0,125,125)
for i in range(im.width//2, im.width):
for j in range(im.height):
r, g, b = pixels[i, j]
S = (r+g+b)//3
if S < 100:
pixels[i, j] = (255,255,255)
else:
pixels[i, j] = (125,125,0)
im.show()
im.save("result.jpg") |
1febdb5fe1371bae2a608f450da740926bca3afd | hsuBnOediH/AlgoExpert | /getYoungestCommonAncestor.py | 1,472 | 3.53125 | 4 | # This is an input class. Do not edit.
class AncestralTree:
def __init__(self, name):
self.name = name
self.ancestor = None
def getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo):
a_set = set()
cur = descendantOne
while cur is not None:
a_set.add(cur.name)
cur = cur.ancestor
cur = descendantTwo
while cur is not None:
if cur.name in a_set:
return cur
else:
cur = cur.ancestor
return topAncestor
# This is an input class. Do not edit.
class AncestralTree:
def __init__(self, name):
self.name = name
self.ancestor = None
def getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo):
d_1 = get_d(topAncestor, descendantOne)
d_2 = get_d(topAncestor, descendantTwo)
cur_1 = topAncestor
cur_2 = descendantOne
diff = d_1 - d_2
if diff != 0:
if d_1 > d_2:
while diff > 0:
cur_1 = cur_1.ancestor
diff -= 1
else:
while diff > 0:
cur_2 = cur_2.ancestor
diff += 1
while cur_1 is not topAncestor:
if cur_1 == cur_2:
return cur_1
else:
cur_1 = cur_1.ancestor
cur_2 = cur_2.ancestor
return topAncestor
def get_d(root, child):
res = 0
cur = child
while cur is not root:
res += 1
cur = cur.ancestor
return res
|
88543273f1431ddc8f12b7462f833274ff4b02a2 | antikytheraton/algorithms | /algorithms/graph.py | 644 | 3.859375 | 4 | '''
Copyright (c) 1998, 2000, 2003 Python Software Foundation.
All rights reserved.
Licensed under the PSF license.
'''
graph = { 'A':['B','C'],
'B':['C','D'],
'C':['D'],
'D':['C'],
'E':['F'],
'F':['C']}
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not start in graph:
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath:
return newpath
return None
print(find_path(graph,'A','D')) |
64482d5db77dd7ccfd43fcc9375c4ec2f2b3a99c | krishnamohan152/Code-Forces | /4A_Watermelon.py | 249 | 3.75 | 4 | #! /usr/bin/env python
# Headers
import sys
# Input
Get_Num = input()
# Main Code
def main(Get_Num):
if int(Get_Num) == 2:
print("NO")
elif int(Get_Num) % 2 == 0:
print("YES")
else:
print("NO")
if __name__ == '__main__':
main(Get_Num) |
a4a2ddf8cca4f927cc1f8e118b4981bb864ba130 | giuschil/Python-Essentials | /python_classes/python.classi_punto_cartesiano.py | 631 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 12 22:40:08 2018
@author: giuschil
"""
#programmazione ad oggetti oop
# voglio creare una classe che crei l'oggetto punto cartesiano
import math
class Punto:
def __init__(self,x,y):
self.x = x
self.y = y
def to_string(self):
return f"({str(self.x)},{str(self.y)})"
def __sub__(self,altro_punto):
cat1 = altro_punto.x -self.x
cat2 = altro_punto.y -self.y
ipo_quadrato = math.pow(cat1,2)+math.pow(cat2,2)
return math.sqrt(ipo_quadrato)
p1 = Punto(18,2)
|
f2809d1aa718fa3c363f14dca8fad47f991ecd49 | shakhobiddin/Python | /Question 4 (sentence).py | 418 | 4.15625 | 4 | #Take the users input
words = input("Enter your sentence to translate to pig latin: ")
print ("You entered: ", words)
#Now I need to break apart the words into a list
words = words.split(' ')
#Now words is a list, so I can take each one using a loop
k=""
for i in words:
if len(i) >=0 :
i = i + "%say" % (i[0].lower())
i = i[1:]
k+=str(i)+" "
else:
print ("empty")
print(k)
|
3c398626e2fdf939f7d15dd2c17caaa2a9baed70 | anipshah/geeksforgeeks_problems | /jumpGame.py | 211 | 3.75 | 4 | def jump_game(arr):
n = len(arr)
jump = 0
for i in range(n):
if i > jump:
return False
jump = max(jump, i + arr[i])
return True
arr=[1,3,0,1,2]
print(jump_game(arr))
|
89fab55233c379ea166239057ee496ecfcdfdc61 | praveendk/programs | /loops/forLoopRange.py | 82 | 3.5625 | 4 | # practise for loop range
for x in range(10):
if x == 6:
continue
print(x) |
12103863497d5642cd9f399503878567ed17bc08 | PARKJUHONG123/turbo-doodle | /MOST_USAGE/SORT.py | 4,327 | 3.765625 | 4 | def bubble_sort(arr):
# time = O(n^2)
# space = O(n)
# In-place Sort (다른 메모리 공간 필요 X length 안에서만 해결 가능)
# Stable Sort (같은 값의 순서가 바뀌지 않음)
length = len(arr)
for i in range(length):
for j in range(1, length - i):
if arr[j - 1] > arr[j]:
temp = arr[j - 1]
arr[j - 1] = arr[j]
arr[j] = temp
print(arr)
def selection_sort(arr):
# time = O(n^2)
# space = O(n)
# In-place Sort
# Unstable Sort (같은 값의 순서가 바뀜)
# [5(1), 4, 5(2), 2] -> [2, 4, 5(2), 5(1)]
length = len(arr)
for i in range(length - 1):
start_index = i
for j in range(i + 1, length):
if arr[j] < arr[start_index]:
start_index = j
temp = arr[start_index]
arr[start_index] = arr[i]
arr[i] = temp
print(arr)
def insertion_sort(arr):
# worst & ave time = O(n^2)
# best time = O(n)
# space = O(n)
# In-place Sort
# Stable Sort
length = len(arr)
for i in range(length):
temp = arr[i]
prev = i - 1
while prev >= 0 and arr[prev] > temp:
arr[prev + 1] = arr[prev]
prev -= 1
arr[prev + 1] = temp
print(arr)
def partition(arr, left, right):
pivot = arr[left]
i, j = left, right
while i < j:
while pivot < arr[j]:
j -= 1
while i < j and pivot >= arr[i]:
i += 1
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
arr[left] = arr[i]
arr[i] = pivot
return i
def quick_sort(arr, left, right):
# JAVA : Arrays.sort() Java 7부터 Dual Pivot Quick Sort
# worst time = O(n^2)
# ave & best time = O(n * log(n))
# space = O(n)
# In-place Sort
# Unstable Sort
if left >= right:
return
pivot = partition(arr, left, right)
quick_sort(arr, left, pivot)
quick_sort(arr, pivot + 1, right)
def merge(arr, left, mid, right):
L, R = arr[left : mid + 1], arr[mid + 1 : right + 1]
l_length, r_length = len(L), len(R)
i, j, k = 0, 0, left
while i < l_length and j < r_length:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < l_length:
arr[k] = L[i]
k, i = k + 1, i + 1
while j < r_length:
arr[k] = R[j]
k, j = k + 1, j + 1
def merge_sort(arr, left, right):
# time : O(n * log(n))
# Not In-Place Sort
# Stable Sort
if left < right:
mid = (left + right) // 2
merge_sort(arr, left, mid)
merge_sort(arr, mid + 1, right)
merge(arr, left, mid, right)
def heapify(arr, length, i):
parent, left, right = i, i * 2 + 1, i * 2 + 2
if left < length and arr[parent] < arr[left]:
parent = left
if right < length and arr[parent] < arr[right]:
parent = right
if i != parent:
temp = arr[parent]
arr[parent] = arr[i]
arr[i] = temp
heapify(arr, length, parent)
def heap_sort(arr):
# time : O(n * log(n))
# Unstable Sort
length = len(arr)
for i in reversed(range(length // 2)):
heapify(arr, length, i)
for i in reversed(range(length)):
temp = arr[i]
arr[i] = arr[0]
arr[0] = temp
heapify(arr, i, 0)
print(arr)
def count_sort(arr, n, exp):
buffer = [0 for _ in range(n)]
count = [0 for _ in range(10)]
for i in range(n):
count[(arr[i] // exp) % 10] += 1
for i in range(1, 10):
count[i] += count[i - 1]
for i in reversed(range(n)):
index = (arr[i] // exp) % 10
buffer[count[index] - 1] = arr[i]
count[index] -= 1
for i in range(n):
arr[i] = buffer[i]
def radix_sort(arr):
length = len(arr)
m = max(arr)
exp = 1
while m / exp > 0:
count_sort(arr, length, exp)
exp *= 10
print(arr)
bubble_sort([3, 2, 4, 7, 5, 1])
selection_sort([3, 2, 4, 7, 5, 1])
insertion_sort([3, 2, 4, 7, 5, 1])
arr = [3, 2, 4, 7, 5, 1]
quick_sort(arr, 0, 5)
print(arr)
arr = [3, 2, 4, 7, 5, 1]
merge_sort(arr, 0, 5)
print(arr)
heap_sort([3, 2, 4, 7, 5, 1])
radix_sort([3, 2, 4, 3, 7, 5, 1]) |
4579f3237510f36d057d7f0e28a74d9a6b6437e0 | taech-95/python | /Beginner/PasswordGenerator.py | 1,372 | 3.796875 | 4 | import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
nr_letters=int(input("How many letters do you want in your password\n"))
nr_numbers=int(input("How many numbers do you want in your password\n"))
nr_symbols=int(input("How many symbols do you want in your password\n"))
# randomLetters = random.choice(letters)
# randomNumbers=random.choice(numbers)
# randomSymbols=random.choice(symbols)
# print(nr_letters)
# print(type(nr_letters))
passwordTemplate=[]
# counter=0
for i in range(nr_letters):
passwordTemplate+=random.choice(letters)
for i in range(nr_numbers):
passwordTemplate+=random.choice(numbers)
for i in range(nr_symbols):
passwordTemplate+=random.choice(symbols)
# passwordTemplate=passwordTemplate+randomLetters
# print(passwordTemplate)
# counter+=1
# if(counter==int(nr_letters)):
# break
# print(passwordTemplate)
random.shuffle(passwordTemplate)
password=""
# print(passwordTemplate)
for i in passwordTemplate:
password+=i
print(f"Your password is {password}") |
3ce584840840749a9c99808e070729ca7c95929b | Adefreit/cs110z-f19-t4 | /Lesson 14/list_example_2.py | 706 | 4.09375 | 4 | # Gets # of swimmers from user
num_swimmers = int(input())
# Keeps Track of the Total
total = 0
# List to Hold Swim Times
times = []
# Loop to get all swim times
for i in range(num_swimmers):
# Get Each Individual Time
swim_time = int(input())
# Puts Time in List
times.append(swim_time)
# Updates the Total
total = total + swim_time
# Calculates the Average
average = total / num_swimmers
# Keeps Track of Num Below Avg
total_below_avg = 0
# Loop to Compare Every time to the Avg
for i in range(num_swimmers):
if times[i] > average:
total_below_avg = total_below_avg + 1
# Print the Final Results
print(average)
print(total_below_avg)
|
906f2d82c978e539c757aed0bbbd36823e8f3e1c | ais-climber/notakto-player | /v2_lstm/heatmap.py | 4,329 | 3.640625 | 4 | """
A script for producing a heatmap of a Notakto strategy.
For a given strategy S, we play S in a variety of games.
From these games, we collect the most likely responses
of S to a given move m, and make a heatmap of these responses.
"""
from Board import Board
from FeatureLayeredNet import FeatureLayeredNet
from strategies import *
from generate_boards import *
import tensorflow as tf
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def play_against(N, player_1, player_2):
"""
Plays a single game between player_1 and player_2, on an NxN board.
Returns two lists, one for player_1 and the other for player_2.
Each list consists of
(their, my)
pairs, where 'their' is the move the other player had made, and
'my' is the move this player made in response.
We also return alongside these the winner, so that we can e.g.
filter games that were won by player_1.
"""
board = Board(N)
p1responses = []
p2responses = []
# Player 1 always goes first, by convention.
turn = 0
previous_move = None
while not board.game_over():
# Player #1
if turn == 0:
this_move = player_1(board)
board.update(this_move)
turn = 1
p1responses.append((previous_move, this_move))
previous_move = this_move
# Player #2
elif turn == 1:
this_move = player_2(board)
board.update(this_move)
turn = 0
p2responses.append((previous_move, this_move))
previous_move = this_move
if turn == 0:
winner = "player_1"
elif turn == 1:
winner = "player_2"
return (winner, p1responses, p2responses)
if __name__ == "__main__":
N = 3
num_games = 1000
winning_choice = "player_1"
init = gen_initial_boards(N)
nbhd = neighborhood(init)
flipped = flip_turns(nbhd)
# Initialize net players
fmodel = tf.keras.models.load_model("Models/featnet_model_"+str(N), compile=True)
cmodel = tf.keras.models.load_model("Models/convnet_model_"+str(N), compile=True)
featnet = FeatureLayeredNet(N, training_boards=[], givenModel=fmodel, modelName='featured_convolutional')
convnet = FeatureLayeredNet(N, training_boards=[], givenModel=cmodel, modelName='convolutional')
# Play some games and mark down the feature net's responses
player_responses = []
for i in range(num_games):
print(i)
# Only collect games where greedy won (this reveals its winning strategy)
# Against greedy
winner, p1res, p2res = play_against(N, featnet.next_move, greedy)
#winner, p1res, p2res = play_against(N, greedy, featnet.next_move)
if winner == winning_choice:
player_responses += p1res
# Build up a dictionary mapping:
# possible opponent squares --> possible response positions, with % cases where we respond in this way.
mapping = dict()
for (their, my) in player_responses:
# Initialize if we haven't seen these moves before
if their not in mapping.keys():
mapping[their] = {(x, y) : 0 for x in range(N) for y in range(N)}
# if my not in mapping[their].keys():
# mapping[their][my] = 0
# Increment the number of times we gave this particular response.
mapping[their][my] += 1
# Pretty display the responses to each move as a heat map
print("Displaying and saving figures...")
for move in mapping.keys():
ser = pd.Series(list(mapping[move].values()),
index=pd.MultiIndex.from_tuples(mapping[move].keys()))
df = ser.unstack().fillna(0)
ax = sns.heatmap(df, annot=True, cmap="Blues", cbar=False)
# Draw a red square around the current move
# (we have to flip the coordinates, since the heatmap goes down then right,
# whereas plotting goes right then down.)
if move != None:
rect = plt.Rectangle((move[1], move[0]), 1,1, color="red", linewidth=3, fill=False, clip_on=False)
ax.add_patch(rect)
plt.axes().set_title("In Response to " + str(move))
plt.savefig("Heatmaps/heatmap_" + str(N) + "x" + str(N) + "_response_to_" + str(move) + ".png")
plt.show()
|
69f83b91a4c81f5ad15bc904422b9c6c650ea253 | nancydemir/Hackerrank | /hackerDayPrintFunction.py | 148 | 3.59375 | 4 |
if __name__ == '__main__':
x = 0
n = int(input())
for i in range(0,n):
print(x + 1,end = "")
x += 1
|
04bc869ae553c647f72354c0c68873d94177cd52 | timid-one/cs-115 | /Notes/traceAndBinExercise.py | 3,439 | 3.828125 | 4 | # two-part exercise
from cs115 import map
'''
Part 0
Here is a memoized version of edit distance.
Your task: make it trace the calls to fastED_help, indented
according to recursion depth. Hint: add a parameter to fastED_help.
'''
def fastED(first, second):
'''Returns the edit distance between the strings first and second. Uses
memoization to speed up the process.'''
depth = 0
memo = {}
def fED (first, second, depth):
if first == '' or second == '':
depth += 1
print(depth * ' ' + str((first, second)))
if second == '':
return len(first)
return len(second)
elif (first, second) in memo:
depth += 1
print(depth * ' ' + str((first, second)))
return memo[(first, second)]
elif first[0] == second[0]:
depth += 1
answer = fED(first[1:], second[1:], depth)
memo[(first, second)] = answer
print(depth * ' ' + str((first, second)))
return answer
else:
depth += 1
substitution = 1 + fED(first[1:], second[1:], depth)
deletion = 1 + fED(first[1:], second, depth)
insertion = 1 + fED(first, second[1:], depth)
answer = min(substitution, deletion, insertion)
memo[(first, second)] = answer
print(depth * ' ' + str((first, second)))
return answer
return fED(first, second, depth)
'''
Part 1
Complete the following function. You may use the functions
numToBinary and increment from lab 6, provided below.
Start by sketching your design in psuedo-code.
'''
def numToTC(N):
'''Assume N is an integer.
If N can be represented in 8 bits using two's complement, return
that representation as a string of exactly 8 bits.
Otherwise return the string 'Error'.
'''
if N > 127 or N < -128:
return 'Error'
elif N >= 0:
return (8 - len(numToBinary(N))) * str(0) + numToBinary(N)
else:
N = N * -1
'''
Examples:
NumToTc(1) ---> '00000001'
NumToTc(-128) ---> '10000000'
NumToTc(200) ---> 'Error'
'''
def numToBinary(N):
'''Assuming N is a non-negative integer, return its base 2
representation as a string of bits.'''
if N == 0:
return ''
if isOdd(N):
return numToBinary(N//2) + '1'
else:
return numToBinary(N//2) + '0'
def increment(s):
'''Assuming s is a string of 8 bits, return the binary representation
of the next larger number takes an 8 bit string of 1's and 0's and
returns the next largest number in base 2'''
num = binaryToNum(s) + 1
if num == 256:
return '00000000'
zeros = (len(s)-len(numToBinary(num))) * '0'
return zeros + numToBinary(num)
def binaryToNum(s):
'''Assuming s is a string of bits, interpret it as an unsigned binary
number and return that number (as a python integer).
'''
def binaryToNumHelp(s, index):
if s == '':
return 0
elif s[0] == '0':
index -= 1
return 0 + binaryToNumHelp(s[1:], index)
else:
index -= 1
return 2**index + binaryToNumHelp(s[1:], index)
return binaryToNumHelp(s, len(s))
def isOdd(n):
'''returns whether a number is odd or not'''
if n % 2 == 0:
return False
else:
return True
|
f82fbcb63e59ca54da9df7d38fd9d87e4fe6195b | khuang110/CS-362-Homework-4 | /name.py | 318 | 3.671875 | 4 | # Make a full name as input to run unit test on
# By: Kyle Huang
def name(first, last):
if not isinstance(first, str) or not isinstance(last, str):
raise TypeError("Does not contain string")
else:
return first + " " + last
if __name__=="__main__":
print(name("Kyle", "Huang"))
|
e2a4d88c5f532a900ec2121d564394acdb4cc9ed | Sumyak-Jain/Python-for-beginners | /while_0.py | 96 | 3.671875 | 4 | a=int(input("enter a number"))
i=1;
while i<11:
print("%d X %d = %d" % (a,i,a*i))
i=i+1
|
ca6f62f9010d790b4ffbb1a14c80e4b6a599cf06 | kaobeosolu78/Practice_Projects | /Project_Euler_Problems/Factorial Sum.py | 322 | 3.6875 | 4 | def factorial(n):
fact = 1
for k in range(0,n+1):
if n == 0:
return 1
elif k != n:
fact *= (n-k)
return (fact)
fact_100 = str(factorial(100))
answer = 0
hold = []
for k in fact_100:
hold.append(int(k))
for k in hold:
answer += k
print (answer)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.